jQuery: serializeArray question

Hello, all,

I was just looking at some code that I wrote a little over two months ago.

It occurred to me that the code, as it currently exists, isn’t nearly as efficient as it could be. But I’m not sure how to do what I think I need to do.

Brief description: the code in question is for saving a user’s contact information in localStorage. Quite simply, I’m using serializeArray() to put all form elements into an array, looping that, checking for a specific class, and if the element has that class, add it to the string that will be stored in localStorage.

What I would LIKE to do is get only those elements with that specific class; instead of serializing the whole form, I’d like to serialize only those fields with that class.

What I’m using, now is:

$.each($('#formID').serializeArray(), function(index,field){
   //.. do stuff

Is there a way to specify that the only items to serialize are the inputs with a certain class??



I’ve tried the following (no success):

$.each($('#formID :input[class=ls]').serializeArray(), function(index,field){

$.each($('#formID').serializeArray(), function(index,field){...}).hasClass('ls');

$.each($('#formID').hasClass('ls').serializeArray(), function(index,field){

None of these are working.



Okay… nevermind… I think I figured it out.

$.each($('#formID :input.ls').serializeArray(), function(index,field){

This seems to work. I’m not seeing any values of form elements without the ls class.



Just adding the class seems to work.

    <input type="text" class="inarr" value="123" name="123"/>
    <input type="text" class="notinarr" value="321" name="321" />
    <input type="checkbox" class="inarr" value="111" name="111" checked/>

$('form .inarr').serializeArray()


I didn’t scroll all the way down the thread before posting this. :smiley:

1 Like

$(‘#formID :input[class=ls]’)

`ls` is missing the quote marks. cf. http://www.w3.org/TR/css3-selectors/

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.