Woddles
Woddles

Reputation: 51

jQuery dynamic dropdown box ajax

I currently have two dropdown boxes and a textbox.

I am using a database query to fill the first dropdown box and ajax to fill the second dropdown, depending on the value chosen in the first dropdown. I also am using ajax to fill in the input textbox once a selection from the second dropdown is chosen.

My problem is, with my current code, when I choose an option from the first dropdown, although it DOES fill in the second dropdown box with the data returned from ajax, I also want it to ajax the input box as well and return that value at the same time as the second dropdown value updates.

     $( "#manufacturerOpts" ).change(function(){
            val1 = $(this).attr("value");
            $.ajax({
               url: "inc/class/data.php",
               type: "POST", 
               data: "manu="+val1,
               cache: false,
               success: function (html1) {   

               $('#modelOpts').html(html1);

               val2 = $("#modelOpts option").attr("value");

              $.ajax({
               url: "inc/class/data.php",
               type: "POST", 
               data: "mod="+val2,
               cache: false,
               success: function (html2) {  
               $('#powerOpts').html(html2);    
               }
              });
                }
              });

    });

    $( "#modelOpts" ).change(function(){
            val1 = $(this).attr("value");
            $.ajax({
               url: "inc/class/data.php",
               type: "POST", 
               data: "mod="+val1,
               cache: false,
               success: function (html1) {  $('#powerOpts').attr("value",html1);  }
              });

            // $("#modelOpts").selectmenu('refresh', true);
    });

Upvotes: 4

Views: 732

Answers (1)

Musa
Musa

Reputation: 97717

You can modify your request to send the value for the textbox along with the dropdown menu options

$.ajax({
    url: "inc/class/data.php",
    type: "POST", 
    data: "manu="+val1,
    dataType: 'json',
    success: function (data) {
        $('#modelOpts').html(data.modelOpts);
        $('#powerOpts').html(data.powerOpts);    
    }
});

and in you server-side code you can easily find out the value of the first option for the modelOpts dropdown and send it as well

$data = array('modelOpts' => modelOptsHtml, 'powerOpts' => powerOptsHtml);
echo json_encode($data);

Upvotes: 4

Related Questions