How to get the value of a specific form variable using jQuery

How to get the value of a specific form variable using jQuery.

I have several forms on the same page and the same variable name in each form, I want to read the value of the text field using the form name.

Please, help

thank

+3
source share
4 answers

To find a set of inputs with a specific name:

$(":input[name='" + name + "'")...

You need to somehow define the form if the same name is used in different forms. For instance:

<form id="one">
  <input type="text" name="txt">
</form>
<form id="two">
  <input type="text" name="txt">
</form>

will be selected with:

$("#one :input[name='txt']")...

Generally speaking, it is a bad idea to use attribute selectors. A good habit to join is to give all of your fields unique field identifiers so you can do this:

$("#fieldId")...

, :

$(":input.fieldclass")...

val() .

+8

$('form[name=foobar] #yourfieldid')

CSS2

+2

You can use simple javascript

var formField = document.forms[form_index].field;

or

var formField = document.formName.field;

or

var formField = document.forms["formName"].field;

or jquery

var $formField = $('form[name="formName"] > input[name="fieldName"]');

Updated my jQuery statement. It only accepts every field in a form with that name.fieldName

+1
source

I have known for many years since the question. However, here is a simple selector:

var $field = $('#formId #fieldId'); var value = $field.val();

0
source

Source: https://habr.com/ru/post/1734512/


All Articles