JavaScript condition not being met - javascript

I have created the below code for a subscribe form and for the most part it is working fine apart from, however the following condition does not seem to be working:
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
What is happening is that when the subValidEmail is entered correctly it clears all of the other entered data which leads me to believe that the subFieldUpdated === true condition is not being picked up correctly?
What I am looking for is that the form will only clear the values once all fields have been entered & a valid email is present.
Any suggestions/advice would be great as I have tried a few things now but with no luck.
$("#modSubCard").submit(function() {
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = true;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated[i] = false;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});

Use Below Code. It will works for you.
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = 0;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated = subFieldUpdated + 1;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === 0 && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});

Related

Faster Evaluating IF Condition of JavaScript

Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')

Checkboxes and trying to save the state of all checkboxes for the user when they return

function getFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
}
function fillFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
getStatus = localStorage.getItem('name'); {
if (getStatus === "true") {
console.log("its checked");
document.getElementByTagName("name").setAttribute('checked', 'checked');
} else {
console.log("its not checked");
}
}
}
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// get the form state
getFormState();
// save the state of the form each X seconds (customizable)
setInterval('fillFormState()', 1 * 1000);
}
};
But it doesn't seem to work. And Im trying to figure out why. Im not very experienced with javascript so it might be quite obvious. Sorry for that. Im trying.
I'm guessing your localStorage is never being set because of this loop:
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
There is no document.getElementByTagName, and you are also searching for "name" instead of your variable name.
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (fields[i].checked === true) { //Check the current field
localStorage.setItem(name, "true"); //Set the actual name, not "name"
} else {
localStorage.setItem(name, "false");
}
}

Remove Required Field from QuickCreate in Sugarcrm

I wrote a function to remove accounts name relate field from Contacts QuickCreate but my function works in Firefox perfectly but in chrome its not working... Here is my function
function manageRequired(reqArr, disabledVal)
{
var requiredLabel = '<span class="required">*</span>'; // for firefox
var search_requiredLabel = '<span class="required"'; // searching string for firefox
var form = "";
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i].id=='EditView')
{
form = 'EditView';
break;
}
if(document.forms[i].id=='form_SubpanelQuickCreate_Contacts')
{
form = 'form_SubpanelQuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Contacts')
{
form = 'form_QuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Accounts')
{
form = 'form_QuickCreate_Accounts';
break;
}
}
for(var j = 0; j < reqArr.length; j++)
{
var flag = true;
if (validate[form] != 'undefined')
{
for(var i = 0; i < validate[form].length; i++)
{
if(validate[form][i][0] == reqArr[j].id && validate[form][i][2])
{
if(disabledVal)
{
flag = false;
break;
}
else
{
validate[form][i][2] = false;
}
}
}
}
var labelNode = document.getElementById(reqArr[j].id + '_label');
if(flag & disabledVal)
{
// we require the field now
addToValidate(form, reqArr[j].id, reqArr[j].type, true,reqArr[j].label );
}
if(disabledVal)
{
if(labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1) // for IE replace search string
{
search_requiredLabel = '<SPAN class=required>';
}
if (labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1)
{
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
labelNode.innerHTML = labelNode.innerHTML + requiredLabel;
}
}
else
{
if(labelNode != null)
{
if(labelNode != null && labelNode.innerHTML.indexOf("<SPAN class=required>*</SPAN>") == -1 && labelNode.innerHTML.indexOf('<span class="required">*</span>') == -1 )// for that field which is unrequired
{
}
else if(labelNode != null && labelNode.innerHTML.indexOf(requiredLabel) == -1) // for IE replace span string
{
requiredLabel = "<SPAN class=required>*</SPAN>";
}
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
}
}
}
}
Can anyone please help me out to solve this issue...
To remove a required field from QuickCreate in Sugarcrm you can use this fuction:
removeFromValidate('EditView','eventlist_c');
or remove remove the validtion applied to the field:
$('#eventlist_c_label').html('{$mod_strings['LBL_EVENTLIST']}: ');

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

"Unable to get value of the property 'style'" when trying to change style in IE

Have written a function for cycling through the questions in a online quiz. I works fine in every browser but IE (god I wish IE would just curl up and die). Function is below.
function cycleQs() {
var qs = document.getElementsByName("quizQ");
var nextQBtn = document.getElementById("btnNextQ");
var i = 0;
var curQ = -1;
for (i = 0; i < qs.length; i++) {
if (qs[i].style.display == "block") {
curQ = i;
}
//qs[i].style.display = "none";
}
var valid = false;
if (curQ > -1) {
var qId = qs[curQ].id.replace("dv", "");
var inps = document.getElementsByName(qId);
if (inps.length > 0) {
if (inps[0].type == "radio") {
for (i = 0; i < inps.length; i++) {
if (inps[i].checked) {
valid = true;
}
}
} else if (inps[0].type == "hidden") {
valid = true;
for (i = 0; i < inps.length; i++) {
if (inps[i].value <= 0) {
valid = false;
}
}
}
} else {
valid = true;
}
} else {
valid = true;
}
if (valid == true) {
for (i = 0; i < qs.length; i++) {
qs[i].style.display = "none";
}
if (curQ < (qs.length - 1)) {
qs[curQ + 1].style.display = "block";
if (curQ == (qs.length - 2)) {
var scoreDv = document.getElementById("dvScore");
nextQBtn.style.display = "none";
var answers = getAnswers();
//alert(answers)
scoreDv.innerHTML = "Processing";
processResults(answers);
}
} else {
qs[0].style.display = "block"; // Problem occurs here when function first loads
}
} else {
alert("You must select an answer before you can proceed");
}
}
Any ideas of a work around for this?
document.getElementsByName is likely not returning anything, because of IEs implementation: see here
so qs[0] probably doesn't exist

Categories

Resources