I need to be able to distinguish between the following three styles of button:
<button>Something</button>
<button><i class="icon-user"></i> Something</button>
<button><i class="icon-user"></i></button>
I have tried using html().length and Is('i') which allows me to distinguish between the first and the others but not sure of the best approach to determine if the content is only the icon or if there is also text.
$(this).children().length > 0 will return true in case 2 and 3.
$(this).text().length > 0 will return true in case 1 and 2.
Use those in combination.
You can do something like this. My example just changes the button background colour, but obviously you can change that to do whatever you like.
// Case 1
$('button:not(:has(i))').css('background', '#00f');
$('button:has(i)').each(function () {
var btn = $(this);
if (btn.text().length > 0) {
// Case 2
btn.css('background', '#0f0');
} else {
// Case 3
btn.css('background', '#f00');
}
});
Here's a Fiddle that shows it working: http://jsfiddle.net/SJDJD/
To check if the button has any html element(s):
$("button").each(function(i){
index = i+1;
htmlElements = $(this).find("*");
if(htmlElements.length > 0){
alert("Button no. "+index+" has an html object");
}
});
Related
Once a user clicks atleast 1 option from my dropdown menu, then the button colours change. Now when the user deselects ALL options (so that there are zero selected options), then I want the button colours to automatically change back to their original colours. Is that possible to achieve?
I tried working with if-else, but it didnt work. P.S. the user can deselect either unchecking each option box or use the "clear" button which clears all.
var i = $("li").index( $(this).parent() );
if ( i === 1 ) {
$('btn_clear').css('background', 'blue');
} else if ( i === 2 ) {
Here is my BOOTPLY ... BOOTPLY
just change your 2 click handlers to the 1 below:-
$(".products .checkbox, .availability .checkbox").on("click", function(e) {
var menu = $(this).closest('.dropdown-menu');
var checkCount = menu.find(':checked').length;
$('.btn_clear', menu).css('background', checkCount > 0 ? 'blue' : 'grey');
$('.btn_apply', menu).css('background', checkCount > 0 ? 'green' : 'yellow');
});
this just counts the checked from in its dropdown and sets the color accordingly.
Bootply
addendum
Here's the updated code for clear handler.
$(".btn_clear").on('click', function (e) {
e.stopPropagation();
var menu = $(this).closest('.dropdown-menu');
menu.find('input[type="checkbox"]').prop('checked', false);
$('.btn_apply', menu).css('background', 'yellow');
});
Just set up a default value for your color, and assign it that way:
var i = $('li').index($(this).parent()),
// here is the "original" color of the button.
color = 'red';
if (i === 1) {
color = 'blue';
} else if (i === 2) {
color = 'green';
} // etc
// Save yourself a bunch of repeated code, and only have the assignment once.
$('#btn_clear').css('background', color);
I'd consider using jQuery's .addClass() and .removeClass() then defining what color that class should have. This allows for some separation of concern when dealing with application logic vs. styling
style
.blue-text {
color: blue;
}
jQuery
var i = $("li").index( $(this).parent() );
if ( i === 1 ) {
$('btn_clear').addClass('blue-text');
} else if ( i === 2 ) {
$('btn_clear').removeClass('blue-text');
}
I'm trying to assign these css values (below) for the javascript line in the example below, but don't know a way to target valueB with the .valueB-class.
$(".valueA").html(valueA + " valueB" + ((valueA > 1) ? 's': ''));
.valueA-class { font-size:X }
.valueB-class { font-size:XX }
Here is an example of what I need help with (you may have to click on the input boxes in the results panel to get the calculations to show up - that's what I had to do): http://jsfiddle.net/hughett/g21g8t85/
Welcome to stackoverflow!
Your question seems a bit vague. I assume that this is you want to achieve. In the specific example the value of the class is changed through the use of the jquery attr function. Firstly, the specific div in which our text is placed is retrieved and then the value gets specified. I am attaching a code snippet below.
A general note, using a . in css indicates that you are referring to a class so there is no need to attach a -class in the name.
$( "#myButton" ).on( "click", function() {
var attr = $("#myText").attr('class');
console.log(attr);
if (attr == "valueA") {
$("#myText").attr("class","valueB");
} else {
$("#myText").attr("class","valueA");
}
});
.valueA { font-size:11pt }
.valueB { font-size:25pt }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Change Text size</button>
<div id="myText" class="valueA">sdsa asd aasdaas asdjlasj dasdkas asldjsalj slad TEST</div>
EDIT to include another answer
In order for the text included in a single span to have different font-size you need to separate it somehow. In the specific example, I have added a second span in the respective div and adjusted the cacl_summary method to get the expected result.
The code is available below; I have also updated the jsfiddle here
<div style="background:yellow;"><span class="label">Simple payback</span>
<span class="figure sp"></span> <span class="figure year"></span></div>
function calc_summary(){
if (cspy) {
sp = parseFloat($("input[name=upgrade]").val()) / cspy;
if (sp) {
sp = (sp < 100) ? sp.toString().substring(0, 4) : sp;
$(".sp").html(sp);
$(".year").html(" years" + ((sp > 1) ? 's': ''));
$(".ror").html(parseInt((1/sp) * 100) + '%');
}
}
}
When handling a jQuery event with multiple selectors, can I get the value of the selector triggered the event?
I'm aware of jQuery multiple selectors, get which selector triggered event and similar questions, but none of them seem to contain an answer to the fundamental question.
Suppose I have 3 buttons:
<button class='red stop danger'>red</button>
<button class='amber floor-it caution'>amber</button>
<button class='green go safe'>green</button>
With the accompanying Javascript code:
var clickCounts = {
red: 0,
green: 0
};
// we only want to count red and green clicks
$('.red, .green').click(function() {
// can't use clickCounts[$(this).attr('class')]
// because there are multiple class values present
clickCounts[??selector??] += 1;
});
If the only way to achieve this is by making a bunch of calls to is() or hasClass(), or write per-button handlers etc. then so be it, but I have yet to see a definitive answer.
Why not apply an ID to the button, and use that as your selector, instead of the class?
<button class='red stop danger' id="red">red</button>
<button class='green go safe' id="green">green</button>
Then:
$('#red, #green').click(function() {
clickCounts[$(this).attr('id')] += 1;
});
if you want per button counts,
i would personally stash it on a data attribute:
$('.red, .green').click(function() {
lastCount = $(this).data('clicks') || 0;
$(this).data('clicks', lastCount +1);
});
if you want global red/green counts,
i would do two separate handlers:
var clickCounts = {
red: 0,
green: 0
};
$('.red').click(function() {
clickCounts.red += 1;
});
$('.green').click(function() {
clickCounts.green += 1;
});
If you are just curious,
sorry I don't have an actual answer as to how to get the triggering selector for a jquery event; I suggest posting an issue
You can use Element.matches() and (for older browsers) Element. matchesSelector. For example:
$('.red, .green').click(function (e) {
var sel;
if ( e.target.matches && e.target.matches('.red') ||
e.target. matchesSelector && e.target. matchesSelector('.red')) {
sel = 'red';
} else {
sel = 'green';
}
clickCounts[sel] += 1;
});
You may want to try this:
http://jsfiddle.net/w3z3bfp4/1/
<button name='red' class='red stop danger'>red</button>
<button class='amber floor-it caution'>amber</button>
<button name='green' class='green go safe'>green</button>
$('.red, .green').click(function(e) {
clickCounts[e.target.name] += 1;
alert('RED '+clickCounts.red);
alert('GREEN '+clickCounts.green)
});
I'm trying to use "toggleClass" when the numeric value inside of the span.points is greater than "0". So it'll null, and then, if the value changes to 1, it'll add a class. Not sure how to accomplish this? Learning jQuery at snails pace... any help would be helpful. Thank you guys!
HTML
<div class="box">
<span class="points">4</span>
</div>
Failed JS Attempt
var points = $('.box > .points').length;
if(points > 0) {
$('.box').toggleClass('orange');
} else {
return false;
}
You should be using .text() or .html() and parse that to a number.
var points = parseFloat($('.box > .points').text());
if(points > 0) {
$('.box').toggleClass('orange');
} else {
return false;
}
Fiddle
Don't forget to either put that in a function or in an $(document).ready({ ... }) statement.
In my HTML code I have buttons 1, 2, 3 and 4 for 4 different views. I have some divs named as:
sheet(button id)+some string
So whenever I click on button 2 suppose, I want all the divisions with id=sheet2abc, id=sheet2xyz, etc to become visible and for the rest (i.e. 1, 3 and 4) the dispaly:none property should be set like for sheet1abc, sheet3abc, etc.
How can I do this via jQuery selectors?
KISS. Essentially:
$('[id^=sheet]').hide();
$('[id^=sheet'+num+']').show(); // num is a relevant value, see the example
Working example: http://jsfiddle.net/j4TzA/
I think you want to use wildcards in jQuery selectors.
This shows every div whose id starts with "sheet1":
$('div[id^=sheet1]').each(function() {
$(this).show();
});
And this hides the others:
$('div[id^=sheet]:not([id^=sheet1])').each(function() {
$(this).hide();
});
I created a fiddle to demonstrate that.
Buttons: button 1 and so on
Sheets: <div id="sheet1" class="sheet">sheet 1</div> and so on
jQuery:
$('.button').click(function(event){
event.preventDefault();
$('.sheet').hide();
$('#sheet'+$(this).attr('href')).show();
}
Next time make your question more clear.
You can filter like:
$('button').click(function() {
var $button = $(this);
$('div[id^=sheet]').each(function() {
if((new RegExp("^sheet" + $button.data('id') + ".*$")).test($(this).attr('id'))) {
$(this).show();
} else {
$(this).hide();
}
});
});
Then code buttons like:
<button data-id="1">1</button>