0

I'm very new to jquery and just looking for some help.

current code:

var formData = {
                    'settings'          : $('input[name=settings]').val(),       
                    'name'              : $('input[name=name]').val(),
                    'email'             : $('input[name=email]').val(),
                    'superheroAlias'    : $('input[name=superheroAlias]').val()
                };

What im looking to do is instead of declare each individual field is maybe add a class to each input and pick up each field that way.

Im guessing this is possible but I've tried so many diffent ways and i feel im just confusing myself more

2
  • Are you using this in an AJAX call? You could use $("#formID").serialize() to get all the fields in the form. Commented Jun 14, 2015 at 20:41
  • If the answer is not clear/working or you meant something else, let me know so I can help Commented Jun 14, 2015 at 20:46

1 Answer 1

1

Yes, it is possible. Use a custom class and each()

var formData = {};

$('.my-class').each(function(){
  formData[$(this).attr('name')] = $(this).val();
  });

console.log(formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input class="my-class" name="settings" value="1"/>
<input class="my-class" name="name" value="2"/>
<input class="my-class" name="email" value="3"/>
<input class="my-class" name="superheroAlias" value="4"/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.