jQuery if data-id element hasClass not working - javascript

I don't know if the function i am trying to create is missing an element or if I am missing something but my function isn't working at all. Not sure if am missing something or if i am not adding something. let me know I provided jQuery and screenshot of the code i am trying to get to work. Basically what i am trying to do is if a certain element that has a data-id has a certain class then hide certain list-items.
$(function($){
if( $('.chbs-vehicle[data-id="313"] a').hasClass('chbs-state-selected') ){
$('ul.chbs-list-reset li(1)').hide();
}
});

li(1) isn't a valid expression and you should use a different evaluator:
$('ul.chbs-list-reset li:eq(0)')
$('ul.chbs-list-reset li:first-child')
$('ul.chbs-list-reset li').eq(0)
Take a look at this Demo
If your condition is met on page load, it works just fine. However, if the chbs-state-selected class is added dynamically, you need to listen for that change with an event handler. Your script as you have it doesn't constantly poll the document to see if Vehicle 313's a has the class.
Based on your comment, it sounds like you need to listen for that same click event that adds the chbs-state-selected class. Check out this rudimentary Demo.
Given this, you don't necessarily need to check for the class, just attach the hide/show functions to the same event. However, if necessary you can add the hasClass check to it.
Regardless, it should be inside that same handler that adds the chbs-state-selected in the first place

You can use eq: jquery function
$(function($){
if( $('.chbs-vehicle[data-id="313"] a').hasClass('chbs-state-selected') ){
$('ul.chbs-list-reset li:eq(0)').hide();
}
});

Related

Assigning JQuery On Click Function in For Loop

I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!

Checking if currently clicked element is equal to a specific div 'id' in JQuery

I have researched on the web and tested for a solution for quite a while, but have not been able to make this work. So I have decided to create a post here, even though its probably low-skilled and I'll get downvoted for it I have put a lot of effort and I hope someone can help out.
My code at the moment uses .click() function from JQuery and my goal is to use it on a button so that when I click that button, it checks whether the id of the button clicked on matches a variable that I set in the .js file. In other words, check if the thing I clicked on's id is equal to my "target".
This is the part of the code with the problem:
var target = '#vig_but_inc';
$(this).click(function() {
if(this.id == target) {
vigor.incStat(); // increase stats once
console.log("hi"); // test if code fires
$('#vig_res').html(vigor.current);
}
});
Please note I have checked if the code works without matching the id, without the if-statement - in that situation if I click on a specific, preset button's id I managed to increase the value of #vig_res which is my goal.
However with the if involved, as explained prior, I am trying to match what is being clicked on with my target, which is the id name I wish it to match to. I'm using this to check my click, which has worked in other areas but doesn't seem to work in this context.
I have made the variable target global scope as explained here in the comments: Check if the clicked div id matches with variable. It still doesn't work.
I know and have tested $(this).click(.., where it would fire off the code inside of whatever div I clicked. So I believe the problem lies afterwards, maybe in the this.id, but I've also used .is() like suggested elsewhere but it won't work that way either.
I hope someone can give me some insight into how to tackle this problem, thank you.
The answer is a little more complicated, in the anonymous function which is called when the click is triggered, this is not the clicked element, it is a jQuery object. You should accept as first parameter event and use event.target. Plus, target should not contain the #, because the .id returns only the name.
So, your code should look like this:
var target = 'vig_but_inc';
$(this).click(function(event) {
console.log(event.target);
if(event.target.id == target) {
vigor.incStat(); // increase stats once
console.log("hi"); // test if code fires
$('#vig_res').html(vigor.current);
}
});
Working Fiddle: https://jsfiddle.net/e8np0g9j/3/
Use the id and class selected before calling the click function like
$('.class').click(function() {});

jQuery on mouseout do nothing?

I have some effects in my menu, which works fine, but these effects shouldn't trigger on a menupoint which belongs to class "active". How should I do that? Using eval or similar things?
To sum it up: I want to deny an effect if the trigger has a special class.
In each of your mouse events, use .hasClass() in an if() statement:
$('.selector').mouseout(function() {
if($(this).hasClass('active'))
{
return;
}
// The rest of your code.
});
Here, the if() checks to see whether the element the event was fired on has the class active. If it does, the function returns, not executing any more code inside it.
You haven't given any code or HTML to work with, so this is a general solution. Please update your question with more detail so I can give you a better answer.
In the trigger function, just wrap your code with
if ($(this).not('.active')) {
...
}
JamWaffles and Cito's way works and are the most effective but just as an alternative you could also do it like this, first fetch the class value:
var className = $('.myclass').attr('class');
Then you want to check the value
if (className != 'whatever') {
// animate and stuff etc
}
But like I said, the other methods are better so you might as well use the built in features of jQuery such as hasClass - just showing theres more than one way to tackle problems :)
bind to (not) active like this:
$('.menuitem:not(.active)').live('mouseout',function(){});

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

jQuery Hide using ID

I'm trying to change the border color of an image using its id with jquery
( photo['id'] is passed in from a previous function )
the ids of the photos are of the form 'photo239839'
$('#photo'+photo['id']+'').click(function(){
$('#photo'+photo['id']+'').css('border-color','#777');
});
When I try to use this same code using its class it works,
but I can't use this method since there are multiple images on the same
page with the same class
$('img.flickr_photo').click(function() {
$("this.flickr_photo").css('border-color','#777');
});
This is what you need to do:
$('img.flickr_photo').click(function(){
$(this).css('border-color','#777');
});
I would always always add a css class rather than an inline style.
Much more maintainable and extensible.
Example:
$('img.flickr_photo').click(function(){
$(this).addClass('greyishBorder');
});
Either photo['id'] is wrong, or is changing after you set up the click handler.
To test for the first case, you can alert (or console.log with FireBug, or whatever) the length of the jQuery selection:
alert($('#photo'+photo['id']).length);
The solution in the second case is to use 'this'. In the click handler, 'this' is set to the element that caused the click event.
$('#photo'+photo['id']).click(function(){
$(this).css('border-color','#777');
});
Edit: #Dreas Grech is right, as long as you want to apply the behavior to all the elements with the flickr_photo class. If you can generalize the selector to select all the elements with a single query, it's better to do that.

Categories