trouble with confirmationboxes when submitting a form - javascript

I'm trying to compare some values of select fields.
When submitting my form I want to check whether the values are equal.
Well ... I've got two problems here.
The values aren't compared the first time I submit the form.
Example: I select option3 for id='idx' and id='idy'. In my case option3 is equal to option3. When I submit the form there should be a confirm box because the values are equal. No confirmationbox appears. I call the site again with the set values and submit the form; the confirmationbox appears. I chose option 1 for id='idx'. This would mean that the values of id='idx' and id='idy' are not equal. But now the box appears again.
What I want is that when I submit the form the values should be compared. In case they're equal a confirmationbox appears.
2.Somehow my code only checks for one condition. But it is possible that the two cases in my code can be true. How would I solve it?
This is my code:
var x = $('#idx option:selected').val();
var y = $('#idy option:selected').val();
var z = $('#idz option:selected').val();
$('#myform').submit(function() {
if (x === y ) {
if (confirm('text') == true){
return true;
} else {
return false;
}
}
if (x === z ) {
if (confirm('text') == true){
return true;
} else {
return false;
}
}
});
If there are any questions, please ask.
Thank you for your help.

First, you should put your $('...').val() lines inside the submit function, or else they will get the value of the select boxes when the page loads.
Second, once you return true or false, it will exit out of that submit function, so you should return false when it fails, or else continue until the end of your conditionals, then have one return true at the end.

Related

Keep value after submit form

I have this category checkbox where if I select certain values it will display div size but also in the same time when I select the checkbox it will submit the form. The problem is if I add this.form.submit() , the code below won't work and the form won't submit the value, but if I don't add it, the code will work.
How do I display div size and submit the form at the same time?
function getIds(checkboxName) {
let checkBoxes = document.getElementsByName(checkboxName);
let ids = Array.prototype.slice.call(checkBoxes)
.filter(ch => ch.checked==true)
.map(ch => ch.value);
return ids;
}
$(".category").on('change', function() {
this.form.submit();
let catIds = getIds("category[]");
$.each(catIds, function(index, value){
if (value == '1' || value == '2') {
$("#size").show();
} else if (value == '3') {
$("#size").hide();
}
});
});
This sounds like a racing problem. The form gets put into a different thread by the browser and gets handled first before the rest of the javascript is able to finish.
A quick (but dirty) hotfix for me is usually to use the setTimeout() method.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
That way the javascript can work it's magic and afterwards the form gets submitted.

jquery validation loop producing false positives

$(document).ready( function()
{
// hides the story and error text when the page loads
$('.errorText').hide();
$("#story").hide();
// global variables for the blanks and the textarea forms
var input = $("form").children();
var storyBlank = $('#story').children();
// Main Event on Click
$('button.submit').on( "click", function (event)
{
// if the form is not validated, highlights errors and prevents the submit from going through
if(!validate())
{
event.preventDefault();
}
// if the form is validated, fills the blanks in the story and displays it
else
{
fillInTheBlanks();
}
});
// Checks to see if there are any empty fields and highlights them if they are empty
function validate()
{
console.log('validate() initiated')
var success = false;
errcnt = 0;
cnt = 0;
while (cnt < 9)
{
if (input.eq(cnt).val().length == 0)
{
errcnt++;
input.eq(cnt).removeClass("hide");
console.log('errorcount', errcnt, 'at input', cnt);
}
else if (input.eq(cnt).val().length !== 0 && !(input.eq(cnt)).hasClass("hide"))
{
input.eq(cnt).addClass("hide");
}
cnt++;
}
if (errcnt == 0)
{
success = true;
}
return success;
}
// Fills in the blanks of the story
function fillInTheBlanks()
{
console.log('fillInTheBlanks() executed');
var blankCount = 0;
while (blankCount < 9)
{
storyBlank.eq(blankCount).empty().append(input.eq(blankCount).val());
blankCount++;
}
$("#story").show();
}
});
I am trying to make a mad libs style page with 9 textboxes for input. I am running into two problems.
First, when I click submit with all textboxes empty, only the the first four show an error (this is done in css, I have two classes on all the textboxes "error hide", I remove the class hide in my loop to show the error).
The second problem I'm having is if I click submit with text in all the textboxes, my validate functions errorcount goes up to 4 errors at every other textbox. I've even tried '$('input').eq(0).val().length == 0' for every textbox in the index and it's returning false every time. I don't understand how it's getting into that if then statement if it doesn't satisfy the argument.
i don't understand your problem, but if is validation on inputs empty... using
http://parsleyjs.org/

Highlight empty select box after alert

I have a site using input:text, select and select multiple elements that generate a text output on button click.
Having searched SO, I found examples of validation code that will alert the user when a select field returns an empty value-
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
$(this).addClass("highlight");
}
At the end, I tried to add a condition after the alert is dismissed, such that the offending select box will be highlighted by adding the 'highlight' class - but this doesn't do anything. My .highlight css is {border: 1px red solid;}
Any help here?
UPDATED WITH ANSWER - Thanks #Adam Rackis
This code works perfectly. I added a line to remove any added '.highlight' class for selects that did not cause an error after fixing
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
$('select').removeClass("highlight");//added this to clear formatting when fixed after alert
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
You were close. In your loop, this does not refer to each select that you're checking.
Also, you're returning false prior to the highlight class being added. You'll probably want to keep track of whether any select's are invalid, and return false at the very end after you're done with all validation.
Finally, consider moving your alert to the very bottom, so your user won't see multiple alerts.
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}
}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
Also, since you're already using jQuery, why not take advantage of its features a bit more:
$('select').each(function(i, sel){
if (sel.value === '') {
$(el).addClass("highlight");
anyInvalid = true;
}
});
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}

Call a recursive function with different variables

I am new to javascript. I am doing a feedback form where there are 12 radio buttons that need to get validated individually and a textarea will be displayed when I click a particular value.
Here, when I click that button, my textarea, which is in display, should be mandatory entered (eg: when I click fail option in a results question, then I should mention in which subject he failed through that textarea. something like that).
For this, I have written code, it's working fine with the 1st radio button, but unable to call this recursively for remaining buttons.
I need to call this code in a function recursively, but my variables need to get change everytime. Like for 2nd time, I should use option2,text2, likewise in next call option3,text3, etc.
var option = $("#form1 input[#name=radio1]:checked").val();
var text = document.getElementById("text1").value;
if (!$("#form1 input[#name=radio1]:checked").val()) {
alert("Please fill all the fields");
return false;
errs++;
} else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
This piece of code needs to be called for var option1 to option10 and same text1 to text10. Like:
var option2 = $("#form1 input[#name=radio2]:checked").val();
var text2 = document.getElementById("text2").value;
This should get called immediately of completion of first radio button.
Please help me out.
"Recursive" is the wrong word here. You just want to loop over all the elements.
Get all the radios, and loop over them. Then get the ID, and all the fields associated with that id.
I'm assuming you're using jQuery, so here's an example:
// Note: The "#" is not needed in jQuery
var radios = $("#form1 input[name^='radio']"); // "^=" means "starts with"
radios.each(function(){
var id = this.name.replace('radio', ''); // this will get the number, eg: 1
var option = $(this).val(); // get radio's value
var text = $('#text'+id).val(); // get textX's value
if(!$(this).is(':checked')){ // check if radio is checked
alert("Please fill all the fields");
errs++; // make sure to do this before "return false"
return false; // break the .each loop
}
else if (option == "3" && trim(text) == "") {
alert("Please enter comments.");
return false;
}
});

If statement returns true if first selector of type returns true

The following is some code for making sure people can't submit if the value of an input with the attribute data-fill="fill" is equal to ''. My problem is that it checks the IF statement from first to last input. This means that if the first input has a value, the form will submit; if the first two inputs are filled, it will submit and so forth... If the first input isn't filled, it works fine for the other inputs. Is it possible to ensure that it checks all inputs before returning true or false?
$('form').submit(function() {
var input = $('input, textarea');
if (input.data('fill') == 'fill' && input.val() == '') {
return false;
}
});
I know I can solve this problem by targeting each input individually with "else if", but that just seems like the wrong way to do it.
To consider all of the input values use the each method.
$('form').submit(function() {
var allFilled = true;
$('input, textarea').each(function () {
if ($(this).data('fill') === 'fill' && $(this).val() === '') {
allFilled = false;
}
});
return allFilled;
});

Categories