I want to check if there's at least one checkbox that checked in a form after the submit button is clicked, if no, the the user should get message and the form SHOULDN'T be submit, so I wrote this code:
jQuery(document).ready(function ($) {
$('#price_quote_create_invoice').click(function () {
$('.price-quotes-table input[type="checkbox"]').each(function () {
if ( $(this).is(':checked') ){
$('#post').submit();
return false;
} else {
alert("You didn't chose any checkbox!");
return false;
}
}) ;
});
});
However, after I press ok on the alert box, the form does submit.
Any idea why this is happening?
Your code is almost right.
You return false on a click event but what you really want to do is to stop the submit event.
Change like this.
$('#yourFormId').submit(function(){
if (!$(this).find('input[type="checkbox"]:checked').length) {
alert("You didn't chose any checkbox!");
return false;
}
});
alert('You didn't chose any checkbox!');
You have an additional comma in your alert..
You can use event.preventDefault() to do this. event is the first argument of your click function. Reference
Related
I have a form which is submitted using Ajax.
If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.
If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.
The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.
I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.
function check() is attached to the submit button.
Any and all advice is welcome.
If I can provide any additional information, let me know.
Thank you
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
As chandan suggested, I edited function check() and it works.
RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.
Anyway, this is the code that does the job:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
Function check() should work without any edits then.
Also, see code from this question
I have a button outside of the form that when pressed, submits my form. That form has an event on it for onSubmit that fires off and then just does some form checks, making sure fields are present. At the end of the form, I return true and nothing happens. Can't seem to figure this out. Appreciate the extra set of eyes. I did verify that that function is being called and makes it all the way past the checks, just nothing happens. Here's the code:
$(document).on('click','.but_addTask',function(e){
e.preventDefault();
$('#addTaskForm').submit();
});
$(document).on('submit','#addTaskForm',function(e){
e.preventDefault();
var description = $('#description').val();
var dueDate = $('#dueDate').val();
if(!$('.taskClientID').length){
alert('Please add client(s) to task');
$('#taskClientSearch').focus();
return false;
}
if(description==""){
alert("Please enter a description")
$('#description').focus();
return false;
}
if(!$('.taskAuditorID').length){
alert('Please add owner(s) to task');
$('#taskOwnersSearch').focus();
return false;
}
if(dueDate==""){
alert("Please enter a dueDate")
$('#dueDate').focus();
return false;
}
console.log('made it!');
return true;
});
You already called e.preventDefault(); at the start of the callback, which suppresses the default behaviour of the event (in this case of course, that behaviour is to submit). By the time you return true it's too late.
If you remove that line, you should be ok.
Docs: https://api.jquery.com/event.preventdefault/
I am trying to create an alert, to insure that the user is submitting the correct information and if 'Ok' is clicked rather than cancel, the link is clicked and <a> sent. I have nearly achieved it, the alert activates, however does not activate if ok is clicked. Unfortunately, I am not a js wizard, yet..
EDIT :
click => preventDefault => alert (yes, no) if yes(send) if no dont.
<script>
jQuery(document).ready(function($){
$("input.btn-default").click(function(e){
e.preventDefault();
var answer=confirm('Are you sure that you want to do this?');
if(answer == true){
///not sure how to remove the prevent default and send link?!
}
else{
return;
}
});
});
</script>
Try the following code using return false; if the user cancel confirm dialog and window.open( $(this).att('href') ); to open the link when he user click OK :
$("input.btn-default").click(function(e)
{
e.preventDefault();
if( confirm('Are you sure that you want to do this?') )
{
window.open( $(this).att('href') );
}
else
{
return false;
}
});
Hope this helps.
confirm() is modal, so you just need to check for answer:
jQuery(document).ready(function ($) {
$("input.btn-default").click(function (e) {
var answer = confirm('Are you sure that you want to do this?');
if (!answer) {
e.preventDefault();
}
});
});
I have initialized my form submission like following:
$(document).ready(function() {
$("#my_form").submit(function(e) {
...
...
}
}
As you see above, it is in $(document).ready(...). When user press "Submit" button on UI, the form will be submitted.
But, How can I also trigger this form submission in Javascript besides user input (e.g. press submit button on UI)?
Call the submit() DOCs method on the form.
$("#my_form").submit();
You can use $("#my_form").submit();
$(document).ready(function () {
$("#SubmitForm").click(function (e) {
var textContent = $("#TextContent").val();
textContent = jQuery.trim(textContent);
if (textContent == "") {
alert("Content field cannot be empty.");
$("#TextContent").focus();
return false;
}
else{ $("#my_form").submit();
}
});
});
I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}