简体   繁体   中英

Use jQuery to target multiple classes

I have this jQuery code where it can add and remove a select input form dynamically.

$(document).ready(function() {
    var max_fields = 20; //maximum input boxes allowed

    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID
    var x = 1; //initlal text box count
    $(add_button).click(function(e) { //on add input button click
      e.preventDefault();
      if (x < max_fields) { //max input box allowed
        x++; //text box increment
        $( ".aaaa" ).first().clone().appendTo( ".input_fields_wrap" );
        }
    });
    $(wrapper).on("click", ".remove_field", function(e) {
      e.preventDefault();
      if($(".aaaa").length > 1) {
        $(this).parent('div').remove();
      } else {
        alert('You can not delete all elements');  
      }
    })
});

I want to use this jQuery code to many classes( class="input_field_wrap and etc." ).

The only thing I can see to make it work is to make it as an onclick function?

function createSelect(wrapper, add_button, a) {
 var max_fields = 20;
 var x = 1;
 $(add_button).click(function(e) { //on add input button click
      e.preventDefault();
      if (x < max_fields) { //max input box allowed
        x++; //text box increment
        $( ".aaaa" ).first().clone().appendTo( ".input_fields_wrap" );
        }
    });
}

This doesn't work.

HTML:

 <div class="input_fields_wrap">
                      <a href="#" class="add_field_button" >Add Another Prescibed Medication</a>
                      <div class="aaaa">
                          Prescibed Medication Name:
                          <select class="form-control" name="prescription[]">
                              <option value="">Select an option</option>
                              <?php 

                            foreach($prescription->result() as $row)
                            { 
                              echo '<option value="'.$row->id.'">'.$row->name.'</option>';
                            }

                          ?>

                          </select>

                          <a href="#" class="remove_field">Remove</a>
                      </div>
                    </div>

You've just to use event delegation on() to deal with fresh DOM added dynamically as you do in the previous click event for .remove_field , it will be :

$('body').on('click', '.add_field_button', function(e) { 
  e.preventDefault();

  if (x < max_fields) { //max input box allowed
    x++; //text box increment
    $( ".aaaa" ).first().clone().appendTo( ".input_fields_wrap" );
    }
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM