简体   繁体   中英

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

var str1=$("#account-number").val().substring(0,4);
$("#first-four").html(str1);

I have tried multiple variations and attempts its been a few hours... so I thought I should ask for help...

I want to be able to take the first four characters of an input field with id "account-number" and send it to a div with id "first-four"

On thing to watch out for is change vs input . The first only fires when the input looses focus.

 $("#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" ).on("input", function() {
        var str1 = $("#account-number").val().substring(0,4);
        $("#first-four").html(str1);
    });
})
$(document).ready(function(){
    $("#account-number").blur(function(){
        var accountNmbr = $("#account-number").val().substring(0,4);
        $("#first-four").html(accountNmbr);
    });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM