tags:

views:

34

answers:

3

what is the main reason that we cannot access the element from its name attribute rather it can be accessed from id attribute

<input type="text" name="textname" id="textid" value="">
<input type="button" name ="buttonname" id ="buttonid" value ="button"

$(document).ready(function(){
    $("#buttonid").click(function(){
        $("#textname").val ="text1";//doesnot  work 
        $("#textid").val ="text1";
    });
});
+1  A: 

Have you looked at the API which has full examples?

$('[name="something"]')

for val,

$('[name="something"]').val('set to this')

It's kind of pointless to reference by name if that element already has a unique ID and you are only targeting it, though.

meder
+4  A: 

The # selector selects elements with a matching ID, not name.

You can select <input> elements names textname like this:

$('input[name="textname"]')
SLaks
A: 

You actually can using this syntax.

$("input[name='mycontrolname']")

The reason it isn't the standard way of referencing elements is that the name element of a tag doesn't have to be unique, whereas the ID does.

For example, with radio buttons it is common to code them like so (note the name attributes):

<form name="myform" id="myform">
 <input type="radio" id="myRadio1" name="myradio" value="1">one
 <input type="radio" id="myRadio2" name="myradio" value="2">two
 <input type="radio" id="myRadio3"name="myradio" value="3">three
</form>
JohnFx