update text box based on checkbox selection jquery

前提是你 提交于 2019-12-08 09:50:18

问题


I want to achieve following thing with Jquery

  • There are multiple trips and each trip has checkbox and textbox.
  • Whenever checkbox is checked then the value in textbox corresponding to that checkbox must be updated to "1" .
  • Whenever customer types in textbox then checkbox shall be checked

    <input type="checkbox" id="ckval1" class="checkvaloare" />Trip 1 <a 
    href="">sad</a><a href="">ssad</a>
    <input type="text" id="text1" class="ckval" size="2" />
    <br/>
    <input type="checkbox" id="ckval2" class="checkvaloare" />Trip 2 <a  
    href="">sad</a><a href="">sassad</a>
    <input type="text" id="text2" class="ckval" size="2" />
    

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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/28982207/update-text-box-based-on-checkbox-selection-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!