views:

25

answers:

2

Probably a simple solution so I'm a bit embarassed, but JS is not really my forte so I figure I'll ask.

I'm using the Jquery Form plugin to submit a group of checkboxes for requirements for an event planning app I am making.

I'm having trouble making my validation presubmit callback refuse the form if there is no array key for 'requirement'. I know in php I could simply use something like array_key_exists or just check against isset(), but I'm not sure what the cognate is in js. code follows.

<form id="choose_reqs" method="post" action="http://www.domain.com/generator/chooseReqs/" enctype="multipart/form-data">
            <p>I'm planning on getting:</p>
            <?php foreach($_SESSION['event']->opt_r as $r){?>
                <span style="display:block; width:120px; padding:4px; border:1px #ccc solid;"><input type="checkbox" value="<?=$r;?>" name="requirement[]"/><?=$r;?></span>
            <?php }?>
            <input type="submit" name="event_chosen" value="Next" />
        </form>

And then the associated js that runs after the form is loaded in:

 function eventTypeChosen(responseText, statusText, xhr, $form)  {

   var options = {  
        target:        '#app',  
        beforeSubmit: formSubmitCheck,
        success:       reqsChosen  
    }; 
        setNav();
        $('#choose_reqs').ajaxForm(options); 
   } 

   function setNav(){
        $('#start_over').click(start);
   }


   function formSubmitCheck(formData, jqForm, options){

        if(formData.hasOwnProperty('requirement')){ 
            alert('Please check at least one requirement'); 
            return false; 
        }else{

    $(jqForm).fadeOut(200);
    return true;
    }
   }

Obviously something is wrong with the .hasOwnProperty() method and how I'm using it.

+1  A: 

From the form plugin page you linked in your comments:

formData is an array of objects representing the name and value of each field that will be sent to the server...

Try printing out the formData object to the console so you can verify its structure.

CD Sanchez
This did occur to me... when dumping out the array each form input is a multidimensional array with a numeric array key, under which are keys for 'name' and 'value'. My problem is that I can't see how to drill through the numeric keys to the name key child and check only if that exists throughout the array (since the submit key is not important). I had thought of looping through them and instructing it to ignore the element with name submit, but this didn't seem to work either.
DeaconDesperado
+1  A: 
function formSubmitCheck(formData, jqForm, options){

        if($('input[name=requirement[]]').fieldValue().length==0){ 
            alert('Please check at least one requirement'); 
            return false; 
        }else{

    $(jqForm).fadeOut(200);
    return true;
    }
   }
davyM
Thanks davyM - worked great!
DeaconDesperado
you're welcome!
davyM