Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a text field to html dropdown

I have a html dropdown field where there should be a text field added at the bottom naming other.The text typed in this field should come as other:text

drop down html is :

<select name="drop">
    <option selected="selected">Please select ...</option>
    <option value="car">car</option>
    <option value="bike">bike</option>
    <option value="Other">Other</option>
</select>

Here other should be text field.For understanding i kept other as option,but i want that to be a input text field where value is given by user.

Thanks in advance

like image 808
user5358888 Avatar asked Oct 20 '25 16:10

user5358888


2 Answers

You could add hidden input field by default for other text :

<input type='text' id='other' name='other' style="display:none"/>

And capture the change on select in your js then check if selected option value equal Other and show the field or hide it :

$('select').on('change', function(){
     if($(this).val()=='Other'){
         $('#other').show().focus();
     }else{
         $('#other').val('').hide();
     }
})

Hope this helps.


$('select').on('change', function(){
  if($(this).val()=='Other'){
    $('#other').show().focus();
  }else{
    $('#other').val('').hide();
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="drop">
  <option selected="selected">Please select ...</option>
  <option value="car">car</option>
  <option value="bike">bike</option>
  <option value="Other">Other</option>
</select>
<input type='text' id='other' name='other' style="display:none" value='other:'/>
like image 98
Zakaria Acharki Avatar answered Oct 22 '25 04:10

Zakaria Acharki


<script type="text/javascript">
function showfield(name){
  if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
  else document.getElementById('div1').innerHTML='';
}
</script>

<select name="drop" id="drop" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
like image 36
S M Avatar answered Oct 22 '25 04:10

S M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!