skip to Main Content

I used this jQuery script in a simple form to show #x just when the yes option is selected on the dropdown (#field1).

That works completely but the main problem is when a submission error occurs, the #x doesn’t appear again, and the user needs to change the dropdown and select the yes field again despite it being on the yes option.

In the beginning, I used the first select code shown here below. Since the selected option was removed after the submission error, I thought the problem was with that code, and so I changed the select codes to the second snippet of code shown here.

The selected option problem is fixed now, and after a submission error, the selected option is still selected, but the #x still does not appear.

$(function() {
    $('#x,#y,#z').hide(); 

    $('#field1').change(function() {
        if($('#field1').val() == 'yes') {
            $('#x').show();
        } else {
            $('#x,#y,#z').hide(); 
        } 
    });
});

My first dropdown codes

<select name="field1" id="field1" class="select-submit2">
     <option value="no">No</option>
     <option value="yes">Yes</option>
</select>

And this is my second dropdown code, and I don’t know which one is correct:

<select name="field1" id="field1" class="select-submit2">
    <option value="no"<? if(@$_POST['hassubunits'] == 'no') { echo 'selected = "selected"'; } ?>>No</option>
    <option value="yes"<? if(@$_POST['hassubunits'] == 'yes') { echo 'selected = "selected"'; } ?>>Yes</option>
</select>

#x should appear after the submission error

2

Answers


  1. You can also use this,

    <select name="field1" id="field1" class="select-submit2">
             <option value="">Select</option>
                    <option value="no">No</option>
                    <option value="yes">Yes</option>
    </select>
       <p id="x">This is p tag</p>
       <span id='y'>This is span tag</span>
       <div id="z">This is div tag</div>
    
     $(document).ready(function() {
          $("p").css("background-color", "yellow");
          $('#x,#y,#z').hide(); 
                                $('#field1').change(function(){
                                    if($('#field1').val() == 'yes') {
                                        $('#x').show();
    
                                    } else {
                                        $('#x,#y,#z').hide(); 
                                    } 
                                });
       });
    
    Login or Signup to reply.
  2. Trigger the .change() event listener immediately after loading the page, by calling .change() after defining the handler.

    $(function() {
      $('#x,#y,#z').hide();
    
      $('#field1').change(function() {
        if ($('#field1').val() == 'yes') {
          $('#x').show();
        } else {
          $('#x,#y,#z').hide();
        }
      }).change();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search