javascript - How to get id from html using Jquery? - Stack Overflow

My code has been given below . Why i am getting undefined? Please help me out.HTML is here<input t

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 to form 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
Add a ment  | 

3 Answers 3

Reset to default 3

Short 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 has id='student_update_form'
  • and this form does not has an attribute named: element_id, so js return undefined

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

相关推荐

  • javascript - How to get id from html using Jquery? - Stack Overflow

    My code has been given below . Why i am getting undefined? Please help me out.HTML is here<input t

    5小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信