JQuery Multiple If Statements - javascript

I have the following code block which works great:
jQuery(".archive-job_listing-layout").click(function(evt) {
evt.preventDefault();
if (!jQuery("body").hasClass('post-type-archive-job_listing'))
return;
console.log("Click " + jQuery(this).data('style'));
console.log(jQuery(window).width());
if (jQuery(this).data('style') == "grid" && jQuery(window).width() < 800) {
jQuery("ul.job_listings").css('display','block');
jQuery("table#wswp-header-row").hide().remove();
jQuery(".table_padding").hide().remove();
return;
}
layout_to_table("click");
})
});
I want to do is add another line which like:
if (!jQuery("body").hasClass('archive tax-job_listing_type'))
return;
but adding this breaks the code. I've tried using If Else, Or (||) And (&&), but nothing works.
If i substitute 'post-type-archive-job_listing' with 'archive tax-job_listing_type' the code also works fine, i just can't seem to get both of these lines of code to work at the same time.

This should work:
if(!jQuery("body").hasClass('archive tax-job_listing_type') && !jQuery("body").hasClass('post-type-archive-job_listing'))
return;

Perhaps separating with a few more parenthesis will work out for you:
if (!(jQuery("body").hasClass('post-type-archive-job_listing')) || !(jQuery("body").hasClass('archive tax-job_listing_type')))
return;

Can use is() which accepts multiple selectors. Will act like or when more than one selector is passed to it
if(!jQuery("body").is('.archive tax-job_listing_type, .post-type-archive-job_listing'))
DEMO

Related

Javascript - Show div only if input value is greater than 999

I'm practicing with a script developed by the user #Bibberty, where there are buttons that count clicks, divs are cloned and also sume input values and all run under LocalStorage, and everything works very well, but practicing with JS (I'm novice, level 0), I can not add a new function
My interest is to show a div (#regalo), only if the input #total has a value between 999 and 1,500.
This only works if I place values, but it does not work in auto mode...
SEE LIVE DEMO (jsfiddle, the snippet does not run here)
Any idea...?
Thanks in advance!
//----------------
SCRIPT:
$(document).ready(function(){
if($('#total').val() > 999 ) {
$('#regalo').show();
}
$('#total').on('change',function(){
if($(this).val() > 999 ) {
$('#regalo').show();
}
else{
$('#regalo').hide();
}
})
})
add this
$('.comp-clone').on('click',function(){
if($('#total').val() > 999) {
$('#regalo').show();
}
else{
$('#regalo').hide();
}
})
You arent checking if the input field changes you are checking if you change it
$(document).ready(function(){
if($('#total').val() > 999 ) {
$('#regalo').show();
}
$('#total').on('change',function(){
if($(this).val() > 999 ) {
$('#regalo').show();
}
else{
$('#regalo').hide();
}
})
$('.comp-clone').on('click',function(){
if($('#total').val() > 999) {
$('#regalo').show();
}
else{
$('#regalo').hide();
}
})
})
That should work for you but if you wanted to clean that up a little
$(document).ready(function() {
CheckTotal();
$('#total').on('change', function () {
CheckTotal();
})
$('.comp-clone').on('click', function () {
CheckTotal();
})
})
CheckTotal() {
if ($('#total').val() > 999) {
$('#regalo').show();
}
else {
$('#regalo').hide();
}
}
$(document).ready(function(){
function manageRegalo() {
const total = Number($("#total").val().replace(".",""));
// or:
//const total = suma();
if(total > 999 && total < 1500) {
$('#regalo').show();
}
else{
$('#regalo').hide();
}
}
$(document).on('click', function (event) {
const target = event.target;
if (target.matches('.comp-clone') || target.matches('.bbp')) {
manageRegalo();
}
});
manageRegalo();
});
JSFiddle
There are a couple of changes here:
Don't use display: none to hide it, that way jQuerys show() will not work. Instead call hide() immediately, that's way I call manageRegalo() at the very end directly one time. If the split second that you can see the regalo at the beginning is a problem, add another CSS class to the element which includes display: none and use jQuerys .addClass() and .removeClass() to show and hide the regalo.
$('#total').val() gives you a string value, you need to convert it to a number, but this string value can has dots in it, so the value 1.000 would be converted to 1, that's why we first need to remove all the dots. Another way to get the click would be to use the suma() function which is defined in the other JS-Code (inside the HTML-Window), but that one recalculates the value again.
You checked if the value is greater than 999, but not if it is smaller than 1500.
Don't listen at the total-Element for a click, first you don't click on the total-Element: You click on one of the Clone N Elements or on the red Xs. But don't listen on those directly as well, because the JS code that's already there inside the HTML code is listening on the document itself. If you would listen on the Clone N or Xs element, you would get the click event first, but at that time the total isn't calculated yet, so you would get the value always one click late.
I reviewed the code you posted and you have two major issues.
Never try adding more code without understanding the code already written.
It's a common thing that we start writing some code before even understanding the whole code already written, and this is a big problem since it could cause the other code to not work. I'll give you the example with your issue. Something that is preventing your code to give you the result you are expecting is that in the code previously written, the function that assings the valute to the input with id of total is converting the input to a string with String.toLocaleString() which converts totally the variable type from integer (which is what your are looking for) to a string.
Here is where this happens in the code:
const displaySuma=()=>document.getElementById("total").value=suma().toLocaleString("es-ES");
const suma = function() {
return Array.from(document.querySelectorAll(".derecha div .add-prod"))
.reduce((a, v) => a + parseFloat(v.value), 0);
}
So, to achieve the functionality you want, you need to remove the last function attached to the sum() function. It will be like this:
const displaySuma=()=>document.getElementById("total").value=suma();
Also, there's no need to add extra event listeners to your mini-app. Like I said, just try to give it a little of research before writing more code, if you do this, you'll be writing JavaScript code easily and understand how it works by the time you achieved your goal of modifying an already written piece of code.
There is already an event listening for the value in the code.
Since the script already has an event listening for the #total value change, we can just create a function and check the condition there. Here is the event listening:
document.addEventListener('click', (event) => {
let target = event.target;
// Add
if (target.matches('.comp-clone')) {
addClick();
addToDerecha(event.target.dataset.clone);
verifyCondition(); //We add our own function that we just made to verify the value.
}
// Remove
if (target.matches('.bbp')) {
removeClick();
getParent('.derecha', target).removeChild(target.parentNode);
storeHTML();
displaySuma();
}
});
And now, our function would simply be: (Vanilla JavaScript)
const verifyCondition = () =>{
let total = Number(document.querySelector("#total").value);
//We convert the value to integer anyways to prevent any kind of errors.
if( 999 < total && total < 1200 ){//Check if value is between 999 and 1200
document.getElementById("regalo").style="display:block;";
}else{
document.getElementById("regalo").style="display:none;";
}
}
And that's it! Here is a fiddle with the new working code, try to give it a check and make sure to search for what you don't understand. That's how any Senior Developer started.
https://jsfiddle.net/ax0L12j7/

Javascript - onclick function change boolean value and change attr visibility

So I'm learning Javascript and I have a doubt on changing a global variable with boolean variable, while changing the attr of visibility on an element.
The code is this:
var lastView=false;
$("#idShipmentActionsCombo-icon").on('click', function(){
if (lastview=false){
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: visible');
lastView=true;
}
else if(lastView=true){
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: hidden');
lastView===false;
}
}
So #idShipmentActionsCombo-icon is the element I click in, #idShipmentActionsCombo-lb and this is what I want to show and hide depending on the value of lastView.
Thanks in advance, and I apologize for my English since it's not my main language.
Since you use jQuery use .toggle() method instead of booleans, conditions and style.
$("#idShipmentActionsCombo-icon").on('click', function(){
$('#idShipmentActionsCombo-lb').toggle();
})
Looks like you're missing a closing ); at the very end from your .on( In addition, there are a few cases where "===" and "=" are confused and where capitalization is incorrect. See this: http://jsfiddle.net/215sxj90/3/
In my opinion you're confusing assignment with logical operators.
The following is the assignment:
lastView = true;
and the following is the logical operator - comparison:
lastView === true
The latter should be used in your conditional statements - if, else if etc.:
var lastView = false;
$("#idShipmentActionsCombo-icon").on('click', function () {
if (lastview === false) {
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: visible');
lastView = true;
}
else if (lastView === true) {
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: hidden');
lastView = false;
}
}

if this input has value doesn't work in IE 9

I am using this simple code to filter through a search form with many text inputs and see if they have a value and then add a class.
Works perfectly in Chrome, safari and Firefox but not in IE9.
$('input[type="text"]').filter(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
Please advice, thanks in advance!
EDIT
Change to each but doesn't solve the issue... Here it is with the event that triggers the function...
$(document).on('event-ajax-form-is-loaded', function() {
$('input[type="text"]').each(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
});
From the limited information you shared, this is how you should be doing this:
$('input[type="text"]').filter(function() {
return $(this).val() !== '';
}).addClass('used');
.filter() is supposed to reduce a set of matched elements so its filter function should always return a bool instead of manipulating the DOM.
Edit: Based on your updated code snippet and the page link you shared in the comments, if you are using jQuery in WordPress, then its always safer to wrap the code like so:
(function($) {
/* jQuery Code using $ object */
})(jQuery);
enter code hereIn JS you can check the element value by getting their tag name
for (var i = 0; i < document.getElementsByTagName('input').length; i++){
if (document.getElementsByTagName('input')[i].value == "")
{
alert("The value of textbox at " + i + " is empty");
}
}
Working Demo
Or like what other people suggest, use a .each in JQuery
$('input[type="text"]').each(function(i){
if ($(this).val() == "") {
alert("The value of textbox at " + i + " is empty");
}
});
anohter Working Demo
If you insist to use filter and here you go
$('input[type="text"]').filter(function()
{ return $( this ).val() != ""; }).addClass("used");
Last Working Demo
and jquery filter reference

alert not firing in JavaScript code

I have the following code and the first alert gives me an X but then the if block never fires. I'm sure its something simple I'm doing wrong...
$('.collectionofdates1>.datenumber').click(function(){
alert($(this).html());
if($(this).html() == "X"){
alert('asdf');
return false;
}
else{
$('.collectionofdates1 .datenumber').removeClass('selecteddate');
$(this).addClass('selecteddate');
}
});
2 recommendations:
1) put spaces in your selectors: $('.collectionofdates1 > .datenumber')
2) use text() when you mean text(), not html(). Also use .trim() to make sure you don't have whitespace: if($(this).text().trim() == 'X'){

If statement in Javascript?

Is this code correct?
if(!($('textarea: name').val().length == 0)) {
alert("test");
}
I want to check if there is something written or not inside the textarea field in the form? I ask because it's not working!?
You're missing your closing parens in your if statement. Try this:
if(!( $('textarea: name').val().length == 0 ))
{alert("test");}
There may be other jQuery selector issues.
if(!($('textarea').val().length == 0)) will work if you have only one textarea element in your page. I think what you were trying to do with that :name selector was select a specific textarea based on its name, in which case you need:
$('textarea[name=yourName]')
Since a length of 0 is "falsy", you can simplify your test to using just .length:
if ($('textarea[name=foo]').val().length) {
alert(true);
} else {
alert(false);
}
Here is a jsFiddle where you can play with it.
if ($('textarea: name').val().length > 0) {
// do something if textbox has content
}

Categories