user2675939
user2675939

Reputation: 371

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>

Upvotes: 1

Views: 218

Answers (2)

Nikolai Mavrenkov
Nikolai Mavrenkov

Reputation: 1923

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

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

Upvotes: 2

TimoStaudinger
TimoStaudinger

Reputation: 42460

You are appending the button. Replace the old button instead:

 function showFields() {
   // ...

   html = '<button type="button" onClick="location.href=XXX">Download File</button>'
   $('#buttonDownload').html(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>

Upvotes: 1

Related Questions