How jQuery to change a second select list based on the Third select list option and second select based upon first

前端 未结 1 381
既然无缘
既然无缘 2021-01-07 14:09

Why third select option is changing based upon second one. But when first select is selected second one is changing. while go to second third one is not changing This is

相关标签:
1条回答
  • 2021-01-07 14:38

    Select1 is not working since there is no id attribute for select1 in HTML.

    <!-- change -->
    <select name="select1" select="select1">
    <!-- to -->
    <select name="select1" id="select1">
    

    Also, there seems to be some mismatch between data-values and values of options.

    1. try to keep val for actual value of the option and data-value for its predecessor.
    2. Both these value are case sensitive so 'telangan' !== 'Telangan'

    Here's a updated version of your code:

    $("#select1").change(function() {
      if ($(this).data('options') == undefined) {
        $(this).data('options', $('#select2 option').clone());
      }
      var id = $(this).val();
      var options = $(this).data('options').filter('[data-value=' + id + ']');
      $('#select2').html(options).show();
    });
    
    
    $("#select2").change(function() {
      if ($(this).data('options') == undefined) {
        $(this).data('options', $('#select3 option').clone());
      }
      var id = $(this).val();
      var options = $(this).data('options').filter('[data-value=' + id + ']');
      $('#select3').html(options).show();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="select1" id="select1">
        <option value="">Select Country</option>
        <option value="india">India</option>
        <option value="america">America</option>
    </select>
    
    
    <select name="select2" id="select2" style="display: none;">
        <option value="">Select State</option>
        <option data-value="india" value="orissa">Orissa</option>
        <option data-value="india" value="telangan">Telangan</option>
        <option data-value="america" value="america">USA</option>
        <option data-value="america" value="america">California</option>
    </select>
    
    <select name="select3" id="select3" style="display: none;">
        <option value="">Select city</option>
        <option data-value="orissa">Nal</option>
        <option data-value="orissa">Mir</option>
        <option data-value="telangan">Hyd</option>
        <option data-value="telangan">Vija</option>
        <option data-value="america">KRK</option>
        <option data-value="america">MRK</option>
    </select>

    0 讨论(0)
提交回复
热议问题