Validate form with dynamic button

I have jquery object(div) which i am generating dynamically based on search results, in that div there is a button(‘btn’), while click on that button I am enabling another button(‘btn1’), while clicking on ‘btn1’ I am doing form validation.
I want the validation should happen while clicking on the button(‘btn’) as well.

var foo = $('<div/>').addClass('myDiv').append($('<div/>').addClass('btn'));// dynamic div generating based on search results.

<div class="btn1" style="display:none;"></div>

$('document').on('click', '.btn', function(){

$('.btn1').on('click', function(){
	//form validation goes here

Tried in the below way: it is working and also it is colsing the popup as well, it should close only after clicking on ‘btn1’ only.

$('document ').on('click', 'btn', function(){

Hmm, I’m confused which button you are talking about :slight_smile: This is why this type of DOM manipulation is not ideal.
Assuming it’s the one you’re creating in jQuery you can save the element to a variable so that you can events to it.

var btnDiv = $('<div/>').addClass('btn')
var foo = $('<div/>').addClass('myDiv').append(btnDiv);
// Add foo to document somehow

btnDiv.on('click', function() {

The bottom method is using event delegation which lets you register events for elements that will get added later, it will work as long as the selector is specific. Consider adding a unique class or id to the button you want to target and it will work too.

@markbrown: Thanks for the response. I have tried in another way got the result mean while you had given another way, in future it will be useful.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.