i’m making a simple dropdown that changes the content according to what is chosen. However, along with erasing the previous content, jquery is also deleting the last dropdown option.
Here is my HTML.
<body>
<h2>Analyze</h2>
<form id="analyze" method="get" action="/results/">
<div id="analyzecontainer">
<p>Search by: </p>
<select id="analyzeselector" class="dropdown" name="analyzeselector">
<option class="dropdownitem" name="select">Select</option>
<option id="byexercisename" class="dropdownitem" name="byexercisename">By Exercise Name </option>
<option id="bydate" class="dropdownitem" name="bydate" value="date">By Date</option>
<option id="byworkoutname" class="dropdownitem" name="byworkoutname" value="workoutname">By Workout Name</option>
</select>
<input id="exercisename" class="textbox required" type="text" name="exercisename" value="Enter Exercise Name">
</div>
<input class="textbox int" type="text" value="How many results" name="numresults">
<input id="submitquery" type="submit">
</form>
</body>
Now here is my Jquery code:
$(document).ready(
function () {
$(document).on("change", "#analyzeselector", function () {
var selected = $(this).find(':selected').attr("name");
if ($("#analyzecontainer :last-child").attr('id') != 'analyzeselector') {
alert($("#analyzecontainer :last-child").attr('id'))
$("#analyzecontainer :last-child").remove()
}
if (selected == 'byexercisename') {
$('<input>').attr({
type: 'text',
id: 'exercisename',
name: 'exercisename',
value: "Enter Exercise Name",
class: "textbox required"
}).appendTo('#analyzecontainer')
}
else if (selected == 'bydate') {
$("#analyzecontainer").datepicker({ dateFormat: "yy-mm-dd" });
}
})
})
Again, every time change my dropdown selection, it deletes the last dropdown option. Thanks guys! Appreciate it.
This line:
Is not doing what you think it’s doing. It’s removing every element underneath
#analyzecontainerthat is the last child of it’s parent. This includes the lastoptionelement in aselect.You could use
:lastto get the last child of the container:Example: http://jsfiddle.net/bthzc/1