1

I have a "grid" with several input fields per row. Lets say each input field represents a day of the week.

html:

<table id="grid">
    <tr>
        <td><input class="fri" type="text" value="foo" /></td>
        <td><input class="mon" type="text" value="bar" /></td>
        <td><input class="tue" type="text" value="baz" /></td>
        <td><input class="wed" type="text" value="x" /></td>
        <td><input class="thu" type="text" value="y" /></td>
    </tr>
    ...

jQuery:

$('#grid').on('change', '.fri', function () {
    var value = $(this).val();
    //do something
});

$('#grid').on('change', '.mon', function () {
    var value = $(this).val();
    //do something
});

// And so on...

There can be any number of rows, all having the same fields.

I made a working fiddle of what I am trying to do.

However, I feel I am repeating myself a little too much (with the jQuery) and I was wondering if there is a way to do the above more concisely (preferably using jQuery).

2 Answers 2

4

You can rather use element selector instead of using individual IDs and then binding them:

$('#grid').on('change', 'input:text', function () {
   var value = $(this).val();
   //do something
});

Also if you have other textboxes in same table which you don't want to target then use multiple class selector:

$('#grid').on('change', '.fri,.mon,.tue', function () {
  var value = $(this).val();
  //do something
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast answer. Just what I needed.
1

You could use event.target like this:

$('#grid').on('change', function (e) {
    alert(e.target.value);
});

This would be the only jQuery you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.