Does something like jQuery.toggle(boolean) exist? - javascript

I write something similar to the following code a lot. It basically toggles an element based on some condition.
In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
I wish there was some sort of jQuery function that would work like this.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?

Ok, so I am an idiot and need to RTM before I ask questions.
jQuery.toggle() allows you to do this out of the box.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});

First, lets see if I understand what you want to do correctly...
You want to look at the state of a checkbox(checked or not) and hide or show a second div based on the status of that value.
Define this style:
.noDisplay {
display:none;
}
Use this JavaScript:
$("button").click(function() {
$("#mydiv").toggleClass("noDisplay", $("#name").val() == "");
});
The documentation from jQuery on it can be found here:
http://api.jquery.com/toggleClass/

You could write the function yourself.
function toggleIf(element, condition) {
if (condition) { element.show(); }
else { element.hide(); }
}
Then use it like this:
toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != "");

Syntax 4
$(selector).toggle(display)
display
true - to show the element.
false - to hide the element.

If toggle() is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:
$.fn.toggleIf = function(showOrHide) {
return this.each(function() {
if (showOrHide) {
return $(this).show();
} else {
return $(this).hide();
}
});
};
and then use it like this:
$(element).toggleIf(condition);

Related

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

Find and replace an option in select field

I am trying to find and replace an option in select box,
I am using this piece of code but this isn't working Help me out please!
$(".select" option).each(function() {
if $(this).val() == "Unknown" {
$(this).val().replaceWith( "---------" );
}
});
You need to put option inside the selector and use setter version of val():
$(".select option").each(function() {
if $(this).val() == "Unknown" {
$(this).val("---------");
}
});
something like this would also work:
$('#mySelect option:contains("Unknown")').text("---------");
http://jsfiddle.net/tKP68/
try out this...
$(".select option").each(function() {
if $(this).val() == "Unknown" {
$(this).val().replaceWith( "---------" );
}
});
Depending on what you want achieve:
$('select option').each(function () {
if (this.value === 'Unknown') { // You should always use === instead of ==
this.value = '---------'; // Change value
this.innerText = '---------'; // Change the option's text
}
});

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

jQuery: test if element is first of MATCHED elements

I have several divs that are alerts. The user dismisses them and after the final one (which is the FIRST in the DOM) I need to trigger some jquery magic.
Here's some simplified HTML:
​<body>
<div class="">Bla bla bla</div>
<div class="alert">A</div>
<div class="alert">B</div>
</body>​
Here's what I'm trying to do with jquery...
$(".alert").click( function() {
if ( $(this).is(".alert:first") ) {
//do stuff
}
});
It doesn't work. The conditional never returns true. The only way I can get it to work is using .index() but that sucks because if the order of the markup changes it will break the script.
What am I doing wrong?
EDIT: The solution uses .index() but in a way that I did not realize was possible. It is relative to the matched selection if used in that way. Thanks!
You can code:
$(".alert").click(function() {
if ($(".alert").index(this) == 0) {
//
}
});
http://jsfiddle.net/g2gGa/
Try this instead :
if ($(this).hasClass("alert") && $(this).is(":first")) {
//do stuff
}
Alternately :
$(".alert").click( function() {
if ($(".alert").index(this) == 0) {
//do stuff
}
});
Hope this will help !!
Try this jsfiddle
$(".alert").click( function() {
if (this == $(".alert:first")[0] ) {
//do stuff
alert(this);
}
});​
you can try this.
$('.alert').click( function() {
if ( ($(this)[0] === $('.alert').first()[0])) {
alert('first');
}
});​

Can I write this JQuery statement cleaner?

So I have the following:
var box = $(".MyCheckBox");
if (box[0].checked)
{
// Do something
}
else
{
// Do something else
}
Is there a better way of doing this using filters or something?
I know I can go:
$(".MyCheckBox")
.filter(function(index) {
return this.checked;
})
.each(function() {
// do something
});
But I need to do something in the else statement... easier way of doing this? Thanks!
You can use the built-in :checked selector:
$(".MyCheckBox:checked").each(function() {
//Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
//Do something with unchecked ones..
});
Or filter in the each similar to what you have:
$(".MyCheckBox").each(function() {
if($(this).is(":checked")) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
Or if say you wanted to toggle a class, then use a different approach, this would give the active class to the checked ones:
$(".MyCheckBox").each(function() {
$(this).toggleClass("active", $(this).is(":checked"));
});
Update
Based on comments if you want just raw speed:
$(".MyCheckBox").each(function() {
if(this.checked) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
attr('checked') returns the checked value of the first element anyway, so no [0] malarky.
if ($(".MyCheckBox").attr('checked')) {
// Do something
} else {
// else
}
I'd go with Nick's updated answer above, but would like to suggest that you complete your selector. i.e.,
$('input.myCheckBox').each(function(){
// tralalala...
}
... just for the fact that it makes your initial jQuery selection a bit faster. I mean, since we're debating about speed and all. ^_^

Categories

Resources