Reputation: 1
I have made a javascript function and want to get the value of that function in a textbox. How can I do this?
My next question is how to put validation to enter numbers only in the textbox?
Upvotes: 0
Views: 2256
Reputation: 741
well, Archinamon made a good job on how to make the js method set a value on the input text , so here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
Upvotes: 2
Reputation: 48387
Others have provided answers on how to retrieve a value.
For validation, you should learn how to use regular expressions. e.g.
function checkPattern()
{
var re = new RegExp(/^\d+$/);
if (!re.test(this.value)) {
this.focus();
alert("Must be a number!");
}
}
var inp = document.getElementById('someTextInput');
inp.addEventListener('blur',checkPattern);
There are ots of tutorials on the internet about using regular expressions.
Upvotes: 1
Reputation: 18430
Here is what you can do to put vaue in text box:
var data = /*call to your function*/
var txtbox = document.getElementById('your textbox id');
txtbox.value = data;
for numerical validation try this (on textbox's onkeypress="fncInputNumericValuesOnly"
):
function fncInputNumericValuesOnly()
{
if(!(event.keyCode >= 45 && event.keyCode <= 57))
{
event.returnValue=false;
}
}
Upvotes: -1
Reputation: 191
<textarea id="my_textbox" name="textbox" ...></textarea>
//the row above is simple html
getElementById("my_textbox").value += "something as a string from js function";
Upvotes: -1