I have two links on a page. When I click on the second link, it displays certain fields. I want to write a onkeyup()
event handler for one of the fields. I have written the code like this and I'm missing something. Please help.
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function(){
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
//This is not working. inputBox is declared as global variable.
inputBox.onkeyup = function(){
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
}
});
Please point out my mistake. TIA :)
UPDATE: I can get the element by ID only after clicking the cc_sec
link. So I cannot do inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
in the beginning of the ready
function.
use jQuery .on
to add eventhandler to dynamically created elements.
$('body').on("keyup","{!$Component.pg.pb.cardForm.cardnumber}",function(){
alert($(this).val());
document.getElementById('printCardNo').innerHTML = $(this).val();
});
You have two options
call document.getElementById in document ready:
var inputBox; $().ready(function() { inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); //cc_sec is the id of the second link in my page. $('#cc_sec').click(function() { alert(inputBox.id); //This alert is giving me the ID of the element correctly. }); inputBox.onkeyup = function() { alert(inputBox.value); document.getElementById('printCardNo').innerHTML = inputBox.value; }; });
or set onkeyup in click event:
var inputBox; $().ready(function() { //cc_sec is the id of the second link in my page. $('#cc_sec').click(function() { inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); alert(inputBox.id); //This alert is giving me the ID of the element correctly. inputBox.onkeyup = function() { alert(inputBox.value); document.getElementById('printCardNo').innerHTML = inputBox.value; }; }); });
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.