views:

71

answers:

3

I have a form that uses a JQuery Json post. I have 10+ textboxes on the page. I have variables passed the only way I know... is there another way to pass multiple variables?

$('#nameSubmit').click(function() {
    var status = document.getElementById('Select2').value;
    var lob = document.getElementById('LOB').value;
    var lName = document.getElementById('LName').value;
    var fName = document.getElementById('FName').value;
    var city = document.getElementById('City').value;
    var state = document.getElementById('State').value;
    $.post("Home/LoadTable", { Status: status, LOB: lob, LName: lName, FName: fName, City: city, State: state }, function(data) {
        //...process code works 
    }, 'json');
});

EDIT

I am using the following method to add textbox and dropdown lists...

<%using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "myForm" })) {%>
<td><%= Html.TextBox("LName")%></td>
<select name="Status" id="Select2"> 
    <option value="ALL">All Policies</option>             
    <option value="Active">Active</option>
    <option value="Cancelled">Cancelled</option>                                     
</select>
<% } %>
A: 

That's pretty much the way to do it. You can write a form serializer that would produce the json for you, but you are still going to pass the produced json into it.

Achilles
Thanks... is this the same way for Html.Textbox, and Drop downs? See Edit
A: 

The following code will loop over all text boxes (no textareas, though) and create an object with the IDs as the key.

$('#nameSubmit').click(function () {
    var obj = {};
    $("input:text", this.form).each(function () {
        obj[this.name] = this.value;
    });
    $.post("Home/LoadTable", obj, function (data) { /* */ }, 'json');
});

EDIT: Another person suggested using $().serialize(), in this use case I strongly support that as the best answer.

Ryan Tenney
Thanks... is this the same way for Html.Textbox, and Drop downs? See Edit
+3  A: 

Put the text boxes inside <form> tags, then use jQuery's serialize method.

<form id="myForm" action="javascript:void(0);">
    <input type="text" name="a" value="Input A" />
    <input type="text" name="b" value="Input B" />
    <input type="submit" value="Submit Form">
</form>

Then you can do this:

$('#myForm').submit(function(){
    $.post("Home/LoadTable", $('#myForm').serialize(), function(data){
        // code...
    },'json');
});
Rocket
The entire page is in a form. I made some edit adjustments...
Ok, so does `$('#myForm').serialize()` work?
Rocket
Sorry about that. It did.. Thanks!