0

I am trying to make a dynamic call to php script using jquery. I have multiple input checkboxes

<input type="checkbox" id="driver[0]" value="log.example.com">
<input type="checkbox" id="driver[1]" value="api.example1.com">
<input type="checkbox" id="driver[2]" value="mail.example.com">

Using jquery, this is what I am trying to do,

 $(document).ready(function() {
            $("#driver[0]").click(function(event){
                if($(this).is(':checked')){
                var domain = $(this).val();
                //alert(domain);
                  $("#stage").load('call.php', 'submit=submit&domain='+domain);
              }
            });
         });

So as you can see, the jquery requires a selector here #driver[0] , which in my case can be either one of them only. So does that mean that I have to write seperate function for each checkbox?

Here is how the data is getting updated into the page.

      <div id = "stage" style = "background-color:#eee;">
         STAGE
      </div>

Since all the domains are getting dynamically generated, I am thinking of a more adaptive way to deal with this, but I am having no luck.

Thanks,

Panda
  • 2,400
  • 3
  • 25
  • 35
  • Possible duplicate of [jquery: click for every id-element starting with](https://stackoverflow.com/questions/6985136/jquery-click-for-every-id-element-starting-with) – adiga Mar 31 '19 at 08:40

2 Answers2

2

You can use a selector that selects all ids which start with driver[:

$(document).ready(function() {
  $("[id^='driver[']").click(function(event){
    if($(this).is(':checked')){
      var domain = $(this).val();
      //alert(domain);
      $("#stage").load('call.php', 'submit=submit&domain='+domain);
    }
  });
});

It would probably be more elegant to start from the container of the <input>s though, if possible, eg:

<div id="container">
  <input type="checkbox" id="driver[0]" value="log.example.com">
  <input type="checkbox" id="driver[1]" value="api.example1.com">
  <input type="checkbox" id="driver[2]" value="mail.example.com">
</div>

and then

$('#container > input').click(...
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Do this with one function dynamically:

$(document).ready(function() {
  $("input[type='checkbox']").click(function(event){
    if($(this).is(':checked')){
      var domain = $(this).val();
      //alert(domain);
      $("#stage").load('call.php', 'submit=submit&domain='+domain);
    }
  });
});
Rishabh Jain
  • 169
  • 1
  • 9