imgrv
imgrv

Reputation: 121

trigger select dropdown automatically to show other hidden fields

Hi i have dropdown selection in my form yes and No. where when someone select yes then it shows 3-4 more fields and when its no it hides other fields. in my form there is modify option also when we take user to the page with populated data fetched from database in input fields.

Now the problem is when someone is selected yes and also submitted other required fields. now want to modify the data, when this page open , i can see that yes option is automatically selected, but hidden fields does not show, we need to click No and then yes then it shows other populated fields. i want it should automatically opened when selected option is yes.

<select name="tab" size="1" class="combo2" id="chkYes" required>
                                    <option value="">Select One</option>

                                    <option value="Yes" <?php if($oth_passport == 'Yes'){ echo "selected";}?>>Yes</option>
                                    <option value="No" <?php if($oth_passport == 'No'){ echo "selected";}?>>No</option>

                                </select>

other fields is --

<tr id="issuc" style="display:none;">
<td>
<input name="oth_ppt" value="<?php echo $othppt;?>" required >
</td></tr>
<tr id="ppno1" style="display:none;">
<td>
<input name="oth_ntl" value="<?php echo $othntl;?>" required >
</td>
</tr>

Javascript code to Control this is -

    <script>

$(document).ready(function(){
    $('#chkYes').on('change', function() {

    if ( this.value == 'Yes') {
      $("#issuc , #ppno1").show();
      $("#issuc input, #ppno1 input").prop("required", true);
    } else {
      $("#issuc , #ppno1").hide();
      $("#issuc input, #ppno1 input").prop("required", false);
    }
  });
});

</script>

Upvotes: 3

Views: 618

Answers (2)

Racil Hilan
Racil Hilan

Reputation: 25351

One way you can solve it is by manually triggering the change event like this:

$('#chkYes').trigger("change");

Here is the updated code:

$(document).ready(function() {
  $('#chkYes').on('change', function() {
    if (this.value == 'Yes') {
      $("#issuc , #ppno1").show();
      $("#issuc input, #ppno1 input").prop("required", true);
    } else {
      $("#issuc , #ppno1").hide();
      $("#issuc input, #ppno1 input").prop("required", false);
    }
  }).trigger("change");
});

Upvotes: 1

Reza Mamun
Reza Mamun

Reputation: 6189

Simply update your code with just one line to load or hide dependent content on the load time:

<script>
$(document).ready(function(){
    $('#chkYes').on('change', function() {
        if ( this.value == 'Yes') {
            $("#issuc , #ppno1").show();
            $("#issuc input, #ppno1 input").prop("required", true);
        } else {
            $("#issuc , #ppno1").hide();
            $("#issuc input, #ppno1 input").prop("required", false);
        }
    }).trigger('change'); //HERE is the trick!!
});
</script>

Upvotes: 2

Related Questions