jQueryCheckboxes being locked to checked state - javascript

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

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>

How to make checkbox visible when main checkbox checked?

good morning guys,
I have 3 checkboxes created in php. one that i want to use as a controller
<p>
<?php $creates = array('name'=> 'single_obs_value','class' => 'singleobsyes','value'=> '1','style'=>' float: left; margin-right: 2px;'); ?>
<?=form_label('Single Observation : ');?>
<?=form_checkbox($creates);?>
<br>
</p>
And the other two are brought in from a database array variable.
<p>
<?php foreach($obsnames as $cp){ ?>
<?php $create = array('name'=> 'cms_permissions[]','class' => 'singleobs','value'=> $cp->id,'style'=>' float: left; margin-right: 10px;'); ?>
<span style="width:200px; float:left">
<?=form_checkbox($create ).' '.form_label($cp->field_name);?>
</span>
<?php } ?>
</p>
How do i first make the two brought in by the database invisible when the page loads. Then when the controller checkbox is ticked make the two checkboxes visible again. If possible with a jquery function that uses the class of the controller checkbox as such.
$('#singleobsyes').change(function(){
Rather than
$('input[type="checkbox"']
As i use other checkboxes on the page and i believe that may cause some conflict.
try this
$(document).ready(function(){
$('input[type="checkbox"]').not('.singleobsyes').hide();// hide all checkboxes other than controller
$('.singleobsyes').change(function(){
if($(this).is(':checked')
$('input[type="checkbox"]').not('.singleobsyes').show();
else
$('input[type="checkbox"]').not('.singleobsyes').hide();
});
});
update: see this fiddle
you can also do this with css selectors as
html
<input type="checkbox" class="singleobsyes" name="a"/>check to show others
<input type="checkbox" class="singleobs" name="b"/>
<input type="checkbox" class="singleobs" name="c"/>
css
.singleobs{
display:none;
}
.singleobsyes:checked ~ .singleobs{
display:block !important;
}
fiddle
you can use wrapper too
fiddle v2
To make the checkboxes invisible you can style="display:none"
Now you can put on the "main" check box an onchange="showem();" attribute.
function showem()
{
$('#checkbox1id').toggle();
$('#checkbox2id').toggle();
}
EDIT: Changes show to toogle
You can make it simple this way,
$(document).ready(function(){
$('input[type="checkbox"]').not('.singleobsyes').hide();
$('.singleobsyes').on("change", function(){
$('input[type="checkbox"]').not('.singleobsyes').toggle();
});
});

When div is clicked, check corresponding radio input jquery

Here's my problem, I want an entire div to be click able, when clicked I need the radio button contained in the div to be checked, so the div acts as a radio itself. Here's what I thought I could use;
$('#content').click(function(e) {
$('input:radio[name="id_"]').prop('checked', true);
});
But this is not selecting the relative radio inside the div. I think I can use a this selector, am I right?
You don't give any code, so I guess:
DEMO
See my demo on CodePen
HTML
<div class="content">
<input type="radio" name="foo">
</div>
<div class="content">
<input type="radio" name="foo">
</div>
<div class="content">
<input type="radio" name="foo">
</div>
CSS (for example)
.content {
float: left;
width: 100px;
padding-top: 100px;
background-color: #eee;
margin-left: 10px;
}
JS (JQUERY)
$('.content').click(function(){
$(this).find('input[type=radio]').prop('checked', true);
})
Yes you can use the this selector. I have made a quick jsfiddle to show you an example.
This should do it.
$('input:radio[name*="id_"]'), assuming the name starts with id_
And yes you can use this. Use it to filter down its children like:
$(this).children('input:radio[name*=id_]').prop("checked", true)
The key is using name*=id_
This means select element whose name starts with id_. Isn't that what you wanted ?
$('#content').click(function(){
$(this).children('radio').attr('checked','checked')
})
building on Deif's solution this will toggle the checked status when clicking on the div
fiddle
<div id="content">
Some content
<input type="radio" id="radio1" value="test" />
</div>
<script type="text/javascript">
$('#content').click(function () {
var val = $(this).find('input:radio').prop('checked')?false:true;
$(this).find('input:radio').prop('checked', val);
});
</script>
Try with this:
$('div').click(function(){
if( $('div').find('input:checkbox').prop("checked") == true){
$('div').find('input:checkbox').prop("checked", false);
}
else{
$('div').find('input:checkbox').prop("checked", true);
}
});
LIVE DEMO

Javascript OnMouseOver and Out disable/re-enable item problem

I wanted to have some radio buttons that disabled when the mouse went over and enabled again when it went out (just for fun).
<form>
<input type="radio" name="rigged" onMouseOver="this.disabled=true" onMouseOut="this.disabled=false">
</form>
When the mouse goes on it it does what it should be when it goes back off the button wont re-enable. Also, how do I make it default to enable so that when you refresh the page it doesn't stay disabled.
Thanks in advance.
You could achieve the same effect by wrapping your radio buttons in a div tag and setting the onmouseover and onmouseout events.
<div id="container" onmouseout="this.disabled=false" onmouseover="this.disabled=true">
<input name="rigged" type="radio">
</div>
The above solution only works in IE, for a solution that works in FireFox do the following.
<script type="text/javascript">
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){
}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
*This javaScript function was borrowed from here: Enable or disable DIV tag and its inner controls using Javascript
<div id="container" onmouseover="toggleDisabled(this)" onmouseout="toggleDisabled(this)">
<input name="rigged" type="radio">
</div>
The inputs do not fire the mouseout events because they are disabled.
So you have to wrap it in a div and catch the div's events.
If you want pure javascript, use Phaedrus's example "toggleDisabled" script.
If you want jQuery and not-so-newbie friendly:
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
function toggleDisabled(d) {
var disable = d;
this.disableChildren = function() { $(this).children().each(function() { this.disabled = d; }); }
}
$("form .radios").hover(new toggleDisabled(true).disableChildren, new toggleDisabled(false).disableChildren);
});
</script>
</head>
<body>
<form>
<div class="radios">
<input type="radio" name="rigged" value="1"/> Item One<br />
<input type="radio" name="rigged" value="2"/> Item Two<br />
<input type="radio" name="rigged" value="3"/> Item Three<br />
<input type="radio" name="rigged" value="4"/> Item Four
</div>
</form>
</body>
</html>
I had a similar problem with wanting an image to expose, and then go regular when the mouse left the image. I was using jQuery and ended up hooking into mouseenter and mouseout, instead of the events you are using. You might want to try those.
$('#rigged').mouseenter(function() {
$(this).disabled = true;
}).mouseout(function() {
$(this).disabled = false;
});
Something like that.
Again, that's using jQuery.
(You'll have to give the input radio button the id 'rigged')
I think when it's becoming disabled, it's not going to fire any events.
You could try a few things.
On mouseover, make an invisible div overlay the radio box. This will make it impossible to use. Then on the mouseout of this invisible div, remove the div.
You could play with mouse x and y coords, and see if they overlay your radio elements. This isn't an optimal solution though.
Markup for the first, in jQuery, would go something like this
$('#rigged').after('<div id="overlay" style="display: none;"></div>'); // make this the size of the radio button and/or associated label (if present). also, maybe with absolute and relative positioning, make sure it will overlap the radio element
$('#rigged').bind('mouseover', function() {
$('#overlay').show();
});
$('#overlay').live('mouseout', function() {
$(this).hide();
});
You'll need to adapt this to work with multiple elements.

Categories