Hassan Raza
Hassan Raza

Reputation: 37

After selecting option in dropdown menu append new input field

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

Answers (1)

almcd
almcd

Reputation: 1089

The following should solve your problem. In summary:

  • We select the dropdown element and listen for changes on it, using jQuery's change() method
  • We check if the value selected on the dropdown element matches 'other'
  • If it does, we check if we've already inserted the new input field into the DOM
  • If we haven't, we append the input field using jQuery's appendTo() 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

Related Questions