0

How can I use a multiplo HTML select with ajax?

HTML

<select name="son" id="son">
  <option value="" >son</option>
</select> 

<select name="son1" id="son1">
  <option value="" >son1</option>
</select> 

<select name="son2" id="son2">
  <option value="" >son2</option>
</select> 

<select name="son3" id="son3">
  <option value="" >son3</option>
</select> 

<select name="son4" id="son4">
  <option value="" >son4</option>
</select>

JS:

   $("select[name='son']").change(function(){

         $('#son1').append('<option value="" selected>Loading</option>');          

        $.ajax({
            url: "ajax.php",
            type: "post",
            data: 's='+ $('#son').find('option:selected').val(),
            success: function(data){
                $("#son1").html(data);
            }
        });
    });  

    $("select[name='son1']").change(function(){

         $('#son2').append('<option value="" selected>Loading</option>');          

        $.ajax({
            url: "ajax.php",
            type: "post",
            data: 's1='+ $('#son1').find('option:selected').val(),
            success: function(data){
                $("#son2").html(data);
            }
        });
    });

The first ajax is working, but when I try to call the second select box, nothing happens.

I need to loading the son1 select and then call an ajax to loading son2 select box, and after that, load son3 select box, and so on...

Any ideas??

Thanks!!!

1
  • Quick FYI, this.value will give you the selected value in your change event, no need to re-select the element and find the selected option. data: 's1=' + this.value would do. Commented Oct 3, 2013 at 1:30

1 Answer 1

1

Anytime you're manipulating HTML with an AJAX call, you should use the jQuery "on" event. Try this

  $("body").on("change", "select[name='son']", function(){

         $('#son1').append('<option value="" selected>Loading</option>');

        $.ajax({
            url: "ajax.php",
            type: "post",
            data: 's='+ $('#son').find('option:selected').val(),
            success: function(data){
                $("#son1").html(data);
            }
        });
    });

    $("body").on("change", "select[name='son1']", function(){

         $('#son2').append('<option value="" selected>Loading</option>');

        $.ajax({
            url: "ajax.php",
            type: "post",
            data: 's1='+ $('#son1').find('option:selected').val(),
            success: function(data){
                $("#son2").html(data);
            }
        });
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.