why can't an element be accessed from the name attribute in Jquery
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";
});
});
The #
selector selects elements with a matching ID, not name.
You can select <input>
elements names textname
like this:
$('input[name="textname"]')
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.
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>
精彩评论