Page 1 of 1

jQuery Button Behavior: live('click') issue...

Posted: Wed Sep 24, 2014 10:04 am
by Wolf_22
I have the following jQuery:

Code: Select all

$('#section_3 button').live('click', '#section_3 button', function(e){
	e.preventDefault();
	var msg = "The following files will be deleted:\n";
	var flag = false;

	$('#section_2 li input[type="checkbox"]').each(function(){
		if($(this).attr('checked')){
			msg += '- '+$(this).attr('value')+"\n";
			flag = true;
		}
	});

	msg += "\nContinue?";
	if(flag){
		var response = confirm(msg);
		if(response){
			alert('File(s) deleted.');
			$('#main').submit();
		}else{
			alert('Delete cancelled.');
			return false;
		}
	}

	$('#main').submit();
});
The above code is attached to a button inside a form that has an action of "index.php" (it's supposed to be posting to itself). However, when I click on this button, the value doesn't show up in the PHP var_dump($_POST) that I have at the top of index.php. Funny thing is that when I comment-out "e.preventDefault();", it does. But doing this has the negative side effect of disabling the confirm logic... Arg!

What's the trick here? I'm obviously doing something wrong and I suspect it's got something to do with how I've handled everything with e.preventDefault()...

Any insight into this would be appreciated (apologies in advance if this has been covered countless times before)...

Re: jQuery Button Behavior: live('click') issue...

Posted: Wed Sep 24, 2014 12:27 pm
by requinix
Rather than use the button's onclick, attach yourself to the form's onsubmit event. Then, instead of calling submit() or returning false, do nothing for confirmation and do e.preventDefault() for a cancel.

Code: Select all

$('#main').live('submit', function(e){
        var msg = "The following files will be deleted:\n";
        var flag = false;

        $('#section_2 li input[type="checkbox"]').each(function(){
                if($(this).attr('checked')){
                        msg += '- '+$(this).attr('value')+"\n";
                        flag = true;
                }
        });

        msg += "\nContinue?";
        if(flag){
                var response = confirm(msg);
                if(response){
                        alert('File(s) deleted.');
                }else{
                        alert('Delete cancelled.');
                        e.preventDefault();
                }
        }
});