HKK
HKK

Reputation: 339

Javascript post form

Im trying to submit a form by javascript, after a specific field is validated.

im using

function doValidate(){
        var error = false;
        var nr = document.getElementById('number').value;
    if (nr > '10'){
        document.getElementById('number').className += " red";
        error = true;
    }
    if (error = false) {
        document.forms["new_qs"].submit();
    }
}

but when error is false, just nothing happens! I inspected the site with firebug, error is false, the document.forms seems to do nothing. But in Online Tutorials this is working very good.

Here is a complete fiddle from the site http://jsfiddle.net/S7G9J/25/

What could be the problem/solution?

Upvotes: 0

Views: 64

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

if (error = false) {

In the above, you are using assignment operator. =. Use == to compare

Also you are comparing string instead of numbers.

Try this:

function doValidate(){
    var error = false;
    var nr = Number(document.getElementById('number').value);
    if (nr > 10){
        document.getElementById('number').className += " red";
        error = true;
    }
    if (error === false) {
        document.querySelector('[type="button"]').submit();
    }
}

Upvotes: 3

Monarch Wadia
Monarch Wadia

Reputation: 4956

The error lies in the line where you submit() the form.

In your fiddle, your form's id is "test". In your javascript, the form you're referencing should have an id of "new_qs". However, there is no such form, so there is no submit() processed.

document.forms[0].submit() will submit the first form in order of appearance in your HTML. So, try this:

function doValidate(){
    var error = false;
    var nr = document.getElementById('number').value;
if (nr > '10'){
    document.getElementById('number').className += " red";
    error = true;
}
if (error == false) { // need double equal here
    document.forms[0].submit();
}
}

Upvotes: 0

Related Questions