My code has been given below . Why i am getting undefined? Please help me out.
//HTML is here
<input type="hidden" id="element_id">
//Jquery code is here
$('#student_update_form').on('submit', function(event) {
event.preventDefault();
var id = $(this).attr("element_id");
alert(id);
});
My code has been given below . Why i am getting undefined? Please help me out.
//HTML is here
<input type="hidden" id="element_id">
//Jquery code is here
$('#student_update_form').on('submit', function(event) {
event.preventDefault();
var id = $(this).attr("element_id");
alert(id);
});
Share
Improve this question
asked Jun 19, 2020 at 3:53
MsM RobinMsM Robin
291 silver badge6 bronze badges
3
-
using
$(this)
here you are referring toform
not your hidden input field . – Swati Commented Jun 19, 2020 at 3:56 -
What are you trying to achieve, and how does your
form
looks like? – Thum Choon Tat Commented Jun 19, 2020 at 3:56 - What exactly you want to get? As per your code, you will get the value of "element_id" appended to the form. Describe what exactly you want to do. – Manikanta Chinta Commented Jun 19, 2020 at 3:57
3 Answers
Reset to default 3Short answer: just
$('#element_id').attr('id')
To selects a single element with the given id attribute:
$('#id')
it equivalent to document.getElementById()
in Javascript: https://api.jquery./id-selector/
To get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
.attr()
https://api.jquery./attr/
You get undefined
because
$(this)
does not refer to<input type="hidden" id="element_id">
, it refer to the form hasid='student_update_form'
- and this form does not has an attribute named:
element_id
, so js returnundefined
You can try:
var id = $('#element_id').attr('id');
alert(id);
$('#student_update_form').on('submit', function(event) {
event.preventDefault();
var id = $("#element_id").val();
alert(id);
});
There's no need to use attr, you can use id directly.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744757692a4591980.html
评论列表(0条)