integrating two javascripts codes into one code to show alerts - javascript

In my first javascript i am showing alerts if any text box having class check is left empty before submitting, if all are filled then in second javascript i am showing an alert that confirm submit?. But how to make these two as one javascript code?
<script type="text/javascript">
jQuery('input.test').not('[value]').each(function() {
var blankInput = jQuery(this);
//do what you want with your input
});
function confirmation(domForm) {
var jForm = jQuery(domForm);
var jFields = jForm.find('.check');;
var values = jFields.serializeArray();
var failedFields = [];
for(var i = 0; i < values.length; i++) {
var o = values[i];
if(o.value == null || o.value.length == 0) {
failedFields.push(jFields.filter('[name=' + o.name + ']').attr('title'));
}
}
if(failedFields.length > 0) {
var message = '';
if(failedFields.length == values.length) {
message = 'fill all fields please';
}
else {
message = 'please fill the fields:';
for(var i = 0; i < failedFields.length; i++) {
message += "\n";
message += failedFields[i];
}
}
csscody.alert(message);
return false;
}
var answer = confirm("Confirm save?")
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;
}
return true;
}
</script>
javascript to show confirm submit alert after text boxes having class check are filled
<script type="text/javascript">
$().ready(function() {
$('#btn_submit').click(function(e) {
e.preventDefault();
var that = this;
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
window.location = "confirmsubmit.jsp";
}
else {
return false;
}
}
})
});
});
</script>
html
<form action="confirmsubmit.jsp" onsubmit="return confirmation(this)" method="POST">
<input type="text" class="check"/>//alert if text box is left empty
<input type="submit" id="btn_submit"/>
</form>

I don't get why you need the second script. You call the validator function onsubmit. Why do change the window.location when you have set the same action? There is not point in binding the same function the the click-event of the button.
You don't need the second script, but have to change the first script.
function confirmation(domForm) {
// Your other code
// ...
if(failedFields.length > 0) {
// Your other code
// ...
csscody.alert(message);
return false;
}
// Your other code
// ...
/* Solution before your comment:
var answer = confirm("Confirm save?")
// This is already the action-target: window.location = "confirmsubmit.jsp";
return answer;
*/
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
// Probably doesn't work because this seems to be asynchronous?
return true;
}
else {
return false;
}
}
});
}

Related

Click event works on third or fourth try on button

This is a continuation of This
I used setTimeout() to place cursor on the input fields on pressing the tab, without which the focus goes to a link outside the <div> for some reason I am not aware of.
setTimeout() fixed that issue, but now:
On clicking on submit button the form does nothing but place cursor on the input fields for three or four times then proceeds with submitting.
Here is the submit button functions
$(“#submitbtn”).click(function(e) {
console.log(“click”);
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
startValidation();
});
e.stopPropagation();
e.cancelBubble = true;
});
Here is hover function for Submit button
$(“#submitbtn”).mouseover(function(e) {
console.log(“Hover”);
removeTimeouts();
$(“#submitbtn”).focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
The function removeTimeouts() has all clearTimeout() for all setTimeout() through out the JavaScript file.
But somehow the click function is never works until third or fourth try.
The hover function works on first mouse move though, it prints “Hover” on console, every time the mouse it moves over submit button.
Even after clearing all setTimeout() somehow the focus is moved to input fields instead of proceeding with the console.log() onclick.
Can someone help me understand the issue and help fix the form gets submitted on first click?
Update:
1) This is typed from mobile app, even after re-editing the quote appearing as “” It’s correct in my code just not here.
2) Focus and timeout event is to validate the input fields while moving out of the input field, like if the field is empty, the cursor won’t move to next input field. But just focus is not working, and tab just takes the cursor out of the input fields to a link below it, so time-out helps keeping the cursor the input field.
3) Snippet - This does not replicate the issue as this is by far I can post the code sorry :(
(function ($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// Another behind the scenes that collects the
// current caret position for an element
// TODO: Get working with Opera
$.caretPos = function (el) {
if ("selection" in document) {
var range = el.createTextRange();
try {
range.setEndPoint("EndToStart", document.selection.createRange());
} catch (e) {
// Catch IE failure here, return 0 like
// other browsers
return 0;
}
return range.text.length;
} else if (el.selectionStart != null) {
return el.selectionStart;
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caret = function (index, offset) {
if (typeof(index) === "undefined") {
return $.caretPos(this.get(0));
}
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (typeof(offset) !== "undefined") {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
// Set caret to beginning of an element
$.fn.caretToStart = function () {
return this.caret(0);
};
// Set caret to the end of an element
$.fn.caretToEnd = function () {
return this.queue(function (next) {
$.caretTo(this, $(this).val().length);
next();
});
};
}(jQuery));
var allTimeouts = [];
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
}
function removeTimeouts(){
for(var i = 0; i < allTimeouts.length; i++) {
clearTimeout(allTimeouts[i]);
}
}
function focusInNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
//$("#number" + thisID).prop("disabled", false);
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
});
allTimeouts.push(s);
if(preID != 0) {
if($("#number" + preID).val().length <= 0) {
var s = setTimeout(function() {
placeCursor($("#number" + preID));
});
allTimeouts.push(s);
}
}
}
function focusOutNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
var value = $("#number" + thisID).val();
var regex = new RegExp(/^\d*$/);
var regex1 = new RegExp(/^.*[\+\-\.].*/);
var l = $("#number" + thisID).val().length;
if(!value.match(regex)) {
alert("Just enter numerical digits");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if (l<=0) {
alert("This field cannot be empty");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if(value.match(regex)) {
var s = setTimeout(function() {
placeCursor($("#number" + nextID));
}, 100);
allTimeouts.push(s);
}
}
}
}
$(document).ready(function(){
$("#number1").focusin(function(){
focusInNumber(1);
});
$("#number1").focusout(function(){
focusOutNumber(1);
});
$("#number2").focusin(function(){
focusInNumber(2);
});
$("#number2").focusout(function(){
focusOutNumber(2);
});
$("#number3").focusin(function(){
focusInNumber(3);
});
$("#number3").focusout(function(){
focusOutNumber(3);
});
$("#number4").focusin(function(){
focusInNumber(4);
});
$("#number4").focusout(function(){
focusOutNumber(4);
});
$("#submitbtn").click(function(e) {
console.log("click");
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
alert("startValidation()");
});
e.stopPropagation();
e.cancelBubble = true;
});
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
});
.SubmitBtn {
width: 100%;
background-color: #cccccc;
}
.Submitbtn:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="reqField" id="number1" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number2" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number3" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number4" placeholder="Enter Number only"></input>
<div id="submitbtn" class="SubmitBtn">Submit</div>
After breaking my head and console.log on all the statement to figure out the flow of code, I was able to find that on $("#submitbtn").click() there is some .focusout() is called.
As these .focusout() were necessary for on the go validation on the <input> fields, i tried to add $.(":focus").blur() and it worked along with adding a return false; on placeCursor() function.
The $.(":focus").blur() removes focus from any currently focused element. And this is a live saver for our logic of code.
So the code looks like
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
$.(":focus").blur();
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
....
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
return false;
}
Hope this helps someone someday.
Thank you!

HTML button that's submitting an empty field even though it shouldn't be

Here's the HTML button I'm working with:
<b>Other: </b><input type="number" id="AmntValue" data-target-element-id="SubmitAmnt" data-target-parameter="Amnt" onchange="setValueOnTarget(this);' +/* ' enableButton(SubmitAmnt);' */+ '">
<button class="button2" id="SubmitAmnt" type="button" data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount=" onclick="disableButton(this); addValueToQueryString(this); redirectPage(this);">Continue To Payment</button>
When someone hits the button but the "Other" text field is blank, it's supposed to not redirect and instead show an error message. Right now the error message displays, but only for a quick moment before it redirects anyway.
Here is my complete JavaScript code:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem)
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
function displaySuccess(message) {
var userMessage = document.getElementById('userMessage1');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'green';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
I'm not sure if something's wrong with the code I put in the button or in the JavaScript.
Disable button by default
The button should be disabled by default, and should only be enabled when the expected input value is detected. It appears you already have a mechanism for this in your example, but you have some impediments to overcome first:
button should be disabled by default. Do this in the HTML:<button disabled …>Continue To Payment</button>
input's onchange handler should just call setValueOnTarget(), because this function already calls EnableButton(). In the HTML:<input onchange="setValueOnTarget(this);" … >
Remove the call to redirectPage() from the button's onclick handler and move it into addValueToQueryString() after you have assigned a value to newSrc.
Add a call to EnableButton() after you call displayError() in cases where you want to allow the user to modify the input and try again.
For example:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
console.log(targetElem);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem);
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
redirectPage(elem);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
EnableButton(elem);
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
<b>Other: </b>
<input
type="number"
id="AmntValue"
data-target-element-id="SubmitAmnt"
data-target-parameter="Amnt"
onchange="setValueOnTarget(this);">
<button
disabled
class="button2"
id="SubmitAmnt"
type="button"
data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount="
onclick="disableButton(this); addValueToQueryString(this);">Continue To Payment</button>
<div id="userMessage"></div>

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

How to return string from a function to another function?

I've made a login form that will check that username and password are valid or not.
Everything is good, until I press Login.
After press login button it said that username and password is wrong although it is not.
How could I fix this? I think it is about return in userCheck() and pwdCheck() functions.
Here is my form
<form name="loginForm" id="loginForm">
<input type="text" id="user" name="user" onfocus="userFocus()" onblur="userBlur()">
<span id="userWarn" class="warnSpan">Username is required.</span>
<input type="text" id="pwd" name="pwd" onfocus="pwdFocus()" onblur="pwdBlur()">
<span id="pwdWarn" class="warnSpan">Username is required.</span>
</form>
Here is the javascript:
var pwdElem = document.getElementById("pwd");
var pwdVal = document.getElementById("pwd").value;
var pwdWarn = document.getElementById("pwdWarn");
var pwdLen = pwdVal.length;
var pwdCheck = pwdCheck();
var userElem = document.getElementById("user");
var userVal = document.getElementById("user").value;
var userWarn = document.getElementById("userWarn");
var userLen = userVal.length;
var userCheck = userCheck();
function userFocus()
{
userElem.style.backgroundColor = "#ccffff";
userElem.style.border = "1px inset #00ffff";
userElem.style.color = "#00ffff";
}
function userBlur()
{
var userLenx = document.getElementById("user").value.length;
if (userLenx != 0)
{
userOk();
}
else
{
userError();
}
}
function pwdFocus()
{
pwdElem.style.backgroundColor = "#ccffff";
pwdElem.style.border = "1px inset #00ffff";
pwdElem.style.color = "#00ffff";
}
function pwdBlur()
{
var pwdLenx = document.getElementById("pwd").value.length;
if (pwdLenx >= 8)
{
pwdOk();
}
else
{
pwdError();
}
}
function userCheck()
{
var userLenx = document.getElementById("user").value.length;
if (userLenx != 0)
{
return "ok";
}
else
{
return "error";
}
}
function pwdCheck()
{
var pwdLenx = document.getElementById("pwd").value.length;
if (pwdLen >= 8)
{
return "ok";
}
else
{
return "error";
}
}
function userError()
{
userElem.style.backgroundColor = "#ffcccc";
userElem.style.border = "1px inset #ff0000";
userElem.style.color = "#ff0000";
userWarn.style.visibility = "visible";
}
function pwdError()
{
pwdElem.style.backgroundColor = "#ffcccc";
pwdElem.style.border = "1px inset #ff0000";
pwdElem.style.color = "#ff0000";
pwdWarn.style.visibility = "visible";
}
function userOk()
{
userElem.style.backgroundColor = "#ddffdd";
userElem.style.border = "1px outset #00bb00";
userElem.style.color = "#00bb00";
userWarn.style.visibility = "hidden";
}
function pwdOk()
{
pwdElem.style.backgroundColor = "#ddffdd";
pwdElem.style.border = "1px outset #00bb00";
pwdElem.style.color = "#00bb00";
pwdWarn.style.visibility = "hidden";
}
function errorForm()
{
if (userCheck=="error"&&pwdCheck=="error")
{
userError();
pwdError();
}
else if (userCheck=="error"&&pwdCheck=="ok")
{
userError();
}
else if (userCheck=="ok"&&pwdCheck=="error")
{
pwdError();
}
else
{
alert("Sorry, an error occured.\n\nPlease refresh page and try again.");
}
}
function loginSubmit()
{
if (userCheck=="ok"&&pwdCheck=="ok")
{
userOk();
pwdOk();
loginForm.submit();
}
else
{
errorForm();
}
}
Here is the Jsbin
Please help, I am new to coding!
The issue with you code seems to be in the function loginSubmit(). It should read as follows:
function loginSubmit()
{
if (userCheck()=="ok"&&pwdCheck()=="ok") // <--change here
{
userOk();
pwdOk();
loginForm.submit();
}
else
{
errorForm();
}
}
The two variables you were referring to (userCheck and pwdCheck) are initialised as soon as the page loads. This means they will represent the state of the login and password fields when the page loads. Since these fields are empty when the page loads, the loginSubmit() function will always show the error. Hope this helps.
You are returning a string from the function, but you aren't using it for anything...
Short example
function getString() {
return "A string";
}
// I don't even store the string...
getString();
So to fix it, use the string that is returned
// Store it
var example = getString();
// Use it
alert(example);
Below code will do the validation which you are trying
function validate()
{
if(trim(document.frmLogin.sUserName.value)=="")
{
alert("Username is required.");
document.frmLogin.sUserName.focus();
return false;
}
else if(trim(document.frmLogin.sPwd.value)=="")
{
alert("Please Enter a Password");
document.frmLogin.sPwd.focus();
return false;
}
}
You appear to have a problem with the way you are trying to call userCheck, pwdCheck, etc.
You are missing the parentheses, which means you are comparing the function itself (i.e. not the result of calling the function) with a string.
your comparisons should look something like this once you've added the parentheses
if (userCheck()=="error"&&pwdCheck()=="error")

Form not submitting when valid data entered

I am building some validation but when I submit correct input it still shows as not valid, can't quite figure out where I'm going wrong!
The function works with invalid input but not with valid input
Javascript/jQuery
(function(){
var form = '.contact-form',
alert = '.alert',
fieldWrap = '.control-group',
errorMsg = '.error-message',
error = 'error',
show = 'show',
hide = 'hide';
var textField = function(){$(field).val() !== (regEx); return false};
var select = function(){$(field + ' option:selected').val() === regEx; return false};
var validate = function(ifParam,field,regEx,e){
if(ifParam()){
$(field).parents(fieldWrap).addClass(error).find(errorMsg).addClass(show);
return false;
}
else{
$(field).parents(fieldWrap).removeClass(error).find(errorMsg).addClass(hide);
return true;
}
};
var valid = function(e){
validate(textField,'#first-name' ,/^[a-zA-Z]$/,e);
validate(textField,'#last-name' ,/^[a-zA-Z]$/,e);
validate(textField,'#contact-number' ,/^[a-zA-Z]$/,e);
validate(textField,'#email' ,/^[a-zA-Z]$/,e);
validate(textField,'#landline-number',/^[a-zA-Z]$/,e);
validate(textField,'#postcode' ,/^[a-zA-Z]$/,e);
validate(select ,'#title' ,'select',e);
return true;
};
$(document).on('submit',form,function(e){
if(!valid()){
$(alert).addClass(show);
e.preventDefault();
e.stopPropagation();
}
else{
$(this).unbind('submit').submit();
}
});
})();

Categories

Resources