How to remove class from body if condition is not met? - javascript

I'm working with an if statement to show an alert message depending on certain conditions.
Under the second condition New Article I want a specific css class to be added (show-banner-alert). I am able to get the css added but its now affecting the conditions following it.
I've tried adding a $("body").removeClass and adding a new class with different properties but I am unable to get rid of the first-class successfully.
Here is my code:
$(window).on("load", function(e) {
$('.preloader').fadeOut('slow');
if (document.cookie.includes("isDismissed=true")) {
document.body.classList.add("alert.container");
} else if ("#pageTitle" === ("New Article") !== "-1") {
document.body.classList.add("show-banner-alert");
} else if ("#pageTitle".indexOf("Test") !== "-1") {
$("body").removeClass("show-banner-alert").addClass("show-alert");
} else if ("#pageTitle".indexOf("New Home") !== "-1") {
document.body.classList.add("show-alert");
}
});

first :
none of the conditions are correct.
all the if conditions are going to give you a correct answer ( true ).
second :
try either using jquery or using vanilla js for dom manipulation. ( I'd recommend jquery).

Related

Validating the state of the slide toggle using Cypress

I'm just new to Cypress and I want to validate if the slide toggle button is ON or OFF.
I have this piece of code that checks whether it is ON or OFF but I have no idea how to put it in an If-Else condition.
cy.get('#slide-toggle-1')
.find('input')
.filter('#slide-toggle-1')
.should('have.attr', 'aria-checked', 'true')
//What I want to do
If(<the code above is true>) {
cy.get('#dropdown').select('value1')
}
else {
cy.get('#button').click()
}
All comments and suggestions are well appreciated. Thank you.
You can use a jQuery OR selector
cy.get('#slide-toggle-1[aria-checked="true"], #button') // "," in the selector means OR
.eq(0) // if both present take the first
.then(toggleOrButton => {
if (toggleOrButton.attr('id') === 'slide-toggle-1') {
cy.get('#dropdown').select('value1')
} else {
cy.get('#button').click()
}
})
Note this only works for static HTML. If you've just clicked the toggle and it's animating, it would pick the button before the animation completes (but the same applies to other methods using .then() or await).
You can use then, but it gets a bit messier when you have more levels of nesting
cy.get('#slide-toggle-1')
.find('input')
.filter('#slide-toggle-1')
.then((btn)=>{
if (btn.ariaChecked === 'true') {
cy.get('#dropdown').select('value1')
}
else {
cy.get('#button').click()
}
})
You should be able to use await with cypress-promise
import promisify from 'cypress-promise'
const btn = await promisify(
cy.get('#slide-toggle-1')
.find('input')
.filter('#slide-toggle-1')
);
if(btn.ariaChecked === 'true')
if(btn[0].ariaChecked === 'true') // might need [0] as per #eric99's comment
I have already done this using the following code:
cy.get('#slide-toggle-1-input').then(($toggleBtn) => {
if($toggleBtn.attr('aria-checked') === 'true') {
//command here if the toggle button is turned on
}
else {
//command here if the toggle button is turned off
}
})
Also don't use dynamic elements such as my example above, I just use that for easier understanding. Instead, use a regular expression or RegEx for the locators like below.
//example above, don't do this
cy.get('#slide-toggle-1-input')
//USE THIS for dynamic locators
cy.get("[id^='slide-toggle-'][id$='-input']").first()
//the ^ search for properties starting from
//the $ search for properties ending from
Read this for further details on the cy.get() and dynamic locators: https://docs.cypress.io/api/commands/get#Selector
Hope it helps everyone, especially who's just starting on Cypress like me! :)

Compare duplicate values of two select in materializecss framework

I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime

BootstrapValidator how to find rules for a field

How do I find if there are rules specified for a particular field?
e.g. conditional zip code validation. I want to apply the validation if it hasn't been applied before, otherwise just enable it.
if (zipFieldElements == null) {
$(registerForm).bootstrapValidator('addField', m.zipCodeFieldName, m.getZipCodeValidator());
} else {
bootstrapValidator.enableFieldValidators(m.zipCodeFieldName, true);
}
The solution was to not worry and always call both. This works reliably (0.5.3):
bootstrapValidator.addField(mBehave.stateFieldName, {validators: {notEmpty: "The state cannot be empty"}, container: 'popover'});
bootstrapValidator.enableFieldValidators(mBehave.stateFieldName, true)

jQuery custom validation in asp.net mvc 3 razor view

I have very basic knowledge about JS/jQuery. I need to perform check on the value of certain text boxes. The example just recreates the problem I heave with the real application which is a lot bigger and the tables are dynamically created based on a data from a data base, so in run time I add the classes on which I base my jQuery logic.
Here is the jsfiddle example - http://jsfiddle.net/Xhnbm/
There are three different checks I need to do - for float, for string length and for float, however you may see that the validations is not performed I always get the integer exception and even if you remove the integer check the validation is not working either, so I guess the problem is not in the functions themselves but somewhere else.
Thanks for help.
P.S
It seem I can't submit the question without adding code. All the code is in the jsfiddle example but since I need to add some here too, I think that the problem is either in the way I declare may functions that perform the check or here :
$('#submitDocument').click(function () {
try {
if ($(".checkString16").val().length > 16) {
throw "The text can be up to 16 symbols";
} else if (!mathFunctions.isInt($(".checkULong").val())) {
throw "Insert integer";
} else if (!mathFunctions.isFloat($(".checkFloat").val())) {
throw "Insert float";
}
validationResult = true;
} catch (exc) {
alert(exc)
validationResult = false;
}
return validationResult;
});
in the way I try to execute the validation when the submit button is clicked. But being no Js programmer at all I don't want to point you to wrong directions.
$('#submitDocument').click(function () {
var validationResult = true;
if ($(".checkString16 input[type='text']:first").val().length > 16) {
validationResult=false;
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
validationResult=false;
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
validationResult=false;
}
return validationResult;
});
This should do the trick.
If the #submitDocument is a input type='submit' and you use it to submit the form, you should try this way:
$('#submitDocument').click(function (e) {
if ($(".checkString16 input[type='text']:first").val().length > 16) {
e.preventDefault();
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
e.preventDefault();
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
e.preventDefault();
}
});
The e.preventDefault() will prevent the submit button from doing it default handler, which is submitting the form.
You can always submit the form manually from the code, using $("#formId").submit();
PS. Make sure that you are also validating those values in code behind, because simple jquery validation is easy to come around.

jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...

Categories