Reputation: 37
After selecting 'other' option in dropdown menu, I want a new input field to appear after dropdown menu, but nothing is happening.
<div style="margin-right:20px" id='degree'>
<label for='college_name'>Degree</lable></br>
<select style="width: 400px" class='degree-selected'>
<option>High school</option>
<option>Bachler's degree</option>
<option>Master's degree</option>
<option>Doctor of philosophy (Ph.D)</option>
<option id='hello'>other</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#hello").click(function(){
alert('degree');
$('#degree').append('<div style="margin-right:20px;"><label for="college_name"></lable><input type="text" placeholder=""></div>');
});
});
</script>
Upvotes: 0
Views: 2381
Reputation: 1089
The following should solve your problem. In summary:
change()
methodappendTo()
method$(document).ready(function(){
$('.degree-selected').change(function () {
var selectedItem = $(this).val();
if (selectedItem === 'other') {
if (!$('#other-field').length) {
$('<input type="text" name="other-field" id="other-field">').appendTo('#form');
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='degree'>
<form id="form">
<label for='college_name'>Degree</label>
<select class="degree-selected">
<option value="item-1">High school</option>
<option value="item-2">Bachelor's degree</option>
<option value="item-3">Master's degree</option>
<option value="item-4">Doctor of philosophy (Ph.D)</option>
<option value="other">Other</option>
</select>
</form>
</div>
Upvotes: 4