Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript name array input selectors (name[sometext])

Tags:

How can I select a named input like this properly in jQuery without assigning ID's?

<input name="person[first]" type="hidden"> <input name="person[last]" type="hidden">  // Seems to be acting on multiple hidden elements instead of this named one // This sets the value of both of those hidden elements in some cases $("input[type=hidden][name=person[first]]").val('Test');  // So I've changed it to this. Is there a better way? $("input[name=person[first]]").val('Test'); 
like image 253
Ben Dauphinee Avatar asked Feb 12 '12 20:02

Ben Dauphinee


People also ask

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

Put the attribute value in quotes...

$("input[type=hidden][name='person[first]']").val();    // ---------------------^-------------^ 

From the docs for attribute-equals-selector...

attribute An attribute name.

value An attribute value. Can be either an unquoted single word or a quoted string.

Since you have more than just a single word, it should be quoted.

like image 191
user1106925 Avatar answered Sep 27 '22 15:09

user1106925


I'm pretty sure you're supposed to put in quotes any attribute selector's value that includes symbols with meaning in CSS. Like this:

input[type=hidden][name='person[first]'] 
like image 29
Niet the Dark Absol Avatar answered Sep 27 '22 17:09

Niet the Dark Absol