2013-07-10 21 views
6

sto cercando di verificare il contenuto di un modulo prima di inviarlo. Fondamentalmente, sto cercando di lavorare con i numeri nel modulo e assicurarmi che rientrino nell'intervallo corretto. Il problema è che il codice JavaScript che sto provando a verificare pensa che l'elemento che gli viene passato sia NaN (l'ho analizzato).Passaggio di una variabile modulo nel campo onsubmit?

Un po 'di lavoro ha rivelato che la variabile ("dimensione") si riferisce ad un "HTMLInputEleMent", che credo sia, in effetti, NaN (anche se io non sono abbastanza sicuro che cosa è in realtà). Credo che il problema è che l'onSubmit non passa quello che voglio che sia di passaggio, anche se ho chiamato il campo "dimensione" e ho passato onSubmit "dimensioni" troppo.

Ho provato a mettere tra virgolette, ma che appena lo trasforma in una stringa ...

mi chiedo se forse non si riesce a passare una variabile all'interno del modulo al suo campo onSubmit? È così? Se è così, come dovrei farlo?

Qui è la forma:

 <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> 

E qui è la funzione, da 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; 
} 

Non ci sono riferimenti ad altre funzioni in là, ma non sono rilevanti per questo, penso. Gli avvisi sono stati/sono solo a scopo di debug ...

Grazie in anticipo!

+0

Puoi cercare il campo per ID all'interno del metodo onsubmit? – oooyaya

+0

Ehm ... forse - come faccio a farlo (sono abbastanza nuovo a questo, nel caso in cui non sia ancora chiaro ...) –

+0

Vedere la risposta qui sotto. Elaborerò. – oooyaya

risposta

2

Si può provare a dare ciascuno degli Input (giorno, mese, anno, dimensione) qualche id (è possibile utilizzare lo stesso valore dell'attributo name) e ottenere il valore document.getElementById ("some id"). valore all'interno della funzione goodForm().

2

è qualcosa di simile che vuoi dire?

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> 

Elaborazione:

La funzione onsubmit è collegato a un elemento il cui id è "myForm" indicato nel codice HTML come id =" myForm". Puoi cercare l'oggetto con questo ID usando il metodo getElementById sul documento. Attento a non fare getElementByID (Id vs ID). Quando invii il modulo, questo metodo verrà chiamato e sarai sulla buona strada.

Quindi è possibile cercare gli elementi nella pagina per ottenere il loro valore nello stesso modo in cui si è cercato il modulo. Basta dare loro un ID come id = "size" e puoi cercarlo.

Si può anche fare qualcosa di simile:

alert(document.myForm.size.value); 

o

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

... ma ho soggiornato lontano da quel metodo in quanto, qualche tempo fa, almeno, alcuni browser odiava . Forse è meglio e più performante ora, non ne sono sicuro.

4

In primo luogo, fare la convalida in linea come questo (via onsubmit) è di cattivo gusto.Solitamente vorrai fare il binding di eventi, includerò il codice di esempio usando jQuery, ma puoi anche usare altri metodi.

Innanzitutto, assegna al modulo un attributo ID univoco per la pagina. Sto assumendo <form id="MyForm"...

Successivamente, probabilmente vorrai che il tuo metodo di validazione "sappia" sui campi di cui ha bisogno.

//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; 
    } 
});
2

Nel caso in cui non si desidera utilizzare JQuery:

Non è necessario passare i parametri, provare a dare loro un id e ottenere dal loro id all'interno della buona funzione modulo .

function goodForm() { 
    var size= document.getElementById("size").value; 
    if(size...){ 
    ... 
    } 

} 
Problemi correlati