Trying to use && in a css data-bind in Knockout - javascript

I am new to knockout and am trying to check two booleans. Currently, I have:
data-bind="css: { hidden: bool1() }"
Hidden is a class I created in CSS. I need to check against two bools to use the class or not. It works fine with one bool. How do I use two?
I tried the following:
data-bind="css: { hidden: bool1() && bool2() }"
data-bind="css: { hidden: bool1() + bool2() }"
I'm just not getting it. Can anyone help please?

Here is a working example. The text is hidden if both boxes are checked. You need to call the observables when using them in an expression in the binding.
ko.applyBindings({
bool1: ko.observable(),
bool2: ko.observable()
});
.hidden {
visibility:hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="css:{hidden:bool1()&&bool2()}">I'm here!</div>
<input type="checkbox" data-bind="checked:bool1" />
<input type="checkbox" data-bind="checked:bool2" />

Update:
Oh! Silly me. Be sure to put in the parentheses after the bool1 and bool2.. so:
data-bind="css: {hidden: bool1(), hidden: bool2()}"
Also, be sure to put it in like a div tag, or whatever floats your boat.
There's a lot of documentation on http://knockoutjs.com/, so you should check that out of you haven't already. Tell me if it works.

This is another option (an extension to Roy J's), it keeps your html a little simpler, and makes refactoring easier if you use the combination of bools in more than one place.
bool1 = ko.observable();
bool2 = ko.observable();
ko.applyBindings({
bool1: bool1,
bool2: bool2,
shouldHideDiv: ko.computed(function () {
return bool1() && bool2();
})
});
.hidden {
visibility:hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="css:{hidden: shouldHideDiv}">I'm here!</div>
<input type="checkbox" data-bind="checked:bool1" />
<input type="checkbox" data-bind="checked:bool2" />

Related

Check if a div is disabled jQuery

I need to check whether myDiv1 is disabled. If so, I need to hide myDiv2, otherwise I need to show myDiv2.
Here is what I have so far:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is('[disabled=disabled]')
alert(isDisabled); //this always returns false
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
But isDisabled return always false even when myDiv1 is enabled. What am I missing here?
So many answers, but none addressing the actual problem: A div element doesn't allow an attribute of type disabled. On a div only global attributes are allowed, whereas disabled is allowed on form elements.
You can easily verify it by testing this HTML:
<div id="a" disabled></div>
<input id="b" disabled>
against this JavaScript:
var e = $('#a');
alert(e.is(':disabled'));
var e = $('#b');
alert(e.is(':disabled'));
Which will return false and true.
What's a solution then?
If you want to have an attribute that is actually named disabled use a data-* attribute:
<div id="c" data-disabled="true"></div>
And check it using this JavaScript:
var e = $('#c');
alert(e.data('disabled'));
or:
var e = $('#c');
alert('true' === e.attr('data-disabled'));
Depending on how you're going to handle attached data-*-attributes. Here you can read more about jQuery's .data() which is used in the first example.
Demo:
Try before buy
The reason why isDisabled returns false to you is, because you have most likely set the following in your HTML:
<div id = "myDiv1" disabled>...</div>
In reality, disabled means disabled = "", so, since "disabled" != "", if you keep using $('#myDiv1').is('[disabled=disabled]') you will always get false.
What will work:
To make this work, as other answers have mentioned, you can use:
$('#myDiv1').attr('disabled') == "disabled" (#guradio answer),
$('#myDiv1').is('[disabled=""]') or
$('#myDiv1')[0].getAttribute("disabled") != null.
What won't work:
While $('#myDiv1')[0].getAttribute("disabled") != null will work regardless of what element the attribute is set on, on the other hand, $('#myDiv1')[0].disabled will only work on 'form elements' and will return undefined for all others (check out the note at the end).
The same occurs when you use $('#myDiv1').is(':disabled') as well.
Alternatively, if you want to keep your code intact, you can set disabled = "disabled" in your HTML and the problem will be solved.
Working Example (using 2.):
/* --- JavaScript --- */
$(document).ready(function(isDisabled) {
isDisabled = $('#myDiv1').is('[disabled=""]');
if (isDisabled) $("#myDiv2").hide();
else $("#myDiv2").show()
/* Will return 'true', because disabled = "" according to the HTML. */
alert(isDisabled);
});
<!--- HTML --->
<script src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "myDiv1" disabled>DIV 1</div>
<div id = "myDiv2">DIV 2</div>
Note: Beware, however, that the disabled attribute is meant to be used with 'form elements' rather than anything else, so be sure to check out the very informative answer of #insertusernamehere for more on this. Indicatively, the disabled attribute is meant to be used with the following elements:
button,
fieldset (not supported by IE),
input,
keygen (not supported by IE),
optgroup (supported by IE8+),
option (supported by IE8+),
select and
textarea.
$('#myDiv1').attr('disabled') == "disabled" ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Try this way. But i dont think div has disable attribute or property
$('#myDiv1[disabled=true]').length > 0 ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Using attribute selector
attribute selector
Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.
First you need to set disabled property for your div
<div id="myDiv" disabled="disabled">This is Div</div>
Then you need to use this
$('#myDiv1').is('[disabled=disabled]')
Use this one:
$(document).ready(function () {
if($('#myDiv1').is(':disabled'))
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
I hope this will help you:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is(':disabled')
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
Use $("#div1").prop("disabled") to check whether the div is disabled or not. Here is a sample snippet to implement that.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.container {
width: 100px;
height: 100px;
background: grey;
margin: 5px;
float: left;
}
div {
width: 100%;
float: left;
}
</style>
</head>
<body>
<div>
<input type="checkbox" id="ChkBox" onclick="UpdaieDivStatus()" /> Toggle access
</div>
<div id="div1" class="container">Div 1</div>
<div id="div2" class="container">Div 2</div>
<script>
function UpdaieDivStatus() {
if ($("#ChkBox").prop('checked')) {
$("#div1").prop("disabled", true);
} else {
$("#div1").prop("disabled", false);
}
if ($('#div1').prop('disabled')) {
$("#div2").hide();
} else {
$("#div2").show();
}
console.log($("#div1").prop("disabled"));
}
</script>
</body>
</html>
If you look at this MDN HTML attribute reference, you will note that the disabled attribute should only be used on the following tags:
button, command, fieldset, input, keygen, optgroup, option, select,
textarea
You can choose to create your own HTML data-* attribute (or even drop the data-) and give it values that would denote the element being disabled or not. I would recommend differentiating the name slightly so we know its a custom created attribute.
How to use data attributes
For example:
$('#myDiv1').attr('data-disabled') == "disabled"
Why don't you use CSS?
html:
<div id="isMyDiv" disabled>This is Div</div>
css:
#isMyDiv {
/* your awesome styles */
}
#isMyDiv[disabled] {
display: none
}
Set the disabled attribute on any HtmlControl object. In your example it renders as:
<div id="myDiv1" disabled="disabled"><div>
<div id="myDiv2" ><div>
and in javascript can be checked like
('#myDiv2').attr('disabled') !== undefined
$(document).ready(function () {
if($('#myDiv1').attr('disabled') !== undefined)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="myDiv1" disabled="disabled">Div1<div>
<div id="myDiv2" >Div1<div>

How to check if a checkbox is checked using *jquery mmenu plugin*

Hi :) a subject very explanatory I guess. I know this question was asked before, but none of the proposed solutions worked with the mmenu plugin.
Here is the link to use checkbox:
http://mmenu.frebsite.nl/documentation/addons/toggles.html
I used both ways to verify if a checkbox was checked:
HTML
//bicisenda is the input id.
<input id="bicisenda" type="checkbox" name="poi" value="Bicisenda" class="Toggle">
JS/JQuery
$('ul li ul li #bicisenda').click(function() {
var _checked = $("#bicisenda").is(":checked");
if (_checked) {
console.log("Checked");
}
});
The author'splugin suggested me to try the code below:
$('#bicisenda').change(function() {
var _checked = $("#bicisenda").is(":checked");
if (_checked) {
console.log("Checked");
}
});
His explanation was that with this add-on the input is hidden, so I see a label that is linked to the input. Summed it up, I don't click the input.
However his suggestion didn't work either.
Any ideas how to check if a checkbox (or radiobutton) is checked?, thanks so much in advance
Well after digging deeper with the plugin code, I finally get it working.
The solution was the following
HTML
<input id="bicisenda" type="checkbox" name="bic" value="Bicisenda" class="Toggle">
JQuery
I made a function that is called in the html code.
function bicis() {
var $bicisendas = $('input[name="bic"');
$bicisendas.click(function() {
if ($bicisendas.is( ':checked' ))
{
console.log("Checked");
}
});
}
I store the input jquery object in the variable $bicisendas and then I check the checked property when the click event occurs. I couldn't check for the property straightforwardly because the check button was wrapped by a label. I needed to isolate the element in that way to rid of the wrapper.
This is my reasoning but being me a js/html5 newcomer any more elaborated explanations or solution are welcome :)
$('ul li label span #bicisenda').click(function() {
if(this.checked) {
console.log("Checked");
alert("checked");
} else {
console.log("UnChecked");
alert("Un Checked");
}
});
input[type="checkbox"] {visibility: hidden;position: absolute}
label {padding: 20px;cursor: pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li>
<label><span> <!--img src="imagenes/bird1.png" /--><a href="#pi/Bicesendas">Bicisendas
<input id="bicisenda" type="checkbox" name="poi" value="Bicisenda" class="Toggle"></a>
</span>
</label>
</li>
</ul>

Angular ng-show/ng-hide issue in nested ng-repeat

I'm new to angular and I know this question has already been asked so many times but I'm not able to make it here.
Here is the JSBin for my problem:
What I'm trying to accomplish here a list of cards (trello style) but I'm not able to make it as it does in trello. Here when clicking add card, angular's compile successfully add the card to list but I'm stuck to hide add card anchor tag then. I've applied some ng-show/ng-hide but then it doesn't maintain the index and hides other add card anchor in the ng-repeat (I know its natural but I'm not able to sort it out). Can somebody please help me here. Thanks
Here is the code as well:
Angular code:
angular.module('app', []).controller('DemoCtrl',function($scope,$compile,$window){
$scope.items = [];
$scope.idx = '';
$scope.c = {};
$scope.addNewList = function () {
if(typeof $scope.c.newList === 'undefined'){
alert('list title blank');
return;
}
$scope.items.push({listTitle: $scope.c.newList});
$scope.c.newList = '';
};
$scope.addNewCardToList = function(idx) {
$scope.idx = idx;
var elm = '<div class="list-card"><textarea style="overflow: hidden; word-wrap: break-word; resize: none; height: 56px;" ng-model="c.title"></textarea><input type="button" value="Add" ng-click="saveNewCardToList(idx)">X</div>';
var temp = $compile(elm)($scope);
if($window.document.getElementsByClassName("list-card").length === 0)
angular.element(document.querySelector('#compose_'+idx)).append(temp);
};
});
HTML:
<div ng-controller="DemoCtrl">
<div ng-repeat="item in items" style="display:inline-block;width:120px;">
<div>{{item.listTitle}}</div>
<div ng-repeat="inner in item.items">{{inner}}</div>
<div id="compose_{{$index}}"></div>
Add a card...
</div>
<br />
Add a list...
<div ng-show="showInput">
<input type="text" placeholder="Add a list..." name="title" ng-model="c.newList">
Save
</div>
</div>
Even if your JSBin is working partially (Add and X button below textarea are not working), best solution with keeping your approach way about angular
is here
BUT, this approach doesn't seems like angular-way. Commonly, anything related with DOM controlling in controller is not best practice. This will be great guide for you.
Anyway, I completed another JSBin just working fine entirely. Take a look.

$('form:not(.some-class)').keydown is still applying keydown event to .some-class

JQuery's ':not' selector is not preventing the intended-to-be-excluded class (which decorates an element) from firing the .keydown event. Why?
From the following code, when I press a key in the .newOwnerEntryInput field, I expect to see the alert for '1' only. But I see both alerts '1' and '2'.
Javascript:
$('.newOwnerEntryInput').keydown(function (event) {
alert('1');
});
// Prevent Enter from submitting form.
$('form:not(.newOwnerEntryInput)').keydown(function (event) {
alert('2');
});
HTML:
<li style="position: relative">
#Html.DropDownList("cftMemberID", null, String.Empty, new { #class = "actionOwnerDropDown hidden" })
<div class="newOwnerEntryDiv">
<input class="newOwnerEntryInput" />
<div class="float-right closeNewOwner">
<img src="~/Images/cancel_x.png" alt="close" />
</div>
</div>
</li>
I have tried a variety of quotes styles, with and without surrounding the excluded class with quotes, as well as adding 'input' after the class, as in $('form:not(.newOwnerEntryInput input)').keydown
Thanks!
Thanks for those who helped. I do need the form to fire for ALL types of input fields, not just those of type input. So that was out.
Here is what solved my problem:
$('form').keydown(function (event) {
if (! event.which.hasClass('.newOwnerEntryInput')) {
alert('2');
}
});
In this case, for my input of class .newOwnerEntryInput, if a key is pressed, it will NOT fire the event and push '2' out to the alert screen.
Again, thanks, it took a couple responses, all of which had a piece of the solution, for me to answer this myself. :)
Try this:
HTML:
<div>
<input class="newOwnerEntryInput" type="text"/><br />
<!-- I know you have MVC dropdown list, but I replaced it with a html textbox (for simple testing) -->
<input class="newOwnerEntryInput1" type="text"/>
</div>
JavaScript:
$('input.newOwnerEntryInput').keydown(function (e) {
alert('1');
});
$('input:not(.newOwnerEntryInput)').keydown(function (e) {
alert('2');
});
I checked with the documentation that in their example, I saw they had the element input followed by the function with the selector.
The documentation is available is here: jQuery :not()
I hope this helps!
Cheers!
Try this :
$('form input:not(.newOwnerEntryInput)').on('keydown',function (event)
{
alert('2');
});
http://jsfiddle.net/rzseLj27/

jQueryCheckboxes being locked to checked state

I have two forms in different tabs, each crossover field has it's value duplicating to the other form onchange/keyup.
When my checkboxes change there is also a background image change to highlight the selection, for some reason I cannot figure out why but when the checkboxes are turned on they will not turn off again.
jsfiddle link > http://jsfiddle.net/UMwkV/
html
<fieldset class="fieldset-form left">
<label>Flammable</label>
<div class="clear"></div>
<div class="flammable"></div>
<input type="checkbox" id="flammable" class="flamcheck" name="flammable" value="1" style="width:12px; height:12px; margin:0 auto; display:block; margin-top:5;">
</fieldset>
<fieldset class="fieldset-form left">
<label>Flammable</label>
<div class="clear"></div>
<div class="flammable"></div>
<input type="checkbox" id="flammable" class="flamcheck" name="flammable" value="1" style="width:12px; height:12px; margin:0 auto; display:block; margin-top:5;">
</fieldset>
jQuery
$("input[name=flammable]").change(function() {
if ($('.flamcheck').is(":checked")) {
$('.flammable').css("backgroundColor", "url(images/flame-on.png)");
$('.flamcheck').prop("checked", true);
}
if (!$('.flamcheck').is(":checked")) {
$('.flammable').css("backgroundImage", "url(images/flammable.png)");
$('.flamcheck').prop("checked", false);
}
})​
If anyone could point out the obvious thing I'm missing it would be greatly appreciated.
use
$(this).is(":checked")
instead
http://jsfiddle.net/UMwkV/6/
$.is() returns true when at least one element matches the selector. Once when both boxes are checked, when you click on one box again, the other checkbox still will be checked, so is() will always return true when you run it on both checkboxes.
AFAIK .is(':checked') runs against the DOM as it was rendered over the wire, not the current live DOM.
So the solution is to use .prop('checked') instead
http://jsfiddle.net/UMwkV/1/
Version 2 allows for independant checking:
http://jsfiddle.net/UMwkV/2/
Version 3 causes mutual updating, and both checkboxes are clickable:
http://jsfiddle.net/UMwkV/8/
I figured out the issue.This code will just work fine
$(".flamcheck").change(function() {
if ($(this).prop("checked") == true ) {
$('.flammable').css("backgroundColor", "url(images/flame-on.png)");
$('.flamcheck').prop("checked", true);
}
if ($(this).prop("checked") == false) {
$('.flammable').css("backgroundImage", "url(images/flammable.png)");
$('.flamcheck').prop("checked", false);
}
});
Check this- http://jsfiddle.net/UMwkV/10/
check this working demo
your code has a syntax error i have corrected it please check the fiddle

Categories