【问题标题】:JQUERY: Change value from text input having a checkbox selectedJQUERY:从选中复选框的文本输入中更改值
【发布时间】:2014-02-23 21:10:05
【问题描述】:

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

        <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>

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

谢谢!!

【问题讨论】:

    标签: javascript jquery text input checkbox


    【解决方案1】:

    如果我的问题没看错 - 它看起来像这样:

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

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

    【讨论】:

      【解决方案2】:

      试试

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

      DEMO

      【讨论】:

        【解决方案3】:

        我知道 jQuery 中没有 :text。假设您的 HTML 保持不变,您可以使用 .prev() 方法在每个 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/

        【讨论】:

          猜你喜欢
          • 2016-01-27
          • 1970-01-01
          • 2017-12-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-16
          • 1970-01-01
          • 2021-02-01
          • 1970-01-01
          相关资源
          最近更新 更多