Hi, I have written a webSite on Shopify and I want to disable my button and add some customs CSS class to my input if the input is not filled on my 4steps form.
I've written a piece of code with what I remember from Jquery it's been a long time since I've used this language.
This is the jQuery funct:
$(document).ready(function () {
$("#submitButton, #btn0, #btn1, #btn2").click(function () {
ValidateForm();
});
function ValidateForm() {
var invalidForm = false;
var index = 0;
var button = document.querySelector("#submitButton, #btn0, #btn1, #btn2");
$("#form__form--stepForm-" + index + "input.form__form--input").each(function () {
if ($(this).val() < 1) {
invalidForm = true;
}
});
if (invalidForm === true) {
button.disabled = true;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationInvalid");
} else if (invalidForm === false) {
button.disabled = false;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationValid");
index++;
}
}
});
I made all my inputs like this one:
<div class="3/3 3/3--thumb 3/3--pocket grid__cell--center">
<input type="text" id="form__form--lastnameInput" name="contact[lastname]"
class="form__form--input form__form--validation" placeholder="Nom *" value required>
<div class="form__form--invalidFeedback">Veuillez saisir votre nom.</div>
</div>
And the button like this:
<button id="btn0" type="button" class="button button--primary form__form--button"
aria-label="SUIVANT" title="SUIVANT">
{% include 'icon-arrow-slider' %}
SUIVANT
</button>
As you can see it's a very basic function for the jquery and a classic HTML input but it doesn't block the button and doesn't make the CSS work either. I'd like to understand why and how to make it work for this site and the following thanks for your time and help, take care of yourself!
Your value checking is always false, consider using length function instead:
if ($(this).val().length < 1) {
invalidForm = true;
}
You may also need to prevent default behavior of your form. Instead of listening to the click, listen the submit event:
$("#form__form--contactWrapper").on('submit',function (e) {
e.preventDefault(); //the form is not sent yet
ValidateForm();
});
Then at the end of your function ValidateForm you can send it when you have all your needed validations done, like this:
$("#form__form--contactWrapper").submit();
I have get rid of all error by doing a big refacto of my code i share you my code
$(document).ready(function () {
$('[to-step]').on('click', function () {
var to_step = $(this).attr("to-step");
var current_step = $(this).closest('[stepform]').attr("stepform");
var form_error = false;
if (!($(this).hasClass("previous-btn"))) {
$('[stepform="' + current_step + '"] .form__form--input').each(function () {
if ($(this).val().length == 0) {
$(this).addClass("input--error");
form_error = true;
} else {
$(this).removeClass("input--error");
}
});
}
if (!form_error) {
if (current_step < 4 || $(this).hasClass("previous-btn")) {
$('[stepform').hide();
$('[stepform="' + to_step + '"]').fadeIn();
}
}
});
$("#submitButton").on("click", function (event) {
event.preventDefault();
if ($("#form__form--radioRgpd:checked").length == 1) {
$("#contact_form").submit();
} else {
$(".form__form--radioRgpdLabel").addClass("label--error");
}
});
});
this piece of code gonna check at what step i am in my 4 'pages' form and add the proper css class if the form is bad filled or not filled.
Related
I have written this function to validate that all form fields and check boxes in a form are filled out. The script automatically disables the submit button and then watches for the moment at which it can be re-enabled. My debugger statements are landing me in all of the proper places, but for some reason, the DOM element is not being updated. I'm sure I am just making a stupid mistake, but can't seem to find a solution. Thank you in advance for any help!
Specifically looking at this section:
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
Here is the whole script below.
$(document).ready(function() {
validateInput();
$('.validate').keyup(function(event){
validateInput();
});
$('[type=checkbox]').click(function(event){
validateInput();
});
function validateInput() {
var valid = 0;
var checkBox = $('[type=checkbox]');
var inputFields = $('input.validate');
var inputLength = inputFields.length + checkBox.length;
inputFields.each(function() {
if($(this).val() !== '') {
valid++ ;
}
});
checkBox.each(function() {
if($(this).prop('checked')) {
valid++ ;
}
});
if(valid === inputLength) {
updateBtnStatus('enable')
} else {
updateBtnStatus('disable')
}
}
function updateBtnStatus(status) {
var btn = $('input[type="submit"]');
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
}
});
I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!
originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo
This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.
i have a script which check when two textfields are not empty it does automatic submission. it picks the variables from the localstorage and places them in the textfields.
if (localEmail != null && localPwd != null) {
$('#form1').submit();
}
and i also i have a script which disables the submit button when all textfields are not filled.
$(document).ready(function (){
var $input = $('#form1 input:text'),
$register = $('#button_id');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
});
});
now my problem is when the page loads for the second and subsequent times and there are variables from the localstorage in the textfields, the submit button still remains disabled and the automatic submission fails. Now i want the button to remain active when there are variable in it so the automatic submission can be done
In document ready do an additional check for input values and disable the button
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form1">
<input type="text" />
<input type="text" />
<button id="button_id">button</button>
</form>
The reason why you are not achieving the desired behavior is because you are only updating the button's disabled property when a change event is fired from the input element(s), which are not fired by default upon page load.
The solution is to therefore move the function involving updating the button's status into a separate one, which we will call upon runtime (e.g. DOM ready) and then again when the change event is fired on element(s) of interest:
var updateButton = function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
};
// Update button status on DOM ready
updateButton();
// Update button status on keyup
$input.keyup(updateButton);
On a side note, please use .prop() when dealing with binary attributes:
$register.prop('disabled', true);
this should work
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
under document ready function.
$(document).ready(function (){
var $input = $('#form1 input:text');
$register = $('#button_id');
$register.prop('disabled', true);
//$register.attr('disabled', true);
$('#button_id').on('click',function(){alert('hi');});
function checkInputs(){
$input.each(function(e) {
if (!$(this).val().length < 1) {
trigger = true;
} else
{trigger = false;}
});
trigger ? $register.prop('disabled',false) : $register.prop('disabled',true);
}
checkInputs();
$('#form1 input:text').on('keyup',function(){checkInputs();});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input/>
<input />
<button type="button" id="button_id" >Submit</button>
</form>
I am using a plugin called pStrength.jquery.js and for some reason its not submitting the form I have, or it is submitting the form even if it is not supposed to (when I changed the code)
The code i am using is:
$(document).ready(function () {
$('#myForm').submit(function () {
return false;
});
$('#myElement1, #myElement2').pStrength({
'changeBackground': false,
'onPasswordStrengthChanged': function (passwordStrength, strengthPercentage) {
if ($(this).val()) {
$.fn.pStrength('changeBackground', this, passwordStrength);
} else {
$.fn.pStrength('resetStyle', this);
}
$('#' + $(this).data('display')).html('Your password strength is ' + strengthPercentage + '%');
},
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
$('#myForm').submit(function () {
return true;
});
}
});
});
Someone has told me that I should use booleans and inside the validation checks, set it to true or false.
The problem is that i have no idea how to do this
Is there anyone that could help me and show me the code to do this?
Thank you in advance
The reason it was still submitting was because the onValidatePassword function runs on each individual field, whereas you actually had two fields to validate. If one field validates and the other doesn't, the form would still submit because the Boolean had already been set to true, which was the only condition needed to submit.
Updated code below, you can also refer to the fiddle.
$(document).ready(function () {
$('#myForm').submit(function (event) {
// TODO: check that the two field values match as well
if ($('#myElement1').data('valid') === 'yup' &&
$('#myElement2').data('valid') === 'yup') {
// remove these three lines to make it submit
alert('Submitting...');
event.preventDefault();
return false;
// and uncomment this one line
//return true;
} else {
event.preventDefault();
return false;
}
});
$('#myElement1, #myElement2').data('valid', 'nope');
...
Your complete onValidatePassword callback should now look like this:
'onValidatePassword': function (strengthPercentage) {
$('#' + $(this).data('display')).html(
$('#' + $(this).data('display')).html() + ' Great, now you can continue to change your password!');
formValid = strengthPercentage >= 60;
// set for each element
if (strengthPercentage >= 60) {
$(this).data('valid', 'yup');
} else {
$(this).data('valid', 'nope');
}
}
Inside your onValidatePassword, you're binding to the submit event, instead of submitting the form. Replace this code:
$('#myForm').submit(function () {
return true;
});
with
$('#myForm').submit();
I'm having a hard time with this quick validation i want in place...but i think it's not validating properly because of my select name arrays and i'm not sure how to go about this.
How it should work:
- If stat holiday box is checked for that day && if any Lieu hours are selected for that day give alert error and stop form submission.
My jsfiddle: http://jsfiddle.net/4bgYj/3/
my jquery:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}
});
});
Let me give you a more user-friendly approach for your problem:
If stat is selected simply disable the form input for lieu hours.
With this you won't have to check anything before submitting the form and the user can't accidentally select a value in lieu hours.
It still needs to be updated to your markup, but the idea is basically:
var stat = $('.stat');
stat.change(function() {
var e = $(this);
var f = e.parent().find('.lieu');
if (e.is(':checked')) {
f.prop('disabled', true);
} else {
f.prop('disabled', false);
}
});
Demo
Try before buy
First, you're missing a );...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});
Try it after adding that and you'll find it works for the first checkbox. But select a different checkbox and it will fail. In HTML, you will want to use unique ids to reference an element. What I would do is change your HTML to put a css class on the TR tag, and then look at the contained elements.
<tr class='line'>
<td> <input type='checkbox' class='isHoliday'/> </td>
<td> <select class='lieuHours'>options...</select> </td>
</tr>
and in your script...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lines').each(function(i, obj) {
var lieuHours = $(this).find(".lieuHours").val();
if ($(this).find(".isHoliday:checked") && lieuHours > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});
You didn't approach the issue properly, the selectors should not be global but specific to the loop you are doing:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lieutimehours').each(function(i, obj) {
var lieuhrs = $(this).val();
if ($(this).closest('tr').find('#statholidaycheck').is(":checked") && parseFloat(lieuhrs) > 0) {
alert('works');
return false;
}else{
alert('fail')
}
});
});
});