How to reference an input within a form in jQuery

By : Brian G
Source: Stackoverflow.com
Question!

An easy jQuery question.

I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and then the input name. ( the input names are not unique in my page )

So for instance:

var xAmt = $('#xForm'+num).('#xAmt');

I really want to supply these values to an AJAX POST

	$.ajax({
	  url: "X.asp",
	  cache: false,
	  type:  "POST",
	  data:  "XID=xID&xNumber=xNum&xAmt=xAmt",

...

If I can get the values in the AJAX call even better.

By : Brian G


Answers

The flexible way to do it has already been answered here, but you can also just make it work with your current code. (Forgive me if this was too basic for what you're looking for.)

Drill down from the unique form name by using the CSS descendant selector (a space):

var xAmt = $('#xForm'+num+ ' #xAmt').val();

Repeat for each value you need and call $.ajax just like you're doing.

By : ack


function queryX( args ) {
    var queryString = [ "XID=", args.XID, "&xNumber=", args.xNumber, "&xAmt=", args.xAmt ].join("");
    $.ajax({
    	url: "X.asp",
    	cache: false,
    	type:  "POST",
    	data:  queryString,
    	success : function( data ) {
    		return data;
    	}
    });
}
var myReturnData = queryX({
    XID : $("input[name='XID']").val(),
    xNumber : $("input[name='xNumber']").val(),
    xAmt : $("input[name='xAmt']").val()
});

EDIT:

This allows you the most flexibility, and if only the input values will change (but the query string variables won't), then you can pass in whatever you want as the value.



Edited:

You need to start with getting them all selected, then you can work with them.

To access just the xForm# elements, you can do a selector like this (you should check the syntax, I haven't run this, it's just an example):

$('form input[name*='xAmt']  ').each(function(){ alert( $(this).val() ); alert( $(this).parent().attr('name') + $(this).parent().attr('id') ); });

The form input[name*='xAmt'] means select any elements inside a form that contain the term xAmt. You can also do starts with, ends with, etc. See the links below.

When in the each loop, you can access each one as $(this). You can access it's parent form as $(this).parent(), so you can tell which form the input is in.

You might build the data in the loop, or do something else with them, and then make the post.

see:

http://docs.jquery.com/Selectors/attributeContains#attributevalue

http://docs.jquery.com/Selectors

http://docs.jquery.com/Each

http://docs.jquery.com/Attributes/attr#name

http://docs.jquery.com/Traversing/parent#expr

By : Eli


This video can help you solving your question :)
By: admin