简体   繁体   中英

Input validation in JavaScript and HTML

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?

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. eg

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.

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;
    }
}
<textarea id="my_textbox" name="textbox" ...></textarea>
//the row above is simple html

getElementById("my_textbox").value += "something as a string from js function";

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