After my button click, I would check if my text fields are not empty. My check works, but if I show my message it's show for a few seconds. Probably the duration of my button click. Here is some code I've tried.
<form>
<div id="errorblock">
<p id="errortext">Error.</p>
</div>
<!-- here are my input fields-->
<button>Send</button>
</form>
This is where I add my event listener after initialisation of the page:
document.getElementsByTagName("button")[0].addEventListener("click", function(){
sendEmail();
});
function sendEmail() {
//check if all fields are fill in. If not do this code;
document.getElementById("errortext").innerHTML = "Fill in all the fields please.";
var errorblock = document.getElementById("errorblock");
errorblock.style.visibility = "visible";
errorblock.style.height = "46px";
}
Can anyone help me?
Thanks
By default HTMLButtonElement has type="submit". It means that on button click the form is submitted. You need to make sure you prevent this submission in case of errors in the form. For example by calling preventDefault methods of the event object:
document.getElementsByTagName("button")[0].addEventListener("click", function (e) {
if (!sendEmail()) {
e.preventDefault();
}
});
function sendEmail() {
//check if all fields are fill in. If not do this code;
document.getElementById("errortext").innerHTML = "Fill in all the fields please.";
var errorblock = document.getElementById("errorblock");
errorblock.style.visibility = "visible";
errorblock.style.height = "46px";
// if there are errors return false
// return true if input is correct
return false;
}
Also I recommend to listen onsubmit event on the form instead of button click event:
document.querySelector("form").addEventListener("submit", function (e) {
if (!sendEmail()) {
e.preventDefault();
}
});
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've just looked at the form validation section in Bootstrap 4.4 (https://getbootstrap.com/docs/4.4/components/forms/#how-it-works) and have implemented the code into my project, the code example and script implementation to trigger the validation looks great!
I was wondering whether it's possible to implement this validation as the user is filling out the form rather than when trying to submit the form?
For instance, if I have two inputs, First Name & Last Name, both of which are required, when I change to the Last Name field, can I get the validation check to trigger for the field I've just filled out?
E.g, validation on the fly?
My current validation (triggered when clicking the form submit button) is:
function validateForm () {
var forms = document.getElementsByClassName('needs-validation')
var validation = Array.prototype.filter.call(forms, function(form) {
console.log(form.checkValidity())
if (form.checkValidity() === false) {
event.preventDefault()
event.stopPropagation()
// get the "first" invalid field
var errorElements = document.querySelectorAll('.form-control:invalid')
// scroll the user to the invalid field
window.scrollTo(0, getOffset(errorElements[0]).top)
}
form.classList.add('was-validated')
})
}
The checkValidity() function works on individual inputs too. Bind the blur handler to each input, and then add class is-valid/is-invalid to each input after validation...
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom validation styles
var inputs = document.getElementsByClassName('form-control')
// Loop over each input and watch blue event
var validation = Array.prototype.filter.call(inputs, function(input) {
input.addEventListener('blur', function(event) {
// reset
input.classList.remove('is-invalid')
input.classList.remove('is-valid')
if (input.checkValidity() === false) {
input.classList.add('is-invalid')
}
else {
input.classList.add('is-valid')
}
}, false);
});
}, false);
})()
https://codeply.com/p/mzBNbAlOvQ
You can add a blur event listener to the inputs, that call your function once triggered.
const inputs = document.querySelectorAll("#form input");
inputs.forEach(e => e.addEventListener("blur", validateForm));
<form id="form">
<input type="text" placeholder="text input">
<input type="text" placeholder="text input">
</form>
#Ryan H To the #Zim code; added or brought back bootstrap's default code (while allowing real-time validation) to not let form submission happen if there are invalid fields on submission. The full code looks like below.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var form_Validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}else{event.preventDefault(); processForm();}
form.classList.add('was-validated');
}, false);
});
//Below code to check every input field
var inputs = document.getElementsByClassName('form-control');
var input_Validation = Array.prototype.filter.call(inputs, function(input){
input.addEventListener('blur', function(event){
input.classList.remove('is-invalid')
input.classList.remove('is-valid')
if (input.checkValidity() === false) {
input.classList.add('is-invalid')
}else{input.classList.add('is-valid')}
// form.classList.add('was-validated');
}, false);
});
//End of block that checks each input field
}, false); //window load event listener container
})();// Immediately invoked function container end
I have form with input and submit button. I would like to open popup while user fills e-mail address and click submit button. In popup will be other button which clicked should make action from the submit button with input value. I have something like this so far:
$('form').on('submit', function (e) {
e.preventDefault();
//function opening popup goes here...
// confirm button in popup
$('#confirm_button').on('click', (e) => {
e.preventDefault();
$(this).unbind('submit').submit();
});
});
The problem is that I have no idea, how to pass value from the input to the confirming function in popup.
Thanks for your help!
To get a single value from a form, example of af an input element in html with id attribute set to username:
var userName = $('#username').val();
or to get all elements of a form where its id attribute is set to myform:
$("#myform").serialize()
To pass input value to other function you must first create a function:
function doSomething(first) {
if (first) {
console.log(first);
alert(first);
}
}
$('form').on('submit', function (e) {
e.preventDefault();
//function opening popup goes here...
});
// confirm button in popup
$('#confirm_button').on('click', (e) => {
e.preventDefault();
var userName = $('#username').val();
$(this).unbind('submit').submit();
doSomething(userName);
});
Note that the important part here is to use #id for accessing values in you page, this is how you access it with popup or not.
You could store the information in a variable or mutliple, for example:
var name;
$('form').on('submit', function (e) {
e.preventDefault();
// Get name from input and store it in the name variable.
name = $('#name').val();
//function opening popup goes here...
// confirm button in popup
$('#confirm_button').on('click', (e) => {
e.preventDefault();
$(this).unbind('submit').submit();
});
});
You could then use name anywhere else in the JS
I am trying to create an agree to terms and agreements. However, when the button is unchecked and the user hits submit, I want it to present the user with an alert telling him to agree to the terms. At first, I made it to where the user couldn't even click on the submit button when the checkbox is unchecked, however, I want the user to be able to click it so he can be alerted with an error. I can't seem to get my code to work no matter what.
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
if(document.getElementById('submit').click() & document.getElementById("myCheck").checked = false;){
alert("Hello! I am an alert box!!");
}
}
<input type="checkbox" id="checkme"/>
I agree to the terms & service<br />
<input type="submit" name="sendNewSms" class="md-trigger blue-texture postbit-button-big md-pointer" data-modal="modal-five" id="submit" value=" Send " onclick="$('.md-modal').removeClass('md-show');" disabled/>
I want the user to be able to click it so he can be alerted with an error
Remove the disabled from the submit button.
Remove the checker.onchange = function(){
Make sure to event.preventDefault(); browser triggering form submits or other default evett actions
All you need:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('submit');
sendbtn.onclick = function( event ){
event.preventDefault();
if(!checker.checked){
alert("You must agree to our terms of service");
}
};
Note that you might want to do the above not on button Click but on formID.onsubmit (the form can always be submitted even without a Button click. Not seeing your form this is all I can suggest.)
P.S:
Developer Console (access by F12 and click Console) helps to debug such errors like &/&& =/=== missing ; etc...
P.S2: when using only JS a handy function to fast-get an element by ID can be achieved with a nice little function i.e:
function ID(id){return document.getElementById(id);} // ...and use like:
var submitBtn = ID("submit");
document.getElementById("myCheck").checked = false; is assigning it to false. If you want to check if it is false, you need this
document.getElementById("myCheck").checked === false;
Remove disabled from submit and the other js and use this:
$('#submit').click(function(e) {
if (!$('#checkme').is(':checked')) {
e.preventDefault();
alert('Check the box!');
} else {
$(e.currentTarget).parent('form').first().submit();
}
});
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();
}
});
});