如何从输入onkeyup文本框jquery获取原始插入文本

时间:2017-07-19 13:58:34

标签: javascript jquery html forms

我有一个小问题可能很容易修复,但我还不是那么好。我正在尝试获取输入类型=文本框的值。如何输入原始值?..不是点?

$(function() {
  var self = this;
  self.txtdata = "";
  $("body").on("keyup", "#txt1", function(e) {
    self.txtdata = self.txtdata + String.fromCharCode(e.keyCode);
    var txtbox = this;
    var dots = "";
    for (var i = 0; i < $(txtbox).val().length; i++) {
      dots = dots + "●";
    }
    $(this).val(dots);
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label for="tabname">Tabname:</label>
<input name="tabname" type="textbox" id="txt1" autocomplete="off">

2 个答案:

答案 0 :(得分:1)

您可以使用解决方案https://jsfiddle.net/4gbog729/

var text = "";
$('input[type="password"]').keypress(function(e){
	text += String.fromCharCode(e.which);
  console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="password">Password:</label> 
<input name="password" type="password" id="txt1" autocomplete="off">

输入类型应为密码而不是文本框。

此处没有输入密码的解决方案:https://jsfiddle.net/4gbog729/2/

var text = "";
$('input[type="text"]').keyup(function(e){
	text += String.fromCharCode(e.keyCode);
  var data = $(this).val();
  $(this).val( text.replace(/[a-zA-Z0-9]n*/g, '*'))
  console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="password">Password:</label> 
<input name="password" type="text" id="txt1" autocomplete="off">

答案 1 :(得分:1)

使用数组存储密钥代码,然后加入密钥。以下是更新的代码:

$(function() {
  var self = this;
  var enteredText = [];
  self.txtdata = "";
  $("body").on("keyup", "#txt1", function(e) {
    enteredText.push(String.fromCharCode(e.keyCode));
    self.txtdata = self.txtdata + String.fromCharCode(e.keyCode);
    var txtbox = this;
    var dots = "";
    for (var i = 0; i < $(txtbox).val().length; i++) {
      dots = dots + "●";
    }
    $(this).val(dots);

    console.log(enteredText.join(''));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label for="password">Password:</label>
<input name="password" type="textbox" id="txt1" autocomplete="off">

示例/伪AJAX代码:

$.ajax({
  url: 'receive.php',
  data: {
    enteredText: enteredText
  },
  type: "POST",
  dataType: "json",
  success: function(data) {
    // do something here after receiving success from server
  }
});