如何从输入字段的文本中获取子字符串并将其显示给另一个html元素

How to get a substring from the text of an input field and display it to another html element

本文关键字:串并 字符串 显示 元素 html 另一个 字符 输入 字段 获取 文本      更新时间:2023-09-26
var str1=$("#account-number").val().substring(0,4);
$("#first-four").html(str1);

我尝试了多种变体,尝试了几个小时。。。所以我想我应该寻求帮助。。。

我希望能够获取id为"account number"的输入字段的前四个字符,并将其发送到id为"first four"的div

需要注意的是更改输入。第一个仅在输入失去焦点时激发。

$("#account-number").on("input", function(){
  $("#first-four").text(this.value.substring(0,4));
});
<input id="account-number" type="text" />
<div id="first-four"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(document).ready(function(){
    $("#account-number").blur(function(){
        var accountNmbr = $("#account-number").val().substring(0,4);
        $("#first-four").html(accountNmbr);
    });
});

JSFiddle:https://jsfiddle.net/Lw4kr4Lq/

$( document ).ready(function() {
    $( "#account-number" ).on("input", function() {
        var str1 = $("#account-number").val().substring(0,4);
        $("#first-four").html(str1);
    });
})