簡體   English   中英

復選框打勾時,如何將在一個文本框中輸入的數據顯示到另一個文本框中?

[英]How display data entered in one text box to another text box on checkbox tick?

我試圖將在復選框中打勾的一個文本框中輸入的數據反映到另一個文本框中。 復選框的默認狀態為選中狀態。 取消選中該值后,該值應更改,然后再次返回。 即使代碼似乎可以正常工作,但我獲得的唯一輸出是“ on”。

 $(".check").click(function() { if ($(this).is(":checked")) { $('.add1').val(this.value) === $('.add2').val(this.value); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type=checkbox checked class="check"> <input type="text" id="first" class="add1" /> <input type="text" id="second" class="add2" /> 

請注意,我想按班做。

這是小提琴: https : //jsfiddle.net/starscream166/n87vLd51/1/

問題是因為this是指checkbox 因此,您在文本框的值中放置的this.value就是字符串“ on”。

要修復此問題,請將.add1val() .add1 .add2 ,如以下示例所示。 還要注意在處理復選框時使用change而不是click ,因為它可以提高可訪問性。

 $(".check").change(function() { if (this.checked) { $('.add2').val($('.add1').val()); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" checked class="check"> <input type="text" id="first" class="add1" /> <input type="text" id="second" class="add2" /> 

傳遞$('.add2').val()結果$('.add1').val()

.val()可用於檢索或分配輸入值。 可以在不帶參數的情況下調用它,該參數將返回輸入的字符串值。 或者,可以使用將值分配給輸入的參數來調用它。

 $(".check").click(function() { if ($(this).is(":checked")) { $('.add2').val($('.add1').val()); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type=checkbox checked class="check"> <input type="text" id="first" class="add1" /> <input type="text" id="second" class="add2" /> 

請在此處檢查: https : //jsfiddle.net/4kp3msax/1/或者您可以執行以下代碼。

 $(".check").click(function() {
    if ($(this).is(":checked")) {
      var add1 = $('.add1').val();
      $('.add2').val(add1);
    }
 });

當一個字段數據中的任何一個更改時有效

 let swt_data = ""; $(".add1").on("change", function() { swt_data = $(this).val(); }) $(".check").click(function() { if ($(this).is(":checked")) { if (swt_data != $('#first').val() != $('#second').val()) { $('#first').val(swt_data); $('#second').val(swt_data) } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type=checkbox checked class="check"> <input type="text" id="first" class="add1" /> <input type="text" id="second" class="add1" /> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM