user3711600
user3711600

Reputation: 873

use jquery to capture form data and post using ajax call

Newbie here. I am building an app in rails and I'm trying to use jquery to capture the values of multiple select boxes within a form. I've tried to simplify this down as much as possible.

form html:

<form action="/units" data-remote="true" id="add_form" method="post">

<select class="select_box" id="box_1">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
</select>

<select class="select_box" id = "box_2"
<option value="1">1</option>
<option value="2">2</option>
<option selected="selected" value="3">3</option>
</select>

*... additional select boxes...*

<input disable_with="Loading..." name="commit" type="submit" value="Submit" />

</form>

In my application.js I want to capture the selected value of each select box.

I've tried using serialize() but can't get it to work since the form is dynamically generated using javascript (i.e. is not part of the DOM when the page is initially loaded).

Since there a lot of form elements (~20) I want to avoid working through the form elements one-by-by to capture the data, e.g.

var val_1 = $("#box_1").find(":selected").val()
var val_2 = $("#box_2").find(":selected").val()
...

Is there some way I can capture all of the selected values of a given class of elements (i.e. .select_box) and store them in an array?

perhaps something along the lines of:

var form_data = $(".select_box").find(":selected").data()

or somehow loop through the elements of class .select_box ?

Just can't quite get my head around this one. Thanks!

Upvotes: 0

Views: 1284

Answers (3)

easy
easy

Reputation: 318

This is how you can get your relevant data:

var form_data = $(".select_box").find(":selected").map(function (index) {
            return ($(this))[0].value;
        });

and this is how you can convert it to JSON for sending to server:

JSON.stringify(form_data.get())

Upvotes: 1

Cyberpks
Cyberpks

Reputation: 1421

You should use serialize() to serialize (as Kyle said) form data, and then post the form. Try this:

$.post( "yourPageUrl", $( "#add_form" ).serialize() );

Upvotes: 0

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

The data() method is used to get the values of an element's data attributes.

You can use the serialize() method on the form element to retrieve the values of all elements within the form.

Or you can use the val() method to retrieve the value of each element.

i.e: $("#textfield_id").val(); // gets the value of a textfield

Upvotes: 1

Related Questions