How to synchronize two text box form values?

前端 未结 6 650
旧时难觅i
旧时难觅i 2021-02-05 04:56

Hi all i am new to jQuery. Suppose I have two HTML text boxes. How can I make it happen that if I write in text box A then same value goes to textbox B and if I write in B then

6条回答
  •  孤独总比滥情好
    2021-02-05 05:35

    I ran into this challenge today. I made a small plugin to make the code more readable and to handle text inputs, but also select fe.

    When you include the plugin, you can simply use $("selector").keepInSync($("otherselector"));

    $.fn.keepInSync = function($targets) {
      // join together all the elements you want to keep in sync
      var $els = $targets.add(this);
      $els.on("keyup change", function() {
        var $this = $(this);
        // exclude the current element since it already has the value
        $els.not($this).val($this.val());
      });
      return this;
    };
    
    //use it like this
    $("#month1").keepInSync($("#month2, #month3"));
    $("#text1").keepInSync($("#text2"));
    
    

    Two way sync


提交回复
热议问题