8

We have two divs: How to select all the input field as an array with name="divText" that are inside "div2".

//Body of div1

<div id="div1>
<input type="text" name="divText" value="v1" />
<input type="text" name="divText" value="v2"/>
<input type="text" name="divText" value="v3"/>
</div>

//Body of div2

<div id="div2>
<input type="text" name="divText" value="q1" />
<input type="text" name="divText" value="q2"/>
<input type="text" name="divText" value="q3"/>
</div>
2
  • 1
    If your actual HTML is exactly the same as exposed here, you could simply do this : $('#div2').children(). Commented Jan 31, 2014 at 11:09
  • 1
    I assume you know about the descendant selector. If not, you really should read jQuery's documentation: api.jquery.com/category/selectors. Also check out the tutorial: learn.jquery.com/using-jquery-core/selecting-elements Commented Jan 31, 2014 at 11:11

5 Answers 5

12

Use Attribute Equals Selector [name="value"] along with ID Selector (“#id”). There is error in your html the closing quote of div id div1 and div2 is missing as well.

Live Demo

$('#div2 input[name="divText"]')
Sign up to request clarification or add additional context in comments.

2 Comments

as a note. This will fulfill the requirement in the title but selects more broadly than the post suggests. The post talks of input elements, where this selects all elements. Which might be correct. It will also select all children of children of the div that has the specified name. Which might or might not also be correct
Thanks @RuneFS for reminding, updated.
0

to get input field as an array, use .get():

var inpfromdiv2=$('#div2').find('input[name="divText"]').get();

Comments

0

Use the attribute selector

$("#div2 > input[name='divText']")

The jquery selector isn't an array but can for a lot of purposes be treated as such

Comments

0

Another way :

$("#div2 input[type=text]")

Comments

0

As @adil answered it is the right way to do what you asked, but I think it is a better practice to put a class and then select it. For example:

<div class="some_class">...</div>
<span class="some_class">...</span>

$('.some_class')

this what you are not constrained for any tag type.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.