Monisha Monisha - 10 days ago 6
jQuery Question

How to generate dynamic text box when selecting multiple options in drop down?

I have drop-down with options at the end 'others' option is there if we select the 'others' option dynamically text box will appear.but in my problem is, it is multi-select drop down.if you select 'others' and one more option in that drop-down,the text-box is coming.how to get that text-box if you select 'others' option and any other option...



function showfield(name) {
if (name == 'others') {
document.getElementById('div1').innerHTML =
'<input type="text" id="others" name="others" autocomplete="off" />';
}
else {
document.getElementById('div1').innerHTML ='';
}
}

<td>
<select class="outcomes" id="outcomes" name="keyOutcomes"
multiple="multiple" style="width: 310px;"
onchange="showfield(this.options[this.selectedIndex].value)">
<option value="Revenue-top-line">Revenue top-line</option>
<option value="Margin">Margin(CTS/Client)</option>
<option value="Cashflows">Cashflow improvement</option>
<option value="Custome">Customer experience/CSAT</option>
<option value="Demand">Demand Elimination</option>
<option value="Risk">Risk Reduction</option>
<option value="Regulatory_compliance">Regulatory compliance</option>
<option value="others">Others</option>
</select>
<span id="outcomeaddress" style="margin-top: 29px; margin-left: 275px; color: red;"></span>
<div id="div1"></div>
</td>




Answer

Well first of all you have added the jquery tag but you don't use it in your question, so i will assume you won't mind if the answer will include jquery:

This is a working code (tested) that if others is selected, with or without other options the input is shown:

$("#outcomes").change(function() {
    var selected = $(this).val(); //array of the selected values in drop box

  for(var i=0; i < selected.length; i++) {
    if (selected[i] == "others") {
        $("#div1").html('<input type="text"  id="others" name="others" autocomplete="off" />');
    } else {
        $("#div1").html("");
    }
  }
});

All it does is taking all the values that is selected (select var), loop over them to check if others is one of the selected, if yes then show the input, if no don't show.

Also don't forget to remove the onchange in the html:

<select class="outcomes" id="outcomes" name="keyOutcomes" multiple="multiple" style="width: 310px;">
    <option value="Revenue-top-line">Revenue top-line</option>
    <option value="Margin">Margin(CTS/Client)</option>
    <option value="Cashflows">Cashflow improvement</option>
    <option value="Custome">Customer experience/CSAT</option>
    <option value="Demand">Demand Elimination</option>
    <option value="Risk">Risk Reduction</option>
    <option value="Regulatory_compliance">Regulatory compliance</option>
    <option value="others">Others</option>
</select> <span id="outcomeaddress" style="margin-top: 29px; margin-left: 275px; color: red;"></span>
<div id="div1"></div