George Pittas
George Pittas

Reputation: 181

Jquery assign value to input

I have the following input field

<input type="text" name="location[state_id]" id="location[state_id]" value="" >

and i am trying to assign there a value with the following jquery

$("#location\\[state_id\\]").val("5");

but it does not working! It works only if the name of both is only location.

Thanks

Upvotes: 16

Views: 64116

Answers (4)

StaticVariable
StaticVariable

Reputation: 5283

try this

<input type="text" name="location[state_id]"class="input" id="location[state_id]" value="" >

$(".input").val("5");

or

you can use curt's answer:

$("input[name='location[state_id]'").val("5");

Upvotes: 10

henkieee
henkieee

Reputation: 1123

JQuery

$('input[name="location[state_id]"]').val(5);

Upvotes: 2

Curtis
Curtis

Reputation: 103348

If you wish to use the name as part of the selector, you can use the following selector:

$("input[name='location[state_id]'").val("5");

Demo

Upvotes: 8

npclaudiu
npclaudiu

Reputation: 2441

As # is an id selector, you could try to set the id of the input to a valid CSS id and let the name of the input the same (I assume that this format is required by a framework of some kind). For example, the HTML can look like:

<input type="text" id="location_state_id" name="location[state_id]" value="" />

and the jQuery expression:

$('#location_state_id').val('5');

Upvotes: 26

Related Questions