Reputation: 4914
<div id="div1">
<div class="row" >
<div class="span2" >
<input type=button value="" name="btn1"/>
</div>
</div>
</div>
$(document).ready(function() {
$('#div1[name="btn1"]').val('test hello');
});
Why doesn't this work?
Where
$(document).ready(function() {
$('[name="btn1"]').val('test hello');
});
seems to work but i have a of other divs which i need to populate with values.
Can I reuse an input element's name or must this be unique?
Upvotes: 3
Views: 27965
Reputation: 2562
You've already gotten several working solutions, but I would like to suggest something else. Why don't you add a class to your button element? Something like:
<div id="div1">
<div class="row" >
<div class="span2" >
<input type="button" class="-row-button" value="" name="btn1"/>
</div>
</div>
</div>
Now, your selector is just $(".-row-button").val("test hello");
Why does it matter? Well, DOM traversal is really expensive, and a selector like $("#div1 [name='btn1']")
is much less efficient than a class selector. That's because the simple space between #div1
and [name='btn1']
means jQuery is going to search through all levels of child controls under #div1
. That's a bad thing.
Even if your page is really small, you should get in the habit of doing things like this now. This change will make your jQuery code:
.-row-button
class can move from underneath #div1
and your jQuery code would still work)Upvotes: 1
Reputation: 69905
Your selector is looking for #div1
having attribute name=btn1
. Try this.
$(document).ready(function() {
$('#div1 input[name="btn1"]').val('test hello');
});
Upvotes: 7
Reputation: 218722
The below code will get input element under div1 and set the text to "test hello"
$(document).ready(function() {
$('#div1').find("input").val('test hello');
});
Upvotes: 0
Reputation: 532435
The selector you are using is trying to find a DIV with the name attribute set to btn1
. You should just be looking for either the input by name or an input with that name in the DIV. Note that names do not need to be unique, though ids do.
$('#div1 [name="btn1"]').val(...); // the space makes all the difference
If you only have one element on the page with that name, you can simply use
$('[name="btn1"]').val(...);
Upvotes: 3