More efficient javascript boolean - javascript

I have a checkbox and some <div>s that show/hides whenever a checkbox is checked. Now it all works great but it could be more efficient.
jQuery("#filtertype").change(function () {
if (jQuery("#posttype").is(":checked")) {
jQuery("#postblock").slideDown("slow");
} else {
jQuery("#postblock").slideUp("slow");
}
if (jQuery("#taxonomycat").is(":checked")) {
jQuery("#taxonomyblock").slideDown("slow");
} else {
jQuery("#taxonomyblock").slideUp("slow");
}
if (jQuery("#taxonomytag").is(":checked")) {
jQuery("#taxonomyblocktag").slideDown("slow");
} else {
jQuery("#taxonomyblocktag").slideUp("slow");
}
if (jQuery("#fieldjeskey").is(":checked")) {
jQuery("#fieldblock").slideDown("slow");
} else {
jQuery("#fieldblock").slideUp("slow");
}
if (jQuery("#sliderme").is(":checked")) {
jQuery("#sliderblock").slideDown("slow");
} else {
jQuery("#sliderblock").slideUp("slow");
}
});
This works like it should; it gets the ID of the checkbox <input> and for every <input> (#filtertype, #taxonomycat etc.) it will show or hide a <div> (#postblock, #taxonomyblock etc.)
It may be smarter to get the ID of every <input> and toggle the slideUp, slideDown function.
How can this be done?

Firstly, rather than have a list of id selectors, put a single class of each of those checkboxes, along with a data attribute to specify the relation. Something like this:
<input type="checkbox" name="posttype" class="filter-checkbox" data-rel="postblock" value="foobar" />
Then in javascript you can simplify all the code above to the following:
jQuery("#filtertype").change(function() {
$('.filter-checkbox').each(function() {
var func = this.checked ? 'slideDown' : 'slideUp';
$('#' + $(this).data('rel'))[func]('slow');
});
});
Example fiddle

It could be more efficient by not using jQuery.
Replace all of your jQuery("#someID").is(":checked") with
document.getElementById('someID').checked, and short of writing your own lightweight animation engine that's as good as you'll get.
Or you can go down the dark path of obscurity:
jQuery("#postblock")["slide"+(document.getElementById('posttype').checked ? "Down" : "Up")]("slow");
But that's probably not a good idea :p

Related

Toggle text of element with jquery

How do I toggle the text of an element with jQuery .click(), .toggle() and .text() only?
You can use a variable to hold the text to be toggled.
But please no classes to be turned off and on with .toggle().
One way you could do this is to change the class of an element to change your css differennces. If you want to add text or additional elements. Look into the .append() function in jQuery.
However, just a personal opinion here, AngularJS would make that kind of stuff very easy to do. If you haven't learned any frameworks yet, I suggest you take a look at it.
Try something like this,
var toggleText = "toggle",
value;
$('div').click(function() {
$(this).text(function(i, v) {
if (v == toggleText)
return value;
else {
value = v;
return toggleText;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>hi.....</div>
You could use .data()
$(this).data('toggle', 0); // initial data
$('div').click(function() { // on click
if($(this).data('toggle') === 0) { // if toggle is off
$(this).data('toggle', 1); // turn toggle on
} else { // if toggle on
$(this).data('toggle', 0); // turn toggle off
}
$(this).append($(this).data('toggle'));
});
Here's a JSFiddle

find select option with selected property using javascript

I have a view that loads select elements dynamically into the page on certain button clicks. Each of these selects have the same id value followed with an index value based on how many times the button is clicked. so the id would be like
id="my_id_" + numOfClicks;
I have also given all these selectors the same class value
class="selects"
What is the best way to have an event handler for when the selected option changes in any of the drop downs. right now I have the following:
$('.selects').change(function() {
if($('this option:selected').val() == 0) {
}
else {
}
});
So what I'm trying to do is first get the right select element using "this" then figure out which of the options are selected. Is there a better/more efficient way to do this?
As you say these get added at runtime, you'll want a delegated event handler. Within the handler, as the comments have pointed out, it's just $(this).val() to get the selected value of that select box. So:
$("selector for some container they're in").on("change", ".selects", function() {
if($(this).val() == 0) {
}
else {
}
});
For instance, if they're all inside an element with the class container, then:
$(".container").on("change", ".selects", function() {
if($(this).val() == 0) {
}
else {
}
});
If there's no other suitable container, you can just use $(document).on(..., but usually it's better to handle things a bit closer to where they are than that.
Side note: Values are always strings, but == will coerce, so "0" == 0 is true. Still, it's useful to remember that they're strings.
Assuming html input.selects:
$('body').on('change', '.selects', function() {
if($(this).val() == '0') {
}
else {
}
});
http://jsfiddle.net/r4pxx0yy/1/
No quote around this.

Attaching onmouseover after page is rendered?

Hi,
When the page first is rendered my div elements looks like this :
<div onmousedown="this.className='showhideExtra_down_click';"
onmouseout="this.className='showhideExtra_down';"
onmouseover="this.className='showhideExtra_down_hover';"
class="showhideExtra_down" id="extraFilterDropDownButton"> </div>
Then i manually updates the onmouse attributes with javascript so it looks like this :
<div onmousedown="this.className='showhideExtra_down_click';"
onmouseout="this.className='showhideExtra_down';"
onmouseover="this.className='showhideExtra_down_hover';"
class="showhideExtra_down" id="extraFilterDropDownButton"> </div>
They looks the same, the big difference is that the first one will change class when hovering and the second will not? Is it not possible to set this after page is rendered?
Please note : I need IE6 compability, thats why I use onmouse instead of CSS hover
BestRegards
Edit : This is what I found and that works grate, I haven´t tested it in IE6 just yet :
$("#extraFilterButton").hover(function() {
$(this).attr('class','showhideExtra_down_hover');
},
function() {
$(this).attr('class','showhideExtra_down');
});
you can use:
$('#selector').live('mouseover',function(){//something todo when mouse over})
live() allows for dynamic changes
(you can do the same for 'mouseout')
To expand on #maniator's correct answer, I would use:
$("#some_id").live("hover",
function() {
// do on mouseover
},
function() {
// do on mouseout
});
This is what I ended up with :
$("#extraFilterDropDownButton").hover(function() {
if($('#divCategoryFilter').css("display") == 'block'){
$(this).attr('class','showhideExtra_up_hover');
}
else{
$(this).attr('class','showhideExtra_down_hover');
}
},
function() {
if($('#divCategoryFilter').css("display") == 'block'){
$(this).attr('class','showhideExtra_up');
}
else{
$(this).attr('class','showhideExtra_down');
}
});
This is however not yet tested in IE6.

Toggle disable/enable checkbox by replacing class name

I have a set of 5 checkboxes with class set to "child". I want that if I select one checkbox, rest of them goes disabled. I have tried following code but it disables the all checkboxes.
if ( !$(this).is ( ":checked" ) ) {
$(this).removeClass().addClass("hand .parent");
$(".child").attr ( "disabled" , true );
}
then even i tried adding this
$(this).removeAttr ( "disabled" );
but it still disables the all controls
help plz! Thanks
Are you trying to do something like this?
See it here: http://jsfiddle.net/fEA3Y/
var $cbox = $('.child').change(function() {
if(this.checked) {
$cbox.not(this).attr('disabled','disabled');
} else {
$cbox.removeAttr('disabled');
}
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
If you really need to toggle classes for some reason, you could do this:
http://jsfiddle.net/fEA3Y/2/
var $cbox = $('.child').change(function() {
if(this.checked) {
$(this).toggleClass('child parent');
$cbox.not(this).attr('disabled','disabled');
} else {
$(this).toggleClass('child parent');
$cbox.removeAttr('disabled');
}
});​
Did you do
$('.child').removeAttr('disabled')
Since you tried it on .child, it's kind of hard to tell the context of this since you're not posting the full code.
Also, are you there there isn't a readonly attribute being set somewhere?

addClass function not worked using JQuery

I have the following code:
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".hideAccessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".hideAccessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
This script removes a class fine but it does not want to add the class. Can you see any issues with this code?
When you add hideAccessRequest class to the element, you search for it by the existence of that class.. if you are adding it, that class won't already be applied and thus you won't match any elements.
$(".hideAccessRequest") doesn't exist. you need to use id, I guess. And you might want to look at toggleClass.
you'd need an identifier for the classes you want to toggle ex:"accessRequest"... try this.
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".accessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".accessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
classes are space-delimited, so if you want them hidden by default...
<div class="accessRequest hideAccessRequest">...</div>

Categories