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>
bpbhat77
  • 529
  • 1
  • 6
  • 19
  • 1
    If your actual HTML is exactly the same as exposed here, you could simply do this : `$('#div2').children()`. –  Jan 31 '14 at 11:09
  • 1
    I assume you know about the descendant selector. If not, you really should read jQuery's documentation: http://api.jquery.com/category/selectors/. Also check out the tutorial: http://learn.jquery.com/using-jquery-core/selecting-elements/ – Felix Kling Jan 31 '14 at 11:11

5 Answers5

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"]')
Adil
  • 146,340
  • 25
  • 209
  • 204
  • 1
    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 – Rune FS Jan 31 '14 at 11:07
  • Thanks @RuneFS for reminding, updated. – Adil Jan 31 '14 at 11:08
0

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

var inpfromdiv2=$('#div2').find('input[name="divText"]').get();
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
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

Rune FS
  • 21,497
  • 7
  • 62
  • 96
0

Another way :

$("#div2 input[type=text]")
4b0
  • 21,981
  • 30
  • 95
  • 142
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.

vlio20
  • 8,955
  • 18
  • 95
  • 180