Input validation in JavaScript and HTML
I hav开发者_运维百科e 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?
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;"
/>
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.
<textarea id="my_textbox" name="textbox" ...></textarea>
//the row above is simple html
getElementById("my_textbox").value += "something as a string from js function";
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;
}
}
精彩评论