繁体   English   中英

JQUERY:更改文本输入的值并选中一个复选框

[英]JQUERY: Change value from text input having a checkbox selected

仅在选中复选框时,才需要更改文本输入的值。 两个输入(文本和复选框)具有相同的类:

        <label for="text_to_apply">Write your text: </label>
        <input type="text" id="text_to_apply" name="text_to_apply" value="">
        <button type="button" id="btn_apply">Change</button>

        <form id="theform">
            <input type="text" value="1" id="one1" class="one"><input type="checkbox" id="one1_" class="one"><br>
            <input type="text" value="1" id="one2" class="one"><input type="checkbox" id="one2_" class="one"><br>
            <input type="text" value="1" id="one3" class="one"><input type="checkbox" id="one3_" class="one"><br>
            <input type="text" value="1" id="one4" class="one"><input type="checkbox" id="one4_" class="one"><br>
            <input type="text" value="2" id="two1" class="two"><input type="checkbox" id="two1_" class="two"><br>
        </form>
    </div>

    <script>
        $('#btn_apply').click(function() {
            var mytext = $('#text_to_apply').val();
            if ($('#theform').find('.one input:checked')) {
                $('#theform').find('.one:text').attr('value', mytext);
            }
        });
    </script>

</body>

我的想法不多了。 请帮忙!

谢谢!!

尝试

    $('#btn_apply').click(function() {
        var mytext = $('#text_to_apply').val();
        $('#theform').find('input:checked').each(function(){
            $(this).prev().val(mytext);
        });
    });

演示

如果我的问题正确无误-它将如下所示:

    $('#btn_apply').click(function() {
        if ($('#yourCheckboxId').is(':checked')){
             $('#inputId').val('some text you want');
        }            
    });

这是小提琴http://jsfiddle.net/Goodluck/2XBcK/

我知道的jQuery中没有:text 假设您的HTML保持不变,则可以使用.prev()方法在每个input:checked之前设置input:checked目标input:checked

    $('#btn_apply').click(function() {
        var mytext = $('#text_to_apply').val();
        if ($('#theform').find('input:checked')) {
            $('#theform').find('input:checked').prev('input').attr('value', mytext);
        }
    });

小提琴: http : //jsfiddle.net/willthemoor/5qmH8/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM