Peter Stuart
Peter Stuart

Reputation: 2434

jQuery finding the correct id

I have a HTML script like this:

    <form id="no1">
      <input id="title" type="text" />
<input type="submit" />
    </div>

    <form id="no2">
      <input id="title" type="text" />
<input type="submit" />
    </div>

I then have a validation script using jQuery. However I would like it to validate the form which has been submitted.

At the moment when I click sumit the jQuery validates the wrong input (because they both have the same id name).

I tried this code, but it didn't work (the "this" is the form element):

var title = $(this).("input#title").val();

Upvotes: 1

Views: 71

Answers (4)

wkm
wkm

Reputation: 1762

Each ID on the page must be unique: http://webdesign.about.com/od/css/f/blfaqmultiIDs.htm

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532555

HTML ids should be unique. You should be using unique ids with the same name, if the posted element needs to have the same name for both forms.

<form id="no1"> 
  <input id="title1" name="title" type="text" /> 

<form id="no2"> 
  <input id="title2" name="title" type="text" /> 

Your code can then be modified as:

$(this).find("[name='title']").val();

Assuming that this refers to the form element being submitted.

Upvotes: 3

Indranil
Indranil

Reputation: 2471

Try this

$(this).find('input#title').val()

Upvotes: 1

JesseBuesking
JesseBuesking

Reputation: 6596

Try

$(this).find('input#title').val();

Upvotes: -1

Related Questions