Skip to content Skip to sidebar Skip to footer

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 do

Solution 1:

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

EDIT: This is working because "others" is the last options, so it checks it last every time you select something, here is a code even if "others" is not last option:

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

  for(var i=0; i < selected.length; i++) {
    if (selected[i] == "others") {
        isSelected = true;
    }
  }

  if (isSelected) {
    $("#div1").html('<input type="text"  id="others" name="others" autocomplete="off" />');
  } else {
    $("#div1").html('');
  }
});

Post a Comment for "How To Generate Dynamic Text Box When Selecting Multiple Options In Drop Down?"