Bilal Saqib
Bilal Saqib

Reputation: 85

How to pass values of two different select tags for process using Ajax and jQuery?

HTML :

<select id="sel">
    <option value="dog">dog</option>
    <option value="cat">cat</option>
</select>

<select id="sel2">
    <option value="chocolate">chocolate</option>
    <option value="pizza">pizza</option>
</select>

JS :

$('#sel').change(function(){
   var index = $("option:selected",this).attr("value");

   $.get("topperprocess.php",{semester_name:index},
        function(data)
        {
           $("div#toppersdata").html(data);
        }
   );
});

This code works very well for a single select tag but I want to use two select tag and there value is passed for process.

Upvotes: 1

Views: 1308

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could do it by getting the value of selected option in the both selects and send it as parameter of get request {sel: sel, sel2: sel2} :

$('#sel,#sel2').change(function(){
     var sel  = $("#sel option:selected").val();
     var sel2 = $("#sel option:selected").val();

     $.get("topperprocess.php",{sel: sel, sel2: sel2},
         function(data){
             $("div#toppersdata").html(data);
         }
     );
 });

Get the values in your php page using $_GET :

$select1_value = $_GET['sel'];
$select2_value = $_GET['sel2']; 

Hope this helps.

Upvotes: 1

aaronofleonard
aaronofleonard

Reputation: 2576

var selectChanged = function() {
    var index = $('#sel').val();
    var index2 = $('#sel2').val();

    $.get(
        "topperprocess.php",
        {
            semester_name: index,
            semester_name2: index2
        },
        function(data){
            $("div#toppersdata").html(data);
        }
    );
}

$('#sel,#sel2').change(selectChanged);

It is a little confusing as to exactly what you want to do. But there are a few modifications that I made that I think will help you out.

1) If you want the exactly same thing to happen for both select boxes, you should create 1 function that is used by both events. Here, you can see I've created selectChanged. This will be called by the change event of both #sel and #sel2.

2) We can retrieve the value of a select box using the .val() function of a select or other input element. We don't need to search for the select option manually.

3) Of course, we send both the values we've retrieved to the server in the object. You're sure you don't want to use a POST, right?

Upvotes: 0

Related Questions