AnonymousObject AnonymousObject - 21 days ago 9
Javascript Question

how to select single element value which created dynamically in html using jquey/ Javascript?

i have a scenario like this,

for (var k in active) {
notifications.append(
'<a href="javascript:toast();">' +
'<div>' +
'<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
'</input>'+
'<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
'<span>' +
'<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
'<br/>' +
'<span class="time">Just Now</span>' +
'</span>' +
'</div>' +
'</input>'+
'</a>');
}


i created dynamic elements using jade template engine.
here i need to identify each
<a>
click and i nedd to get the value of hidden field.

function toast() {
var grade;
//var phone_number=document.getElementById('phone_number').value;
$.each($('.phone_number'), function () {
grade = $(this).val();
alert(grade);
});
}


by doing this i got a loop of value. which i didn't want. i need single item value. how to solve this ?

Answer Source

notifications = $(".notifications")

active = [{ phone_number: "982334",expiry_count: "1"},
         { phone_number: "982334",expiry_count: "1"}]
var k;
for (var k in active) {
         
        notifications.append(
            '<a href="javascript:toast();">' +
            '<div>' +
            '<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
            '</input>'+
            '<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
            '<span>' +
            '<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
            '<br/>' +
            '<span class="time">Just Now</span>' +
            '</span>' +
            '</div>' +
            '</input>'+
            '</a>');
    }
    
    
      $(document).on('click', 'a', function(){
         
          alert($(this).find('.phone_number').val())
    })
      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class="notifications"></div>

Its simple.Try this

    $(document).on('click', 'a', function(){
          alert($(this).find('.phone_number').val())
    })