If/Else statement within ng-click - javascript

I am trying to create a conditional statement within my ng-click function. I have the if working, but now I need to figure out how to get an else. I have the following code currently:
<div ng-click="item.subCategory.length > 1 && showSubCategories();">
This runs a function to display my sub-categories if there is more than 1 sub-category within a category. What I would like to do is expand on it so that I can run a different function if there is only 1 sub-category.
In Javascript the statement would look like this:
if (item.subCategory.length > 1) {
showSubCategories();
} else {
showProducts();
}
Is it possible to do that within an ng-click?

Yes. Ternary operators are available to ng-click:
<div ng-click="item.subCategory.length > 1 ? showSubCategories() : showProducts()">
That should let you do what you want.

A cleaner way to do this would be to create a wrapper function (obviously name it whatever makes sense to you). This keeps the logic in one place and also scales well (what happens when you need more checks?)
showSubCategoriesOrProducts(item) {
if (item.subCategory.length > 1) {
showSubCategories();
} else {
showProducts();
}
}
Then in the view:
<div ng-click="showSubCategoriesOrProducts(item)">

HTML:
<div ng-click="onClick(item);">
JavaScript
$scope.onClick = function(item) {
if (item.subCategory.length > 1) {
showSubCategories();
}
else {
showProducts();
}
}

I hope this will work
ng-click="item.subCategory.length > 1? showSubCategories() : showProducts()" .
here, the part before "?" is the condition. If it is true, the part after "?" i.e. showSubCategories() will execute. If the condition is false the later will be executed

Related

For loop with eval not working

My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});

Wanting to toggle class, when value is greater than 0?

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.

How to bypass function for element with specify class and two conditions with jQuery

It's hard to say in couple wors in title... So i have this code:
var class_main_content = $('.main_content ul').attr('class');
var xml_element_name = $(xml).find(class_main_content)[0].nodeName.toLowerCase();
var no_option = $('.no_option').attr('class');
if ((class_main_content) == xml_element_name){
...
}
else if ($(class_main_content) == (no_option)){
...
}
and i have first condition with some actions - every things fine, next i have second condition which first condition is also performs, but i need to do something for element with class .no_option. The problem grows when this element have two class from first condition and second. How to pass by first condition and do something for second? :)
Rather than getting the class attribute and comparing it against things, why not use the hasClass JQuery function:
var main_content=$('.main_content ul');
if(main_content.hasClass('something')) {
do_something();
}
if(main_content.hasClass('no_option')) {
do_something_else();
}
You can of course do the reverse test:
if(!main_content.hasClass('no_option')) ...

JQuery, a new Selection using the results

Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?

What is wrong with this simple javascript function to swap the CSS class of an HTML body?

I've been staring at this for too long. I've put alerts throughout and the flow is correct. The styles exist. The body starts with the "styleBlack" class. The condition of the if statement is met and the body's class becomes "styleLight". A second call meets the condition of the else statement but the innerHTML of mDiv does not change, nor does the class of the body.
function ColorSwap() {
var mDiv = document.getElementById("m_divSwap");
if (mDiv.innerHTML = "Go Light") {
mDiv.innerHTML = "Go Dark";
document.body.className = "styleLight";
} else {
mDiv.innerHTML = "Go Light";
document.body.className = "styleBlack";
}
}
You're assigning instead of comparing
Change
if (mDiv.innerHTML = "Go Light")
to
if (mDiv.innerHTML === "Go Light")
At a first glance, it seems that in your if instead of comparing a string value (with ==)you are assigning (with =).
In my opinion you could use JQuery that is a cross browser standard javascript framework, you could download from here (http://docs.jquery.com/Downloading_jQuery).
Also you could put an id attribute to your body like
And the jquery code could be like this:
function ColorSwap() {
if ($("#m_divSwap").text() == "Go Light")
{
$("#m_divSwap").text("Go Dark");
$("#mybody").removeClass('styleBlack');
$("#mybody").addClass('styleLight');
}
else
{
$("#m_divSwap").text("Go Light");
$("#mybody").removeClass('styleLight');
$("#mybody").addClass('styleBlack ');
}
}
Hope it helps.
Best Regards.
Jose.

Categories