jQuery将一个输入事件模拟为另一输入

时间:2019-07-16 00:57:07

标签: javascript jquery jquery-events

我有两个文本输入ID:input1和input2。我想在input1到input2上模拟按键。我无法复制onblur值,因为在仿真后,我将更改input1的值。您能否让我知道如何在jQuery 1.6或Javascript中执行此操作?我在下面尝试过,但这不起作用,并且更改了值,即$('#'+ origid).val()返回空白。

$(".maskedinput").keyup(function (e) {
        var value = $.trim($(this).val());
        var origid = $(this).attr('origid');
        var originalelemevt = jQuery.Event( "keypress" );
        originalelemevt.which = e.which;
        originalelemevt.keycode = e.keycode;

        $('#'+origid).trigger( originalelemevt );
        var newval = '';
        if(value.length >=4){
            var orignal = value.substring(0,value.length-4);
            for(var i=0;i<orignal.length;i++)
                newval +='*';

            newval +=value.substring(orignal.length);
            $(this).val(newval);
        }

    });

$(document).ready(function() {
  $("#I1").keyup(function (e) {
        var value = $.trim($(this).val());
        var newval = '';
        
        if(value.length >=4){
            var orignal = value.substring(0,value.length-4);
            for(var i=0;i<orignal.length;i++)
                newval +='*';

            newval +=value.substring(orignal.length);
            $(this).val(newval);
        }

        $('#I2').val(e.target.value);

    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<form id='F1'>
  <input id='I1'>
  <input id='I2'>
</form>

3 个答案:

答案 0 :(得分:0)

您可以复制键盘上的内容。无需实际触发按键事件。

\w

Demo

答案 1 :(得分:0)

将输入内容包装在<form>标记中。参见HTMLFormElement API。演示中将评论详细信息。

// Register the form to the input event
document.forms.F1.oninput = matchText;

/* matchText() is immediately called when user enters text to
   input#I1
   e.target always references the origin of event (the tag that was
   clicked, hovered, typed into, etc.)
   this keyword refers to the tag that listened for events
   this.elements is a collection of all form controls of the form
*/
function matchText(e) {
  if (e.target.matches('#I1')) {
    this.elements.I2.value = e.target.value;
  }
  return false;
}
<form id='F1'>
  <input id='I1'>
  <input id='I2'>
</form>

答案 2 :(得分:0)

这是我正在寻找的id1上的按键事件。

$("#id1").keypress(function(e) {
  var inputkey = e.which || e.keyCode;
  var result = getInputSelection(document.getElementById("id1"));
  $("#id2").trigger("keypress")
    .val(function(i, val) {
      var key = e.which || e.keyCode;
      // return this.value + String.fromCharCode(key);

      return this.value.substr(0, result.start) + String.fromCharCode(key) + this.value.substr(result.end)
    });


});

$("#id1").keyup(function(e) {
  mask('id1');
});

$("#id1").keydown(function(e) {

  var inputkey = e.which || e.keyCode;
  //alert(inputkey);
  if (inputkey == 8) {
    e.preventDefault();
    var new_val = replaceValue(inputkey);
    //alert(new_val);
    $("#id1").val(new_val);
    $("#id2").val(new_val);
    // mask('id1');
  } else if (inputkey == 46) {
    e.preventDefault();
    var new_val = replaceValue(inputkey);
    //alert(new_val);
    $("#id1").val(new_val);
    $("#id2").val(new_val);
    // mask('id1');
  }
});

function mask(elid) {
  var $this = $('#' + elid);
  $this.val($this.val().replace(/.(?=.{4})/g, '*'));


}

function replaceValue(inputkey) {
  var result = getInputSelection(document.getElementById("id1"));
  // alert("Backspace "+result.start +","+result.end);
  var new_val = $("#id1").val();
  if (result.start == result.end) {
    if (inputkey == 8) {
      new_val = $("#id2").val().substr(0, result.start - 1) + $("#id2").val().substr(result.end);
    } else if (inputkey == 46) {
      new_val = $("#id2").val().substr(0, result.start) + $("#id2").val().substr(result.end + 1);
    }
  } else {

    new_val = $("#id2").val().substr(0, result.start) + $("#id2").val().substr(result.end);
  }
  return new_val;
}

function getInputSelection(el) {
  var start = 0,
    end = 0,
    normalizedValue, range,
    textInputRange, len, endRange;

  if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
    start = el.selectionStart;
    end = el.selectionEnd;
  } else {
    range = document.selection.createRange();

    if (range && range.parentElement() == el) {
      len = el.value.length;
      normalizedValue = el.value.replace(/\r\n/g, "\n");

      // Create a working TextRange that lives only in the input
      textInputRange = el.createTextRange();
      textInputRange.moveToBookmark(range.getBookmark());

      // Check if the start and end of the selection are at the very end
      // of the input, since moveStart/moveEnd doesn't return what we want
      // in those cases
      endRange = el.createTextRange();
      endRange.collapse(false);

      if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
        start = end = len;
      } else {
        start = -textInputRange.moveStart("character", -len);
        start += normalizedValue.slice(0, start).split("\n").length - 1;

        if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
          end = len;
        } else {
          end = -textInputRange.moveEnd("character", -len);
          end += normalizedValue.slice(0, end).split("\n").length - 1;
        }
      }
    }
  }

  return {
    start: start,
    end: end
  };
}
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="banner-message">
  SSN:
  <input type="text" id="id1" />
  <input type="text" id="id2" style="display:none" />
</div>