skip to Main Content

I am using an ajax call when two drop-down selects are changed. How do I do that? This is what I have done, but it works when there is any change to the form, which is not quite the behavior I am looking for:

$myForm.change(function(event)
{
    event.preventDefault();
     $.ajax({
        method: "GET",
        url: $endPoint,
        data: $formData,  
        success: function(data){
            console.log("success!"); },

        error: function(error){
            console.log("error: ", error)
        },
        complete: function(xhr, status){ 
            console.log("The request is complete!");
        }

    });

Also, it doesn’t look like this is working:

$("#id_dropdown_1", "#id_dropdown_2").change( function () {
     ... same as above 
});

2

Answers


  1. You can store the id of the first dropdown that is changed, then call the ajax when a dropdown is changed afterward that isn’t the same one:

    var selectChanged = "";
    $("select").change(function() {
      if (selectChanged === "") selectChanged = $(this).attr("id");
      else if ($(this).attr("id") !== selectChanged) console.log("Call function here");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="select1">
      <option>A</option>
      <option>B</option>
      <option>C</option>
    </select>
    <select id="select2">
      <option>X</option>
      <option>Y</option>
      <option>Z</option>
    </select>
    Login or Signup to reply.
  2. you used another overload of the jquery function

    use $(“#id_dropdown_1”, “#id_dropdown_2”) is wrong

    separate between ids with comma only without double quotes between two ids like this
    $("#id_dropdown_1, #id_dropdown_2")

    and don’t forget to pass event parameter to change function

    $("#id_dropdown_1, #id_dropdown_2").change( function (event) {
         ... same as above 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search