HTML Multi-Page Form Issues (page is refreshing) - javascript

I am having a problem with a multi-page form submission. The problem is that the page is refreshing when I press the next page button. I believe it is a return true/false problem, but I don't know where the issue is. Here is the code:
$(document).ready(function () {
var info = [];
function showinfo() {
for (i=0; i<info.length; i++) {
$('#step3 ul').append(
$('<li>' + info[i] + '</li>')
);
};
};
$('#step1_btn').click(function() {
$("input").each(function() {
if (input.type != radio) {
info.push(this.name+':'+this.value);
} else if ($('.radio').is(':checked')) {
info.push(this.name+':'+this.value);
}
});
$('#step1').css('display','none');
$('#step2').css('display','inherit');
$('#progbar').attr('value',33);
return false;
});
$('#step2_btn').click(function() {
$("input").each(function() {
if (input.type != radio) {
info.push(this.name+':'+this.value);
} else if ($('.radio').is(':checked')) {
info.push(this.name+':'+this.value);
}
});
$('#step2').css('display','none');
$('#step3').css('display','inherit');
$('#progbar').attr('value',66);
showinfo();
return false;
});
});
Not sure if that is all you need to see. If you need to see the html as well, I can provide that. Thanks in advance for any help you all can give. I can read javascript fairly well when someone else writes it, but for some reason writing it myself ends up in catastrophe every time.

try event.preventDefault():
$('#step1_btn').click(function(e) {
e.preventDefault();
// your code here
return false;
});

Related

How made my function affect the DOM Jquery?

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.

DOM not being manipulated from inside a function that is being triggered properly

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');
}
}
});

Customizing a password strength validator plugin

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();

jQuery empty input check function not working as expected

This question has been done to death on SO and I'm really, really sorry! I've already taken the bones of the below idea from a couple of SO questions on the same theme.
All said though, I still can't get it to work as expected.
It works OK if NONE are filled in.
It works OK if the END input is filled in and not the others.
It works OK if the MIDDLE input is filled in.
If you fill in ONLY the FIRST input though, it alerts, but submits anyway?
JSFIDDLE
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
} else {
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
}
});
});
});
I'm sure it's something totally embarrassingly obvious but after a 16 hour day, I just can't see it. Any help appreciated ...
You need to pull the 'incompletion' check outside of the .each
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
}
});
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
});
});
http://jsfiddle.net/6WpeF/6/
try
if(document.getElementById('id of input').value != ""){}

JavaScript Echo Var Within Double Quote

Okay,
Another novice type question.
I have this array within the head section on my website and want to use it inline JavaScript:
var MyVariable = {"chkboxid":"chkbox"}
chkboxid is a id of a checkbox input.
Now, while validating the checkbox input on form submit, neither this works
$("form#myform").submit(function () {
if ($(MyVariable.chkboxid).is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
Nor This (check the double quote at the variable)
$("form#myform").submit(function () {
if ($("MyVariable.chkboxid").is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
However, if I hardcode the checkbox input id, it works. I mean "input#chkbox" in place of MyVariable.chkboxid.
$("form#myform").submit(function () {
if ($("input#chkbox").is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
How can I use that variable instead of hard coding the input id?
You are missing the "#" before the ID:
$("form#myform").submit(function () {
var element = $("#" + MyVariable.chkboxid)
if (element.is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
}
Note however that chkboxid is the key, the actual ID of the checkbox should be the value:
var MyVariable = {"chkboxid": "real_id_here"}
please check below code.hope it will work
$("form#myform").submit(function () {
if ($("#chkboxid").is("checked")) {alert("checked");
} else {
alert("not checked");
}
});
thanks,Ripa Saha

Categories