简体   繁体   中英

My JavaScript doesn't seem to run

I'm currently trying to create a regex to work in an input field. The JavaScript itself returns no errors in JS Chrome console, but since onLoad() doesn't even work, I'm very confused. Here is my website if you want to see it yourself: users.aber.ac.uk/mta2/cs25010

<script>
        var regEx = new RegExp("[0-9]+\.[0-9][0-9]");
        var regEx2 = new RegExp("[0-9]+");
        function validateFilter()
        {
            var input = document.forms["filterPrice"]["price"].value;
            if(regEx.test(input) == true || regEx2.test(input) == true)
            {
                alert("Input must be only numbers. Decimal allowed");
                return false;
            }
        }

        function onLoad()
        {
            alert("HI");
        }
    </script>

<form name="filterPrice" action="homepage.php" method="GET" onsubmit="return validateFilter()">
        <select name = priceSelect> 
            <option value = "Greater"> Filter prices greater than </option>
            <option value = "Less"> Filter by prices less than </option>
        </select>
        <input id ="priceInput" name="price" type ="text">  </input>

        <button> Go </button>
</form>

您必须像这样将if语句更改为false

if(regEx.test(input) == false|| regEx2.test(input) == false)

You are not explaining what exactly is wrong with validateFilter . But looking at the function and the regular expressions, it's clear that they don't do what you want to do.

If you want to check whether a string contains only digits or a decimal like x.xx then you your expression should be

^\d+(\.\d{2})?$

The important part are ^ and $ . They anchor the expression, so the whole string must match the pattern, not only part of the string. Eg your expression ( new RegExp("[0-9]+") also matches "foo9" and "123foobar" .

The other expression, new RegExp("[0-9]+\\.[0-9][0-9]") , is also incorrect. It does not just match 0.00 but also eg 0x00 . That's because your are using a string to define the expression, and \\ is the escape characters for strings as well. So the expression you are creating is actually [0-9]+.[0-9][0-9] , where . matches any character.

Furthermore, if the expression does not match, you want to show the alert, ie when regEx.text(input) returns false , not true .

Revised code:

var regEx = /^\d+(\.\d{2})?$/;

function validateFilter() {
    var input = document.forms["filterPrice"]["price"].value;
    if (!regEx.test(input)) {
        alert("Input must be only numbers. Decimal allowed");
        return false;
    }
}

DEMO

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