简体   繁体   中英

How to get text from input box to a span

I have got the HTML but I am not sure on how to get the input box into the span. I tried using document.getElementById but that didn't work. Any help would be great!

Name:
<p>
  <input type="text" name="fname" id="name">
<p>
  <button id= "button" onclick="namejs">Go</button>
<p>
  <span id= "namespan">Name</span>

You can user innerHTML attribute for span tag, like below :

var name = document.getElementById("name").value; //get name from TextBox
document.getElementById("namespan").innerHTML=name ; //write in span

You can try the following, this is plain Javascript Getting values you can use

document.getElementById("myspan").innerHTML="value";

For modern browsers

document.getElementById("myspan").textContent="value";

CODE

Name:
<p>
<input type="text" name="fname" id="name">
  <p>
<button id= "button" onclick="myFunction()">Go</button>
  <p>
  <span id="namespan">Name</span>

function myFunction() {
  var name = document.getElementById("name").value;
  document.getElementById("namespan").textContent=name;
}

Added a fiddle

Hope this will help you.

<!DOCTYPE html>
<html>
<head>
    <script>
    function showInput() {
        document.getElementById('display').innerHTML =
            document.getElementById("user_input").value;
    }
</script>
</head>
<body>
<form>
    <label><b>Enter a Message</b></label>
    <input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>

If you use jquery , you can smoothly update span on real-time when you write in input :

$('#namespan').html($('#name').val()); // GET Value of INPUT --> SET IT as inner HTML of span

DEMO :

 $('#name').keyup(function(){ $('#namespan').html($(this).val()); // GET Value of INPUT --> SET IT as inner HTML of span }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Name: <p> <input type="text" name="fname" id="name"> </p> <p> <button id= "button" onclick="namejs">Go</button> </p> <p> <span id= "namespan">Name</span></p> 

Add an onkeyup event handler

 document.getElementById('name').onkeyup = function() { document.getElementById('namespan').innerHTML = this.value; } 
 Name: <p> <input type="text" name="fname" id="name"> </p> <p> <button id="button" onclick="namejs">Go</button> </p> <p> <span id="namespan">Name</span> </p> 

You can simply:

Html:

Name:
<p><input type="text" name="fname" id="name"><p>
<p><button id= "button">Go</button></p>
<p><span id= "namespan">Name</span></p>

jQuery:

$('#button').click(function(){
$('#namespan').text($('#name').val()); 
});

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