Form submits when "<button>" is clicked - javascript

I have an Account Create form. There is no submit button, just a <button>. Right now I have a jQuery validation running when the button is clicked. The validation is being run and the proper errors show up for it, but the form is then submitted and the page reloaded. Even though I have no submit button and not jQuery submit() function anywhere.
HTML:
<form id="accountCreate" method="POST" action="<?=site_url('account/create')?>">
<h3>Create an Account</h3>
<ul>
<li><input type="text" name="email" placeholder="Email..." /></li>
<li><input type="password" name="password" placeholder="Password..." id="password" /></li>
<li><input type="password" placeholder="Verify Password..." id="verifyPassword" /></li>
<li><button id="button">Create</button></li>
</ul>
</form>
JS:
$(document).ready(function() {
$('#button').click(function() {
var password = $('input#password').val();
var passwordV = $('input#passwordVerify').val();
if (password.length >= 6 && password.length <= 24) {
if (password == passwordV) {
} else {
$('div#error').css('display', 'inline');
$('div#error span.errorMessage').text('hey');
}
} else {
alert('yo');
return false;
}
});
});

When no type attribute is defined a <button /> acts as a submit button.
Add type="button" to fix this problem.
<button id="button" type="button">Create</button>
http://www.w3.org/TR/html-markup/button.html#button

You need to specify a default type= attribute for the button, as different browsers can use different defaults. In your case, it looks like the browser has defaulted to type="submit".

$(document).ready(function() {
$('#button').click(function() {
var password = $('input#password').val();
var passwordV = $('input#passwordVerify').val();
if (password.length >= 6 && password.length <= 24) {
if (password == passwordV) {
} else {
$('div#error').css('display', 'inline');
$('div#error span.errorMessage').text('hey');
}
} else {
alert('yo');
return false;
}
//Just add return false
return false;
});
});

You should add evt.preventDefault(); to make the submit only do what you want.

Related

How would you make an iframe if the value is true in javascript?

I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.

Email Validation with Materialize and jQuery

I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
<label for="email">Email Address</label>
</div>
<br></br>
<a class="waves-light btn red lighten-2 disabled" id="submit">Submit
<i class="material-icons right">send</i>
</a>
<br></br>
<br></br>
<br></br>
</form>
Here is the JavaScript/jQuery:
$(document).ready(function(){
$('.parallax').parallax();
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});
function checkValidity (current) {
let isValid = true;
if (!current.val()) {
isValid = false;
} else {
isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
submit.removeClass('disabled');
} else {
if (!submit.hasClass('disabled')) {
submit.addClass('disabled');
}
}
}
function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});
Please let me know what I'm doing wrong! Thanks!
You can use email type for your input and a button submit who will trigger validation input.
I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? )
You have to add jQuery Validation Plugin
$(document).ready(function(){
$('#survey input').on('keyup', function(){
var validator = $("#survey").validate();
if (validator.form() && validateEmail($('#email').val())) {
$('#submitButton').prop('disabled', false);
$('#submitButton').removeClass('disabled');
}
else{
$('#submitButton').prop('disabled', true);
$('#submitButton').addClass('disabled');
}
} );
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email.toLowerCase());
}
/*
Confirmation Window
*/
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
<label for="email">Email Address</label>
</div>
<button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
</form>
StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen
Another way to solve this is to add a regex field to your <input ... elements e.g.
<div class="input-field col s6">
<input id="email" type="text" class="validate" value="hello#email.com" regex="(?!.*\.\.)(^[^\.][^#\s]+#[^#\s]+\.[^#\s\.]+$)" required="" aria-required="true" value="hello#email.com" >
<label for="email">Email</label>
<span class="helper-text" data-error="Invalid email address."></span>
</div>
The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.
name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
age (only contain numbers - regex = ^\d+$).
NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.
To validate using e.g. JQuery - you would add listeners to each of your input elements: -
$(document).ready(function(){
$("input").on('input propertychange blur', function(event) {
var elm = event.currentTarget;
var val = elm.value;
var isValid = true; // assume valid
// check if required field
if (elm.hasAttribute("required")) {
isValid = val.trim() !== '';
}
// now check if regex
if (isValid && elm.hasAttribute("regex")) {
var regex = new RegExp(elm.getAttribute("regex"), 'g');
isValid = regex.test(val);
}
elm.classList.remove(isValid ? "invalid" : "valid");
elm.classList.add(isValid ? "valid" : "invalid");
updateButtonState();
});
});
function updateButtonState () {
var numOfInvalid = $('input.invalid').length;
if (numOfInvalid > 0) {
$('.submit-button').prop('disabled', true);
$('.submit-button').addClass('disabled');
}
else{
$('.submit-button').prop('disabled', false);
$('.submit-button').removeClass('disabled');
}
}
When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.
If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).
See the following CodePen to see everything in action: -
https://codepen.io/bobmarks/pen/oNGGvWq

Form Validation event.preventdefault not working

I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.
Any help or suggestion will be appreciated
Here is the code
<form id="accmanager" name="accmanager" action="view-acc.php" method="POST">
<h1>Account Management</h1>
<p>
<ul type="none">
<li><input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information</li>
<li><input type="radio" name="optaccmanager" id="addacc" /> Add Account</li>
<li><input type="radio" name="optaccmanager" id="tochangepass" /> Change Password
<ul id="changepass" type="none" style="display: none">
<li><input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" /></li>
<li><input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" /></li>
</ul>
</li>
</ul>
<input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>
and the script code
<script>
//form validation section
$(document).ready(function(){
var changepass = $("#changepass"),
addacc = $("#addacc"),
viewaccinfo = $("#viewaccinfo"),
tochangepass = $("#tochangepass");
addacc.on("click",function(event){
changepass.css("display","none");
$("#submitbtn").attr("value","Add Account");
});
viewaccinfo.on("click",function(event){
changepass.css("display","none");
$("#submitbtn").attr("value","View Account");
});
tochangepass.on("click",function(event){
changepass.css("display","inline");
$("#submitbtn").attr("value","Change Password");
});
$("form").submit(function(event){
var newpassword = $("#newpassword"),
confirmpassword = $("#confirmpassword");
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
});
});
Try to change this:
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
To:
if ((newpassword.val().length == 0) || (confirmpassword.val().length == 0)){
event.preventDefault();
newpassword.attr("title","Please enter new password");
return false;
}
Thanks you all for your help guys I sorted the bug by changing the if block expression.
From previous code:
$("form").submit(function(event){
var newpassword = $("#newpassword"),
confirmpassword = $("#confirmpassword");
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
});
To new code:
$("form").submit(function(event){
if ($("#tochangepass").is(":checked")){
if ( ($("#newpassword").val().length == 0) || ($("#confirmpassword").val().length == 0) ) {
event.preventDefault();
newpassword.attr("title","Please enter new password");
}
else {
return true;
}
}
}

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

onsubmit() form on mobile browser

I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true

Categories