How to make form submission work? - javascript

When I press the register button, it doesn't submit. How can i make this work?
< script >
$(function() {
//adds the 'invalid' class if textfield is empty
$('button.btn').on('click', function(event) {
event.preventdefault();
if ('Register User' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
});
< /script>
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="Register User" name="createTask">Register</button>
</form>
I have also tried using "return false" instead of preventdefault(), still fails to submit successfully.

First of all, you need event.preventDefault() (capital D).
preventDefault stops the action the event is about to perform, which in this case would be the form submission. That's fine, because you want to validate the input, but it means you have to then trigger the form submission yourself if you want it to go through. The simplest way to do that given your current code is to check the number of .invalid fields and submit if there are none, like so:
$(function () {
//adds the 'invalid' class if textfield is empty
$('button.btn').on('click', function (event) {
event.preventDefault();
if ('Register User' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
// Submit if there are no errors
if ($('.invalid').length == 0) {
$('form').submit();
}
}
});
});

Related

Validating user input with try and catch with jQuery

I want to validate whatever the values of the inputs are using try and catch. Every time the user gives a wrong value I want a a message to appear next to the input box that filled wrong.
The problem is that the every time it executes, the wrong message appears in both input boxes and I don't want to put many conditions. I just want to make it as simple as possible. I don't have a clue what conditions I should use.
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i]);
} //for loop
function fn(exp, str) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
alert(e);
$("#empty1").fadeIn(3000);
$("#empty1").html(e);
$("#empty1").fadeOut(3000);
$("#empty2").fadeIn(3000);
$("#empty2").html(e);
$("#empty2").fadeOut(3000);
} //try and catch
} //function
}); //button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
Name<input id="name"><span id="empty1"></span></br>
</br>
Last Name<input id="lName"><span id="empty2"></span></br>
</br>
<button id='btn'>Click</button>
</body>
</html>
For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
<form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label><b>Password</b></label>
<input type="password" class="form-control" placeholder="Password" name="psw" id="psw">
</div>
<div class="form-group">
<label><b>Repeat Password</b></label>
<input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">
<span id='message'></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="save">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<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/jquery-validate/1.17.0/additional-methods.min.js"></script>
<script>
$("#myform").validate({
rules: {
psw: {
required: true
},
rpsw: {
equalTo: "#psw"
}
}
});
</script>
Since you want it according to what has been asked of you to do,
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i],i+1);
} //for loop
function fn(exp, str, no) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
//alert(e);
if($('#err').length==0)
$("#empty"+no).val('').addClass('error').after('<p style="display:inline;" id="err">'+e+'</p>');
} //try and catch
} //function
}); //button
});
where error class can have css like
.error{
border: 2px solid red;
background-color: #f7b9d9;
}

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Cannot make simple jQuery work

I'm learning jQuery, but I can't make this example work. I know it's quite simple but I don't know what I'm missing. I'm trying to add the class "invalid" in a textfield.
<script src="../jquery/jquery-1.8.2.js"></script>
<script src="../jquery/jquery.ui.effect.js"></script>
<script>
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
</main>
There is a syntax error in your Javascript. The corrected Javascript:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
});
Fiddle here: https://jsfiddle.net/s9x1Ldfm/
However I would add the return does not make a lot of sense. It returns false sometimes and void others. What exactly are you trying to do with that?
So, the problem in your code is that you are missing some closing ')' and '}'. The following will make it correct:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
} // end of for
return false;
} // end of if
}); // end of click
});
You can try to debug your javascript by using the debugger in the browser, by clicking F12. In the Element/Console section, you can see the error messages you have in your code. It will give you some hints regarding the error you have. Also, if you do not have any syntax problem, you are able to use
debugger;
In your code and when you run it in your browser with the debugger mode (F12), you can debug step by step into your code and look at the values of the variables and see how your program is behaving.
But, if in your code you just want to see if the input text is empty or not by the time the user click the button, you can try the following snippet:
<script>
$(function() {
$('#create_task').on('click', function() {
event.preventDefault(); // prevents submission
if ($('.validate').val().length > 0) {
$('.invalid').hide();
} else {
$('.invalid').show();
}// end of if
}); // end of click
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<div class="invalid" style="display:none">Invalid input</div>
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button id="create_task" class="btn" type="submit" name="createTask">Create Task</button>
</form>
</main>
Pay attention how I changed the name of button to id to detect the button without extra validation. I hope it helps.
Use event.preventDefault() to prevent the form submission.
Check out his fiddle.
Here is the snippet.
$('button.btn').click(function(event) {
event.preventDefault();
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
.invalid {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
Your code has number of issues. First of all, if you want to capture form submission use .submit function and not click on button. Otherwise, you can remove the form tag and capture the click on button element.
Additionally, you can loop through jQuery object using .each. Using for is definitely faster as it is a native JavaScript functionality. I have made a proof of concept on this jsfiddle.
See this code.
$(function () {
$('button.btn').on('click', function () {
if ('create_task' == $(this).val()) {
$('.validate').each(function (i, e) {
if ("" == $(e).val()) {
$('.validate').addClass('invalid');
} else {
$('.validate').removeClass('invalid');
}
})
}
})
});
.invalid
{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</main>
You have a syntax error as you haven't closed the $(function(){ in your script.
Moreover move your return false to an outer block (so that you'll prevent the default submit behaviour of the button) AND, use submit (which is same as using .submit() method) event as such:
$(function() {
$('button.btn').on('submit', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
return false;
});
});
NOTE: If you wanted, you could change the type='submit' to type='button' while triggering the click event, thus ridding you of returning false in your JavaScript code.

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

Form submits when "<button>" is clicked

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.

Categories