3

HTML:

<div id="div1">
  <div class="row" >
     <div class="span2" >
    <input type=button  value="" name="btn1"/>
    </div>
</div>
</div>

jQuery:

$(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?

1
  • name attributes of HTML Elements are not required to be unique. Nov 23, 2011 at 18:16

4 Answers 4

7

Your selector is looking for #div1 having attribute name=btn1. Try this.

$(document).ready(function() {
    $('#div1 input[name="btn1"]').val('test hello');
});
3

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(...);
1
  • tx i am aware of this. But i have 6 div with all the same button names only the values are different
    – alex
    Nov 23, 2011 at 18:21
1

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:

  • a lot easier to follow and maintain later
  • slightly more robust (because the .-row-button class can move from underneath #div1 and your jQuery code would still work)
  • faster
0

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');
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.