0

I am generating some select inputs dynamically, and it follows this structure

<select id="OrderType_orderItem_0_product" name="OrderType[orderItem][0][product]" class="form-control">,

<select id="OrderType_orderItem_1_product" name="OrderType[orderItem][1][product]" class="form-control">

and so on.

I need to do a ajax post on .change on every select generated, how can I do that?

Right now I have this, but it obviously just work for the first select of id 0:

$(document).ready(function () {
        $('[name="OrderType[orderItem][0][product]"]').change(function(){
           var val = $(this).val();
           $.ajax({
                type: "POST",
                url: "myurl" + val,
                success: function(data) {

                }
            });
            return false;
        });

2 Answers2

3

One way of doing this would be to give them a shared class

<select id="OrderType_orderItem_0_product" name="OrderType[orderItem][0][product]" class="form-control myClass">,

<select id="OrderType_orderItem_1_product" name="OrderType[orderItem][1][product]" class="form-control myClass">

And then assigning this event to that class:

$(document).ready(function () {
        $('.myClass').change(function(){
           var val = $(this).val();
           $.ajax({
                type: "POST",
                url: "myurl" + val,
                success: function(data) {

                }
            });
            return false;
        });

because we are using this element for val it will use the element that has triggered the event.

Budyn
  • 563
  • 7
  • 21
2

You just need to trigger function on change of any select input that's name's start with OrderType

Try this exemple :

$(document).ready(function () {

  $("select[name^='OrderType']").change(function(){

           var val = $(this).val();

           $.ajax({
                type: "POST",
                url: "myurl" + val,
                success: function(data) {

                }
            });
            return false;
  });

});