Rhys
Rhys

Reputation: 3

JavaScript validation change value on submit

I need to set a form input value to -1 when submitted if nothing is entered. So far I have this function, but it doesn’t change the value to -1.

<form action="validate.php"
      method="post" onsubmit="return validate()" >

<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>

function validate()
{
    var catID;
    catID = document.getElementsByName("CategoryID");

    if (catID.value == "")
        catID.value = -1;
    return true;

}

Upvotes: 0

Views: 2066

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26444

There are a number of issues with your code. First, JavaScript code should either be included in a separate javascript file or embedded inside script tags.

Second, you'll want to use return false instead of return true.

Also, the default behavior of a form, is for it to be submitted. You might want to pass in a parameter event and use the event.preventDefault method.

Also, getElementsByName returns a collection not a single element. You need to pass in an index like so

getElementsByName("categoryID")[0];

The form tag requires the closing tag </form>.

catID.value == "" is searching for an empty string. You can use a boolean instead. It's equivalent to !catID.value

Here is my temporary solution.

<form action="validate.php"
      method="post" onsubmit="validate()" >

<input type="text" name="CategoryID" size="3" maxlength="3" onkeyup="checkCategoryID(this)"/>
</form>

<script>   

    var catID = document.getElementsByName("CategoryID")[0];

    function validate() {

        if (!catID.value) {
            catID.value = -1;
            return false;
       }        
    }
</script>

Upvotes: 1

Related Questions