Gags
Gags

Reputation: 3829

update text box based on checkbox selection jquery

I want to achieve following thing with Jquery

JQUERY as

$(function () {
$("input[type=checkbox]").on('click', function () {
    $(this).next().val($(this).is(':checked') ? '1' : '0');
});
$("input[type=text]").on('keyup', function () {
    if ($(this).val()) {
        $(this).prev().prop('checked', true);
    } else {
        $(this).prev().prop('checked', false);
    }
});
});

But this is not working and when i use JSF Tag <h:selectBooleanBox> then also it is not working.

Upvotes: 0

Views: 1250

Answers (2)

ambe5960
ambe5960

Reputation: 2000

next() only get the next sibling element. In your case, the next sibling element after the checkbox are the tags. There are two sets of tags before your desired input, which is why it works for you after 3 'next()'s. Of course that is not very pretty to use 3 nexts and would break easily if you ever added another element in there.

use

 nextAll('.ckval:first')

and it will find the next ckval input rather than the next element.

Upvotes: 0

Pete
Pete

Reputation: 58432

You need to use nextAll and prevAll (along with the firstpseudo selector) as you have anchors in between your checkbox and textbox.

I would also change the click event to change

$(function () {
    $("input[type=checkbox]").on('change', function () {
        $(this).nextAll('.ckval:first').val($(this).is(':checked') ? '1' : '0');
    });
    $("input[type=text]").on('keyup', function () {
        if ($(this).val()) {
            $(this).prevAll('.checkvaloare:first').prop('checked', true);
        } else {
            $(this).prevAll('.checkvaloare:first').prop('checked', false);
        }
    });
});

Example

Upvotes: 2

Related Questions