Jimmy
Jimmy

Reputation: 12527

Put input text into span - only works on keyup

I'm trying to put the value of my input into a span, not only on page load (to replace text) but also change it as I type. This code seems to work when I have typed something new into the box:

$(document).ready(function(){
    $("#fname").on("change keypress input", function() {
        $("#brand").text( $(this).val() );
    });    
}); 

However, is there a better way of not only getting it to change when I type something new, but also on pageload as well? (I.e it will pull the content across straight away).

Thank you.

Upvotes: 0

Views: 62

Answers (3)

Shafiqul Islam
Shafiqul Islam

Reputation: 5690

you can use this code. i hope it will work

$(document).ready(function(){
var load_text = $('#fname').text();
$("#brand").text(load_text);
$("#fname").on("change keypress input", function() {
    $("#brand").text( $(this).val() );
});    
}); 

you can also use this code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
 $("#fname").on("change keypress input", function() {
  $("#brand").text( $(this).val() );
}).change();    
}); 
</script>


<form id="test_form">
<input type="text" id="fname" value="your_input_text" />
<span id="brand"></span>
 </form>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178421

Just trigger one of them

$(function(){
  $("#fname").on("change keypress input", function() {
    $("#brand").text( $(this).val() );
  }).change();    
});

Upvotes: 1

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6969

You can play with multiple events like this..

$("#fname").on({
    change : function(){
        //code here
    }, 
    keypress : function(){
       //code here
    }, 
    input: function(){
       //code here
    } 
});

Upvotes: 1

Related Questions