Pythonista
Pythonista

Reputation: 11625

indexing form elements with jquery

I've been searching around and all the answers I've seen will use something along the lines of $('form :input')$ to get all of the inputs. But I already have a reference to the form using $("form").submit() and I just need to grab a specific input field from the fieldname. I'm unsure of how to use $(this) with additional selectors to get the forms specific elements

So, how would I go about doing that.

Example of the bit of code I need to workout.

$('form').submit(function(){
    var form = $(this)
    var form_errors = array_of_errors
    for(var fieldname in form_errors){
        var errors = form_errors[fieldname]
        var field = \\how to get this
        \\ Something like $(form, 'input[name='+fieldname+']') maybe?
    }
});

Upvotes: 0

Views: 51

Answers (2)

vol7ron
vol7ron

Reputation: 42109

$('form').submit(function(){
    var $form       = $(this),             // good naming practice to use $ to signify jQuery object
        form_errors = validateForm(this);  // semi-colon

    var fields = Object.keys( form_errors );
    for ( var i=0,n=fields.length; i<n; i++ ){
       var field  = fields[i],
           errors = form_errors[field],
           $field = $form.find('input[name=' + field + ']');

       $field.applyErrorMarkup(errors);    // whatever you plan to do with the field
    }
});



// Pseudocode of one possible way to validate your form
function validateForm(frm){
   var errors = {};

   // BEGIN LOOP: <insert code to iterate over fields and validity checks>
   var field = 'fieldname';            // placeholder

   if( true /* error found */ ){
      var err = errors[field];
      var msg = 'new error message';   // should be the dynamic validity check error message (e.g., 'only numbers permitted')
      errors[field] = err && [msg].concat( err ) || msg;
   }
   // END LOOP

   return errors;
}

Upvotes: 0

Fez Vrasta
Fez Vrasta

Reputation: 14835

$(selector, context)

jQuery selectors can have a second argument, used to define their context.

$(`input[name=${fieldname}]`, form);

will do the trick.

This means that your selector will look only inside the element you have passed as context.

Documentation: http://api.jquery.com/jquery/#jQuery-selector-context


$(context).find(selector)

An alternative could be to use find() in conjunction with the context:

$(form).find(`input[name=${fieldname}]`);

Upvotes: 1

Related Questions