binhhtse binhhtse - 6 months ago 7
jQuery Question

Pass value to Jquery function

I would like to pass value of index to function like this. Who can give me some ideas!

index = 3;
$("#addNewRow"+index+"").on("click", function () {


});

Answer

You don't need to pass it, you can directly use it:

index = 3;
$("#addNewRow"+index).on("click", function () {
  alert(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addNewRow3">Add New Row</button>

That's the easiest and best way, but you can do it in many other ways. For example, you can extract it back from the object ID:

index = 3;
$("#addNewRow"+index).on("click", function () {
  alert(this.id.substring(9));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addNewRow3">Add New Row</button>

Or you can pass it using event data:

index = 3;
$("#addNewRow"+index).on("click", index, function (e) {
  alert(e.data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addNewRow3">Add New Row</button>

Comments