1

i have list of items, i need to set checkbox checked value to true when price input is empty, and to false when it's not.

<td><input type="text" value="" class="name"></td>
<td><input type="text" value="" class="producer"></td>
<td><input type="text" value="" class="model"></td>
<td><input type="text" value="" class="dateOf"></td>
<td><input type="text" value="" class="color"></td>
<td><input type="text" value="" class="price"></td>

Edit:

<td><input type="checkbox" class="checkbox"></td>

and there is my jquery function :

$(function() {
    $('.price').on('input', function() {
        if (!$('.price').val()) {
            $(this).closest('td').next().find('.checkbox').prop("checked", true);
        }else{
             $(this).closest('td').next().find('.checkbox').prop("checked", false);
        }

    });
});

the problem is that it works only for first "price" input, how to make it work for all ?

4
  • 2
    Where is checkbox? Please don't tell me that IDs are not unique Commented Jan 28, 2014 at 21:14
  • 1
    Please read the jQuery tutorial about basic event handling: "In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this. To turn the DOM element into a jQuery object that we can use jQuery methods on, we simply do $( this )". Tutorials are great, they help a lot! You should read them! Commented Jan 28, 2014 at 21:17
  • 2
    To reduce the code a bit you could write: $(this).closest('td').next().find('.checkbox').prop("checked", !$(this).val()); (and remove the if/else statement) Commented Jan 28, 2014 at 21:17
  • to my shame ids are not unique indeed, i've removed them -_- Commented Jan 28, 2014 at 21:28

2 Answers 2

2

Use this keyword

if (!$(this).val()) {

instead of

if (!$('.price').val())

If there are multiple inputs with the class price, the keyword this will handle the event for the specific input .price you are changing.

Sign up to request clarification or add additional context in comments.

3 Comments

Using the class selector would still work if there wasn't another issue though, wouldn't it?
@James: .val will always return the value of the first selected element. So the only other "issue" there is is that there are multiple elements with that class.
Very true. Didn't think of multiple prices.
1

Try

$('.price').keyup(function () { 
    $(this).closest('td').next().find('.checkbox').prop("checked", !$(this).val());
});

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.