user1327418 user1327418 - 1 year ago 116
HTML Question

How to make a textbox invisible based on the choice of a dropdown in dynamically generated GUI

When ChoiceC is chosen in the drop down menu I want to make the "Other" textbox invisible and bring it back otherwise. Am I not writing my function correctly? It should be called on every change of value in the DropDown right? The HTML here is from a 'View Source' command because the GUI is generated dynamically.

<label>
Please Specify
</label>

<select name="ctl00$ctl00$cphMainContent$cphContent$dd-140"
id="ctl00_ctl00_cphMainContent_cphContent_dd-140"
data-qid="140">
<option value=""></option>
<option value="ChoiceA">A</option>
<option value="ChoiceB">B</option>
<option value="ChoiceC">C</option>

</select>


<label>
Other
</label>

<input name="ctl00$ctl00$cphMainContent$cphContent$txt-139"
id="ctl00_ctl00_cphMainContent_cphContent_txt-139"
data-qid="139"/>
<span id="ctl00_ctl00_cphMainContent_cphContent_reqValidator_txt_139"





<script>
$(
function ()
{
if ($("#data-qid='140'").val() == 'ChoiceC')
$("#data-qid='139'").hide();
}
);
</script>

Answer Source

You need to listen to the change event of the select dropdown to identify the value entered and then based on the value, you can show/hide the input field. Here is a quick example of this in action-

 <script>
 $(document).ready(function() {
  $('input[data-qid=139]').hide();
  $('input[data-qid=139]').prev().hide();
  $('select[data-qid=140]').on('change', function(e) {
    var inputValue = $(this).val();
    if(inputValue == 'ChoiceC') {
      $('input[data-qid=139]').hide();
      $('input[data-qid=139]').prev().hide();
    } else {
      $('input[data-qid=139]').show();
      $('input[data-qid=139]').prev().show();
    }
  });
 });
 </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Please Specify</label>

<select name="ctl00$ctl00$cphMainContent$cphContent$dd-140"  id="ctl00_ctl00_cphMainContent_cphContent_dd-140" data-qid="140">
        <option value=""></option>
        <option value="ChoiceA">A</option>
        <option value="ChoiceB">B</option>
        <option value="ChoiceC">C</option>
</select>


<label>Other</label>
<input name="ctl00$ctl00$cphMainContent$cphContent$txt-139" 
     id="ctl00_ctl00_cphMainContent_cphContent_txt-139" 
 data-qid="139"/>
<span id="ctl00_ctl00_cphMainContent_cphContent_reqValidator_txt_139" 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download