Reputation: 25
I wanted to know how to display a value entered inside a textbox into a label by using the onkeyup method. I am able to display it inside a textbox. This is what i have done so far:
<script>
function multiply(value){
var x;
x= 2*value;
document.getElementById('out2x').value=x;
}
</script>
<body>
<div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
<label for="">Input</label>
<input type="text" name="" onkeyup="multiply(this.value);">
<br>
<label for="">Result(x2):</label>
<input type="text" id="out2x" name="" readonly>
</div>
</body>
I tried to set the id 'out2x' to label but it doesn't work.
Upvotes: 1
Views: 1339
Reputation: 665
In Your Case, I have a simple Keyup with jQuery like this
$('#value').keyup(function (){
$('#copy-value').val($(this).val());
});
So This Snippet for Example:
$('#value').keyup(function (){
$('#copy-value').val($(this).val());
});
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
<label for="">Input</label>
<input id="value" type="text" name="">
<br>
<label for="">Result(x2):</label>
<input id="copy-value" type="text" name="" readonly>
</div>
</body>
Upvotes: 0
Reputation: 65796
Where do you actually have the script
in the document? It should be just before the CLOSING body
tag so that by the time it's reached, all the HTML will have been parsed. If the script
runs before the HTML is parsed, your document.getElementById()
statement won't find a matching element.
Also, the value
of the input
is always a string. You must convert that to a number in order to do math with it. There are several ways to do this and you need to be prepared for situations where the input incorrectly has a non-numeric value in it, but below, I've converted the value
by prepending a +
to it.
A couple of other things....
You are not using the label
element properly. The for
attribute must have a value that matches the id
attribute value of the form element the label is "for" or you can nest the form element within the label
so that it knows what element it relates to.
Don't use inline JavaScript - separate it into the JavaScript code.
<body>
<div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">
<label>Input
<input type="text">
</label>
<br>
<!-- Not always best to use an input for output. -->
<span>Result(x2):
<span id="out2x"></span>
</span>
</div>
<!-- Place your script just before the closing body tag
so that by the time it's reached, all the HTML elements
will have been parsed. -->
<script>
// Do your event handling in JavaScript, not with inline JavaScript
document.querySelector("input").addEventListener("keyup", function(event){
// You must convert the input string to a number
document.getElementById('out2x').textContent = 2* +this.value;
});
</script>
</body>
Upvotes: 3