Jquery, getting 'this' selector from a conditional - javascript

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'));
});

Related

Updating a value on click once when multiple element exists

I have a fiddle here http://jsfiddle.net/wMUTg/56/ that I'm trying to update a value by one when a button is clicked, only once. Similar to the 'like' functionality on facebook. I've got that working, however if I have multiple elements that are similar only one is updating. I know I have to use the $this functionality but I'm struggling to find where to put it. Also, does anyone know if this can be achieved without an input field? Ideally I'd like it to be in a span tag but I needed the input to get the value first.
$(".red #update").one("click", function() {
var val;
val = $('#counter').val();
val++;
$('#counter').prop('value',val );
});
#CertainPerformance, is right. You should use class instead of same multiple IDs in one DOM.
However here is your solution:
Used $(this).prev('#counter') as selector to refer relevant element.
$(".red #update").one("click", function() {
var val;
val = $(this).prev('#counter').val();
val++;
$(this).prev('#counter').prop('value',val );
});

Function hide() , prev() , show() are assembled to get required result but unable to understand its working?

I have got a script which works fine. The script is :
var minimized_elements = $('.innovision-msg');
var minimize_character_count = 100;
minimized_elements.each(function(){
var t = $(this).text();
if(t.length < minimize_character_count ) return;
$(this).html(
t.slice(0,minimize_character_count)+
'<span>...</span>'+'Read more'+
'<span style="display:none;">'+ t.slice(minimize_character_count ,t.length)+ '<span>...</span>' +
'Read less</span>'
);
});
$('a.read_more', minimized_elements).click(function(event){
event.preventDefault();
$(this).hide().prev().hide();
$(this).next().show();
});
$('a.read_less', minimized_elements).click(function(event){
event.preventDefault();
$(this).parent().hide().prev().show().prev().show();
});
Here in this script i can not understand the meaning and use of code:
$(this).parent().hide().prev().show().prev().show();
Can any one explains what this line of code means ?
Moreover when it set var minimize_character_count = 250; Script does not works.
$(this).parent().hide().prev().show().prev().show();
This line is hiding the parent element of this element which is clicked (for minimization). After hiding the parent element, it goes to the previous sibling (of the parent element) and make it visible. It again goes to the previous sibling (of the previous sibling of the parent element) and make it visible.
Basically, jquery methods (after doing their job, whether to hide, show or traverse) returns the reference to the current element which allows you to chain the methods in this manner.
This is basically chaining which works on an returned object
$(this).parent().hide().prev().show().prev().show();
$(this) referring to either 'a.read_less', minimized_elements
On click on this element , it will find the parent dom and will hide it.
.prev() is use to select the previous element. So it will select the previous element and will show it. Again using prev() will select previous to previous element and will also show it
Method chaining is one of the nice features of jQuery. Most of the methods will return objects on which it is called, and hence you can call other methods in same chain.
Yet another one of the really cool aspects of jQuery is the fact that
most of the methods returns a jQuery object that you can then use to
call another method. This allows you to do command chaining, where you
can perform multiple methods on the same set of elements, which is
really neat because it saves you and the browser from having to find
the same elements more than once - source

Dependent selects with Chosen Jquery

I just want to do something very simple, which is a select depending on which option is selected it populates a second select.
I've always done this by hiding/showing selects this way (JS):
$( document ).ready(function() {
$("#select_1").change(function() {
if ($("#select_1").val()=="A") {
$("#select_2").show();
$("#select_3").hide();
}
else if ($("#select_1").val()=="B") {
$("#select_3").show();
$("#select_2").hide();
};
});
But now I'm trying Chosen and it does not work. It removes all Chosen mask and returns the selects to native. I've also tried this (JS):
$(document).ready(function(e) {
$("#select_2").css('visibility','hidden');
$(".chosen").chosen();
$("#select_1").click(function() {
if ($("#select_1").val()=="A") {
$("#select_2").css('visibility','visible');
}
And it doesn't work either. It does not remove the Chosen, but doesn't do anything. Any idea on this? I know it sounds pretty basic by I couldn't find an accurate response to it anywhere.
PS: I'm trying to do it with JS, not via AJAX.
I'm assuming that #select_1 is to have the chosen plugin applied to it. If this is correct, #select_1 is going to have a style of display:none; applied to it, so you not going to register any 'click' events on it.
If you look at the "chosen" documentation, http://harvesthq.github.io/chosen/, you can discover how to register a change handler to your chosen element.
If chosen is applied to #select_2 and #select_3, then toggling the visibility of these two elements is pointless because they are already hidden. The HTML rendered by the chosen plugin will have container elements with IDs of #select_2_chosen and #select_3_chosen - so toggle the visibility of these!
The code below assumes that #select_2 and #select_3 have the class 'chosen'. I am applying the chosen to #select_1 separately so I can bind the change event that is to be unique to it. Finally, I trigger the change event immediately after defining the change handler so that #select_3_chosen will become hidden.
$(".chosen").chosen();
$("#select_1").chosen().change(function () {
var value = $(this).val();
if (value=="A") {
$("#select_2_chosen").css('visibility','visible');
$("#select_3_chosen").css('visibility','hidden');
} else if (value == "B") {
$("#select_2_chosen").css('visibility','hidden');
$("#select_3_chosen").css('visibility','visible');
}
}).trigger('change');

Dynamically adding onchange function to drop down with jQuery

I have a couple of drop down boxes with ids country1, country2, ... When the country is changed in a drop down the value of the country shoudl be displayed in an alert box.
if I add the onchange handler for one box like this it works fine:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
But I need to do this dynamically for all drop down boxes so I tried:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
This doesn't work. No syntax error but just nothing happens when the seleted country is changed. I am sure that the each loop is performed a couple of times and the array contains the select boxes.
Any idea on that?
Thanks,
Paul
The reason .live() existed was to account for elements not present when you call the selector.
$('[id^=country]') .each(function(key,element){ iterates over elements that have an id that starts with country, but only those that exist when you run the selector. It won't work for elements that you create after you call .each(), so using .live() wouldn't do you much good.
Use the new style event delegation syntax with that selector and it should work:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Replace document with the closest parent that doesn't get dynamically generated.
Also, consider adding a class to those elements along with the id attribute.
Instead of incremental ids I'd use a class. Then the live method is deprecated but you may use on with delegation on the closest static parent or on document otherwise.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
You don't need an each loop this way; plus events are attached to all the elements in the jQuery collection, in this case all .country elements.

The best way to generalise a code for toggling the disabled attribute

The following code (*) for toggling the disabled attribute beetween two buttons works and you can check it at http://jsfiddle.net/cNSVX/3/.
I was wondering what is the best way to generalise this code in order to attach this behaviour to a couple of buttons.
Something like the following.
body.onload(togglingButton(elem1, elem2));
$('#filterOpened').click(function() {
$('#filterOpened').attr('disabled', 'disabled');
$('#filterClosed').removeAttr('disabled');
});
$('#filterClosed').click(function() {
$('#filterClosed').attr('disabled', 'disabled');
$('#filterOpened').removeAttr('disabled');
});
function togglingButton (elem1, elem2) {
if (elem2.attr('disabled')) {
elem1.attr('disabled', 'disabled');
elem2.removeAttr('disabled');
} else {
elem2.attr('disabled', 'disabled');
elem1.removeAttr('disabled');
}
};
​
You can do it like below with jQuery. Also if you are using jQuery 1.6+ then you should be using .prop() to toggle your disabled property.
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The prop method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
​$('button').click(function(){ //<--- attaches click to all button's
$(this).prop('disabled',true); //<-- only disable the clicked button
$('button').not(this).prop('disabled',false); //<-- all button's but the clicked one should be enabled
});​​​
here's an example fiddle http://jsfiddle.net/cNSVX/5/
If you are planning on excluding some buttons out of the toggling it would be a good idea to give them a class so you can select the ones you need/don't need easier
One simple way to do this would be to use jQuery's .data() function to link the two elements, then assign a single event handler to both:
function disableToggle(el1,el2) {
el1.data('partner',el2);
el2.data('partner',el1);
el1.add(el2).on('click',function(){
$(this).prop('disabled',true);
$(this).data('partner').prop('disabled',false);
});
}
$(function(){
var opened = $('#filterOpened');
var closed = $('#filterClosed');
disableToggle(opened,closed)
});
I've created a demo:
jsFiddle DEMO

Categories