How to get the attribute name value of a input tag using jQuery. Please help.
A better way could be using 'this', it takes whatever the name of the 'id' is and uses that. As long as you add the class name called 'mytarget'.
Whenever any of the fields that have target change then it will show an alert box with the name of that field. Just cut and past whole script for it to work!
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.mytarget').change(function() {
var name1 = $(this).attr("name");
alert(name1);
});
});
</script>
Name: <input type="text" name="myname" id="myname" class="mytarget"><br />
Age: <input type="text" name="myage" id="myage" class="mytarget"><br />
You need to write a selector which selects the correct <input>
first. Ideally you use the element's ID $('#element_id')
, failing that the ID of it's container $('#container_id input')
, or the element's class $('input.class_name')
.
Your element has none of these and no context, so it's hard to tell you how to select it.
Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name')
which would return (in your example) 'xxxxx'
.
Use the attr method of jQuery like this:
alert($('input').attr('name'));
Note that you can also use attr
to set the attribute values by specifying second argument:
$('input').attr('name', 'new_name')
var value_input = $("input[name*='xxxx']").val();
Give your input an ID and use the attr method:
var name = $("#id").attr("name");
While there is no denying that jQuery is a powerful tool, it is a really bad idea to use it for such a trivial operation as "get an element's attribute value".
Judging by the current accepted answer, I am going to assume that you were able to add an ID attribute to your element and use that to select it.
With that in mind, here are two pieces of code. First, the code given to you in the Accepted Answer:
$("#ID").attr("name");
And second, the Vanilla JS version of it:
document.getElementById('ID').getAttribute("name");
My results:
You can test for yourself here. The "plain JavaScript" vesion is over 35 times faster than the jQuery version.
Now, that's just for one operation, over time you will have more and more stuff going on in your code. Perhaps for something particularly advanced, the optimal "pure JavaScript" solution would take one second to run. The jQuery version might take 30 seconds to a whole minute! That's huge! People aren't going to sit around for that. Even the browser will get bored and offer you the option to kill the webpage for taking too long!
As I said, jQuery is a powerful tool, but it should not be considered the answer to everything.