简体   繁体   中英

HTML5 + JavaScript, type of input

When I declare JS.

var test = $("#test").val();

Then the "number validaion" is not working on the browser side.

<input type="number" id="test" name="test" required>

Is there any chance to declare $("#test") and use HTML5 in input validation as well (such as required, number validation etc.)? Or I have to to do it on JS side.

It have to be declared to use it later in my AJAX post scipt.

Thanks :)

Use parseInt("stringOfNumber") to get integer from string. When inputting data, you write strings, not numbers.

This is how you use the input type number in HTML5:

<input type="number" name="cost">

Here is a working example of the http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number .

If you want to add validation try this:

<input type="number" pattern="[0-9]*" name="cost">

Here is a working example of the pattern attribute http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern

Note: Both the input type number and the pattern attribute have limited browser support.

You can check if it's Not a Number, and then invert it.

if(!isNaN(test))
{
    // Is a number
}

If you use jQuery, you could use

if($.isNumeric(test))
{
    // Is a number
}

Don't rely on Client Side validation though, as it can be easily avoided and some browsers don't support it. Eg: JavaScript validation can be avoided by disabling JavaScript.

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