Add "checked" to input when parent "a" selected, javascript - javascript

I have this html code:
<a onclick='addSelector(this)'>
<img src='resources/img/produkti/test.jpg'>
<input type='checkbox' value='test.jpg' name='main_image'>
</a>
And this is my javascript:
function addSelector(elem) {
var a = document.getElementsByTagName('a')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('selected')
}
elem.classList.add('selected');
elem.find( 'input[type=checkbox]').prop('checked', true);
}
So, when 'a' is clicked, it gets 'selected' class. I want to make it so child input gets 'checked' too. Is there any way to solve this?

epascarello's comment is correct, but ultimately your problem is that elem is not a jQuery object. You might have better success with $(elem) on your last line (or wherever you are applying jQuery functions).
A much better way of writing the whole thing would be to have a click listener on the element instead like this:
// Listen for an anchor being clicked
$('a').on('click', function(event) {
// Remove selected class from all anchors
$('a').removeClass('selected');
// Add selected class to this element
$(this).addClass('selected');
// Make the relevant checkbox ticked
$(this).find('input[type="checkbox"]').prop('checked', true);
});
Although as mentioned on here elsewhere, a label is better than an anchor :).

Replace the anchor (which isn't being used as an anchor anyway) with a <label>.
This will have the behaviour you want by default. It will also associate the alt text (which you should add) of the image with the input for screen readers.

Related

How to add an id to an existing div on click in css/js?

I'm new to html/css/js and I'm working on a small project where I have a few divs with the same classnames, for example:
<div class="imgBox">
Something here...
</div>
None of them have an unique id. What I want to do is to add an id to a single div after I click on it. It would allow me to modify the selected div and make it in css fullscreen or something like that.
Do you have any ideas how to create a function in js for it?
I couldn't find a proper solution on the internet, but if I missed something, let me know.
Not entirely sure of your logic for wanting to add the IDs after the element is created, but this would add the ID attribute when you click the div.
var global_id = 1;
// click on div
$('.imgBox').on('click', function(e){
existingID = $(this).attr('id');
if (typeof existingID == 'undefined'){
$(this).attr('id', global_id);
global_id++;
}
});

How to change button class in a div while just the last one can keep the change?

I'm using this code to change my buttons's class:
$('button').on('click', function(){
var btn=$(this);
if(btn.attr('class')=='tct-button'){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
The problem is that I have multiple div's with multiple buttons in each. I need to change this so that every time I click on a button in a div the others which were changed by a previous click (in that same div) change back to the default class which is 'tct-button', and just the last clicked button turns to 'tct-button2'. Would you please help me.
use toggleClass in jquery ,there is no need to check hasClass()
$(this).toggleClass("tct-button2 tct-button");
DEMO
Use hasClass()
Determine whether any of the matched elements are assigned the given class.
Code
$('button').on('click', function(){
var btn=$(this);
if(btn.hasClass('tct-button')){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
However I think you need
$('button').on('click', function(){
$('.tct-button2').removeClass('tct-button2'); //Remove all class
$(this).addClass('tct-button2'); //Add the class to current element
});
If you want to add an additional class to your buttons (tct-button2) whilst keeping tct-button on every button you could do what Satpal suggested.
However, from the sounds of it and I may be wrong, if you want to change the classes so that each button only has one class at a time on it (either tct-button or tct-button2) you can do similar to what Satpal suggested and use:
$('button').on('click', function(){
$('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Add original class and Remove tct-button2 class
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
Here is the example http://jsfiddle.net/lee_gladding/xao46uzs/
to only affect buttons in the div the clicked one belongs to, use a similar method to:
$('button').on('click', function(){
$(this).parent('div').find('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Remove all class in that div
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
(You might want to use a better selector for the parent, possibly a class or what ever your actual html uses)
Example:
http://jsfiddle.net/lee_gladding/xao46uzs/3/

Jquery, getting 'this' selector from a conditional

I have several elements on my page with the 'checkbox' class. When clicked, a corresponding checkbox input is checked. However, I need to have JQuery check if the checkbox element is active when the page first loads, and check the checkbox input accordingly at that time.
Since there are multiple 'checkbox' classes on my page, I used the 'this' selector previously and it worked fine, however I do not know how to make it do this with my conditional on page load without the .click action that I used before. Here's what I'm trying to make work:
if($('.checkbox').hasClass('active')) {
$('[name="'+$(this).attr('rel')+'"]').prop('checked', true);
}
Obviously the 'this' selector doesn't know what I'm referring to. Is there a better way of doing this? Since it's checking through a bunch of elements and not just one I'm stumped. Thanks!
You can only use this within the context of a jQuery function, so in this scope it's not going to refer to any .checkbox.
You can use .each instead:
$('.checkbox.active').each(function() {
// In this context, this refers to the DOM element represented by .checkbox.active
$('[name="'+this.rel+'"]').prop('checked', true);
});
The each function may suit your needs:
$('.checkbox').each(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$('[name="'+$this.attr('rel')+'"]').prop('checked', true);
}
});
If the checkboxes must be unchecked when the active class is absent, then:
$('.checkbox').each(function() {
var $this = $(this);
$('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active'));
});

Creating a "selected item" javascript code for navigation menu?

I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});

Is there a way to detect if I'm hovering over text?

What I'm really after is to detect when the cursor changes to type "text", that is, when I'm hover over a piece of text. I have tried looking at the element types I am hovering over, but this isn't too accurate because I don't know what they actually contain.
I understand that detecting the CSS cursor attribute is only possible if it has previously been assigned by me.
Is this possible at all? How would you go about doing this?
EDIT:
I do not want to check If I am currently over a specific element, I want to know if I am hover over any text within that element. A div could be 100% width of the browser, but with a shorter piece of text at the far left. I don't want to detect when hovering over just any part of an element.
No need to try to detect if the cursor changed.
You can simply detect if the mouse is hovering your text by using this kind of construct :
document.getElementById('myTextId').onmouseover = function() {
// do something like for example change the class of a div to change its color :
document.getElementById('myDivId').className = 'otherColor';
};
If you don't have an id but a class or a tag, you can replace getElementById by getElementsByClassName or getElementByTagName (which will return arrays on which you'll iterate).
If you want to restore the color when leaving the element, I suggest you bind the event onmouseout in the same way.
For example, if you want to do something on any paragraph, you may do that :
var paras = document.getElementByClassName('p');
for (var i=0; i<paras.length; i++) {
paras[i].onmouseover = function() {
// do something like for example change the class of a div to change its color :
document.getElementById('myDivId').className = 'otherColor';
};
}
I you plan to do a lot of things like this, I suggest you look at jquery and its tutorial.
One possible way is to find all the text nodes in your DOM and wrap them in a span with a certain class. Then you could select that class and do whatever you want with it:
// Wrap all text nodes in span tags with the class textNode
(function findTextNodes(current, callback) {
for(var i = current.childNodes.length; i--;){
var child = current.childNodes[i];
if(3 === child.nodeType)
callback(child);
findTextNodes(child, callback);
}
})(document.body, function(textNode){ // This callback musn't change the number of child nodes that the parent has. This one is safe:
$(textNode).replaceWith('<span class="textNode">' + textNode.nodeValue + '</span>');
});
// Do something on hover on those span tags
$('.textNode').hover(function(){
// Do whatever you want here
$(this).css('color', '#F00');
},function(){
// And here
$(this).css('color', '#000');
});
JSFiddle Demo
Obviously this will fill your DOM with a lot of span tags, and you only want to do this once on page load, because if you run it again it will double the number of spans. This could also do weird things if you have custom css applied to spans already.
If you're using jQuery (which you should, because jQuery is awesome), do this:
$("#myDiv").mouseover(function() {
$("#myDiv").css("background-color", "#FF0000");
});

Categories