Passing a form-variable into the onsubmit field?
Asked Answered
S

4

12

I am trying to verify the contents of a form before sending it. Basically, I'm trying to work with the numbers in the form and ensure they are within the correct range. The problem is that the JavaScript I have which is trying to verify it thinks that the item being passed to it is NaN (I have been parsing it).

A little work revealed that the variable ("size") is referring to an "HTMLInputEleMent", which I guess is, indeed, NaN (although I am not quite sure what it actually is). I think that the problem is that the onSubmit is not passing what I want it to be passing, even though I named the field "size" and I passed onSubmit "size" too.

I tried putting it in quotation marks, but that just turns it into a string...

I am wondering if perhaps you are unable to pass a variable from WITHIN the form to it's onSubmit field? Is that so? If so, how should I do this?

Here is the form:

        <form onsubmit="return goodForm(size, day, month, year)" action="http://localhost:8080/pomper_servlet/CostCalc" method="GET">              
            The day of the month must be entered as a number (ex: 1,22)
            <input type="text" name="day"><br>
            The month of the year must be entered as a number (ex: Jan.=1, etc.)
            <input type="text" name="month"><br>
            The year must be entered as a 4 digit number (ex: 2008, 2017)
            <input type="text" name="year"><br>
            Please Choose a tour-length, in accordance with the chart below:
            <input type="TEXT" name="length"><br>
            How many people will be in your group? (No More than 10 allowed!)
            <input type="text" name="size"><br>                
            Please select a tour:<br>
            <input type="RADIO" name="tour" value="Gardiner Lake">
            Gardiner Lake<br>
            <input type="RADIO" name="tour" value="Hellroaring Plateau">
            Hellroaring Plateau<br>
            <input type="RADIO" name="tour" value="The Beaten Path">
            The Beaten Path<br>
            <input type="SUBMIT" value="Submit">
        </form>

And here is the function, from functions.js:

function goodForm(gSize, day, month, year) {
"use strict";
window.alert("goodFrame(): "+gSize);
var groupSize1 = parseInt( gSize.replace(/^"|"$/g, ""), 10);
window.alert("goodFrame(): "+groupSize1);
var sizeInt = parseInt(groupSize1);
if(groupSize(sizeInt) && goodDate(day, month, year)){
    window.alert("true");
    return true;
}
else{
    window.alert("false")
    return false;
}

There are references to other functions in there, but they aren't relevant to this, I think. The alerts were/are for debugging purposes...

Thanks in advance!

Satanic answered 10/7, 2013 at 19:45 Comment(3)
Could you look up the field by ID inside of the onsubmit method?Compotation
Er...maybe--how do I do that (I'm pretty new to this, in case that hasn't become clear yet...)Satanic
See answer below. I'll elaborate.Compotation
A
5

You can try giving each one of the Inputs (day, month, year, size) to id (you can use the same value as your name attribute). Get the value by id within your goodForm() function.

<input type="text" name="day" id="day"> <-- set

document.getElementById("some id").value <-- get

Aftertaste answered 10/7, 2013 at 19:59 Comment(0)
C
8

Is something like this what you mean?

JavaScript:

 document.getElementById("myForm").onsubmit = function() {
     alert(document.getElementById("size").value);
 }

HTML:

<form name="myForm" id="myForm">
    <input type="text" name="size" id="size">
    <input type="submit">
</form>

Elaboration:

The onsubmit function is attached to an item whose id is "myForm" specified in the HTML as id="myForm". You can lookup the item with this ID using the method getElementById on the document. Careful not to do getElementByID (Id vs ID). When you submit the form, this method will get called and you'll be on your way.

Then you can lookup items on the page to get their value the same way you looked up the form. Just give them an ID like id="size" and you can look it up.

You can also do something like:

alert(document.myForm.size.value);

or

alert(document.forms["myForm"].size.value);

...but I've stayed away from that method since, a while ago at least, some browsers hated it. Maybe it's better and more performant now, I'm not sure.

Compotation answered 10/7, 2013 at 19:53 Comment(0)
A
5

You can try giving each one of the Inputs (day, month, year, size) to id (you can use the same value as your name attribute). Get the value by id within your goodForm() function.

<input type="text" name="day" id="day"> <-- set

document.getElementById("some id").value <-- get

Aftertaste answered 10/7, 2013 at 19:59 Comment(0)
B
4

First, doing inline validation like this (via onsubmit) is bad form. Usually you will want to do event binding, I'm going to include sample code using jQuery, but you can use other methods as well.

First, give your form a unique ID attribute for the page. I'm assuming <form id="MyForm"...

Next, you will likely want your validation method to "know" about the fields it needs.

//this function is executed when the page's dom is loaded
// assumes jQuery is loaded already
$(function(){

    //binds the myFormOnSubmit method below to run as part of your form's onsubmit method
    $('#MyForm').submit(myFormOnSubmit);

    //runs when the form is trying to submit
    function myFormOnSubmit(event) {
        var f = $(this);

        // note, you have to match on attribute selectors
        //  you may want to give each of these fields an id=".." attribute as well to select against #IdName
        var size = f.find('[name=size]').val();
        var day = f.find('[name=day]').val();
        var month = f.find('[name=month]').val();
        var year = f.find('[name=year]').val();
        var tour = f.find('[name=tour]:checked').val(); //selected radio button's

        var isValid = validDate(year,month,day) && validSize(gSize) && validTour(tour);

        if (!isValid) {
            event.preventDefault(); //stop submit
        }
    }

    function validTour(tour) {
        return !!tour; //will be false if it's an empty string, ex: no selected value
    }

    function validSize(size) {
        var s = parseInt(size); //get integer value for size

        if (s <= 0 || s > 10) return false; //not in range
        if (s.toString() !== size) return false; //doesn't match input, invalid input
        return true; //true
    }

    function validDate(year, month, day) {
        //coerce the values passed into numbers
        var y = +year, m = +month, d = +day;

        //convert to an actual date object
        var dtm = new Date(y, --m, d);

        //compare the values
        if (!dtm) return false; //invalid input
        if (dtm.getFullYear().toString() !== year.toString()) return false; //year doesn't match input
        if ((dtm.getMonth() + 1).toString() !== month.toString()) return false; //month doesn't match input
        if (dtm.getDate().toString() !== day.toString()) return false; //day doesn't match input

        var now = new Date(); console.log(now);
        var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        //entered date is before today, invalid
        if (dtm <= today) return false;

        //passed checks
        return true;
    }
});
Babirusa answered 10/7, 2013 at 20:8 Comment(0)
Z
2

In case you don't want to use JQuery:

You don't need to pass the parameters, try giving them an id and get them by their id inside the good form function.

function goodForm() {
    var size = document.getElementById("size");
    if(null != size){
       // do something with size.value
    }

}
Zacharie answered 10/7, 2013 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.