user2675939 user2675939 - 1 month ago 8
Javascript Question

show and hide based on drop-down selection

I have a drop-down fields that when changed should display a button that can download files based on drop-down selection. The problem is it keeps appending button, so if 1 is selected, it shows 1 button, on selecting another option, it appends another button and so on. So, with every selection, button keeps adding up instead of just showing one 1 button. I tried adding $('#buttondownload').remove(), but its not working properly. Here is the code:



function showFields(this) {
if (this.value == "1" || this.value == "2")
{
download.style.display = "block";
}
if (this.value == "")
{
download.style.display = "none";
}
if (this.value == "1")
{
var file = "'test.pdf";
}
if (this.value == "2")
{
var file = "test2.pdf";
}
html = '<button type="button" onClick="location.href='+ file + '">Download File</button>'
$('#buttonDownload').append(html);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" name="ID" onChange="showFields(this);">
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="download"><div id="buttonDownload"></div></div>




Answer

You need to clear the container before appending a new button:

$('#buttonDownload').empty().append(html);
Comments