简体   繁体   中英

How to get ID of Button(onClick) which is created dynamically in javascript

How to get ID of button which is created by using following JS. I want to set Button's ID on as label's text.

function addnewsubj(){
var a = $("#subjname").val();

if(a!==""  ){
    $('.techsubj').append(
    '<div class="row sub'+ a +'" id="sub'+ a +'">'+
        '<div class="col-xs-6 col-md-4">'+
            '<a href="#fourth" id="'+ a +'" class="btn btn-info" >'+ a +'</a>'+
        '</div>'+
        '<div class="col-xs-12 col-sm-6 col-md-8">'+
            '<div class="progress">'+
                '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">'+
                    '<span class="sr-only">60% Complete (warning)</span>'+
                '</div>'+
            '</div>'+
        '</div>'+
    '</div>'
    );
}
else{
    alert("Text Box is empty");
}}

HTML

<label id="subjTitle">  </label>

You don't have a button anywhere. If you mean the anchor element that is styled as a button,

$('subjTitle').text($('.techsubj .btn').attr('id'))

Or, you could always explicitly create it with an ID, or best of all you could create the content as a DOM hierarchy instead of as a HTML source and just keep the reference to the "button" object around.

use jquery 'on' method for dynamic event. use this code:

$(document).on('click','.btn-info', function(){
  $('#subjTitle').text($(this).attr('id'));
});

if you are using jquery below version 1.7 than you may use "live" or "delegate" for dynamic element.

Here is a little Example:

HTML :

  <div id='th'></div>

Jquery:

  $('#th').append('<div id="rock">this is Dynamo</div>');

  alert($($('#th').children('div')[0]).attr('id'));

may it helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM