it should be
$('<button/>').click(confCheck)
You need to pass a function reference as the parameter to click()
, don't invloke it ans sent the result
Question
I'm trying to create and add event listener to a button in jquery. I'm able to achieve this, but What is my problem is that when I click any of the button in the form, this event is triggering.
here is my code:
$('#submitPh').on('click',function(e){
e.preventDefault();
secCheck($(this).attr('id'));
});
function secCheck(invoker) {
console.log('called');
var id = 'secModal', title = '<h3>Security Verification</h3>',
body = $('<form/>').attr({'method': 'post', 'action': '', 'id': 'secCheck'}).append($('<div/>').addClass('form-group')
.append($('<div/>').addClass('controls')
.append($('<label/>').attr({'for': 'verPass'}).addClass('control-label').text('Please enter your password'), $('<input/>').attr({'type': 'password', 'id': 'verPass', 'name': 'verPass', 'value': '', 'placeholder': 'Enter your password'})
.addClass('form-control'))), $('<div/>').addClass('form-group').append($('<div/>').addClass('col-lg-10 warning-mes')),$('<div/>').addClass('form-group').append($('<button/>').click(confCheck()).attr({'type': 'button', 'id': 'secCheckSubmit'}).addClass('btn btn-default').text('Submit')));
createModal(id, title, body, invoker);
}
function createModal(id, title, body, invoker) {
var modal = $('<div/>').attr('id', id).addClass('modal fade')
.append($('<div/>').addClass('modal-dialog')
.append($('<div/>').addClass('modal-content')
.append($('<div/>').addClass('modal-header')
.append($('<button/>').attr({'data-dismiss': 'modal', 'area-hidden': true}).addClass('close').html('×'), title), $('<div/>').addClass('modal-body').html(body), $('<div/>').addClass('modal-footer')
.append($('<button/>').attr({'type': 'button', 'data-dismiss': 'modal'}).addClass('btn btn-default').text('Close')))));
if (!$('div#' + id).length) {
$('body').append(modal);
}
showModal('#' + id, invoker);
}
function showModal(sId, invoker) {
var $this = invoker;
var id = sId;
var $target = $(sId || (id && id.replace(/.*(?=#[^\s]+$)/, ''))); //strip for ie7
var option = $target.data('modal') ? 'toggle' : $.extend({remote: !/#/.test(id) && id}, $target.data());
this.modal = $target
.modal(option, this)
.one('hide', function() {
$this.is(':visible') && $this.focus();
});
}
function confCheck() {
alert();
}
This is how I did. But this was not producing the expected result as I stated above.
Please anyone help me to solve this problem...
Edit
Solution
it should be
$('<button/>').click(confCheck)
You need to pass a function reference as the parameter to click()
, don't invloke it ans sent the result
OTHER TIPS
You can use .appendTo() in this context
Try,
$('<button/>').appendTo('#button').click(sp.confCheck(func,data));
better you should give a class name for the newly created button and provide deligate for event listening
$('#button').append($('<button/>', { class: "test" }));
$("body").on("click", ".test", function () { });