d-man
d-man

Reputation: 58083

jquery form field by form object

I have 2 different forms, both forms contains input fields with same field id how can get input field with respect to form object using jquery.

<form name"f1">
<input type="text" id="quantity" />
</form>

<form name"f2">
<input type="text" id="quantity" />
</form>

Upvotes: 0

Views: 392

Answers (5)

Diego
Diego

Reputation: 16714

You are not supposed to use the same ID more than once in a document.

Anyway this function could do it:

function getFieldByForm(anyForm, fieldId) {
    if(typeof(anyForm) == "string")
        anyForm = $("#" + anyForm);
    return anyForm.find("#" + fieldId);
}

You can call the funcion on any of this two ways:

getFieldByForm($("form[name='f1']"), "quantity");

or

getFieldByForm("formId", "quantity");

For the second one you need the forms to have ID.

Here you have a working example.

Upvotes: 0

Tomgrohl
Tomgrohl

Reputation: 1767

First you need to make your ID's unique, maybe classes may work better for you:

<form id="f1" name"f1">
    <input type="text" id="quantity" class="quantity" />
</form>

<form id="f2" name"f2">
    <input type="text" id="quantity2" class="quantity" />
</form>

form1Qty = $('form[name="fl"] .quantity').val();
form2Qty = $('form[name="f2"] .quantity').val();

//OR

form1Qty = $('#fl .quantity').val();
form2Qty = $('#f2 .quantity').val();

Upvotes: 0

Boopathi Rajaa
Boopathi Rajaa

Reputation: 4729

same ID ?? It violates the XHTML standards . you can do without jquery.. this will faster

document.forms["f1"].name1

with

<form name="f1"><input name="name1" /></form>

Upvotes: 0

pilif
pilif

Reputation: 12718

You must not use the same ID multiple times on the same document according to the (X)HTML specification.

Now, all browsers let you get away with that, but there's no way to select the second form via an ID selector as document.getElementById() will only return the first one.

I would fix the markup so the IDs are distinct. If that's not possible, select the input by going via the form:

$('form[name=f2]>input[type=text]:eq(0)')

or

$('form[name=f2]>#quantity'); // but please fix the IDs

Also, I would recommend giving the forms (distinct) IDs too as selecting by name can be very expensive in IE which has to go through all the forms on a page and compare name attributes.

Upvotes: 2

duncan
duncan

Reputation: 31912

form1_quantity =    $('form[name="fl"] #quantity');
form2_quantity =    $('form[name="f2"] #quantity');

Upvotes: 0

Related Questions