Checkbox new state not reflecting - javascript

I have shown the problem at http://jsfiddle.net/7ZpCW/1/
I have implemented the code such that when I click on checkbox or text next to it, checkbox should be selected/de-selected depending upon its previous state.
The problem is when I click on text, though checkbox is getting checked but the alert message is getting executed only the number of times the previous checkboxes were selected.
While when I click on checkbox alert message is executed based on current state.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<span id="MYARRAYloader_collapse" class = "w195" style="display:block">
<div class="sp15"> </div>
<div class="lf fs12 lh15" style="padding-left:10px;">
<input type="checkbox" name="MYARRAY[]" id="MYARRAY0" value="ALL" checked class="chbx checkbox-selector1">
All
<br>
<input type="checkbox" name="MYARRAY[]" value="V" class="chbx checkbox-selector1">
Opt1
<span class="gray t11">(42)</span>
<br>
<input type="checkbox" name="MYARRAY[]" value="N" class="chbx checkbox-selector1">
Opt2
<span class="gray t11">(38)</span>
<br>
</div>
<div class="sp12"> </div>
</span>
<script>
$('.checkbox-selector').click(function() {
var chb = $(this).prev();
chb.click();
return false;
})
$('.checkbox-selector1').click(function() {
var chb , chb1 , action;
chb= $(this);
clusterName = chb.attr('name');
clusterVal = chb.attr('value');
var array = new Array();
$('input[name="'+clusterName+'"]:checked').each(function(i,el){
alert('Count Me');
chb1 = $(this);
if(clusterVal == 'ALL')
{
if(chb1.attr('value')!='ALL')
{
chb1.attr("checked","");
}
else
array.push($(el).val());
}
else
{
if(chb1.attr('value')=='ALL')
{
chb1.attr("checked","");
}
else
{
array.push($(el).val());
}
}
});
});
</script>

You are seriously convoluting this problem. You can make the text clickable simply by wrapping the checkbox and text in a label.
<label><input type="checkbox" /> This is some text</label>
<label><input type="checkbox" /> This is some text</label>
<label><input type="checkbox" /> This is some text</label>
jsFiddle: http://jsfiddle.net/7ZpCW/
​
You should really format your code like this to make it more semantic. But you won't. So you can fix your code by replacing this:
$('.checkbox-selector1').click( ... );
with this:
$('.checkbox-selector1').change( ... );
jsFiddle: http://jsfiddle.net/7ZpCW/2/

Related

On click radio button append value to div and remove from div when another radio button is clicked

Basically, I'm trying to append a radio button value to a div on click. This works as it should, but I can't seem to clear the div when clicking another radio button.
There should only ever be 1 piece of appended data within the div.
I tried to clear the div with innerHTML before appending the value but doesn't seem to work
$('input[type="radio"]').one('click', function () {
var getVal = $(this).val();
if ($('.selections').text().length < 0) {
console.log('less than');
}
else if ($('.selections').text().length > 0){
console.log('more than');
$('.selections').innerHTML = "";
$('.selections').append(getVal);
}
console.log(getVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Between £381K and £450K" id="between381">
Between £381K and £450K
</span>
</label>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Over £450K" id="over450">
Over £450K
</span>
</label>
</form>
<div class="selections">
</div>
innerHTML is used when using vanilla JS. You should use text() on jQuery referenced object. You also do not need to append here.
I also believe you have mistakenly used .one(), which should be .on().
$('input[type="radio"]').on('click', function () {
var getVal = $(this).val();
if ($('.selections').text().length < 0) {
//console.log('less than');
} else if ($('.selections').text().length > 0){
//console.log('more than');
$('.selections').text(getVal);
}
//console.log(getVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Between £381K and £450K" id="between381">
Between £381K and £450K
</span>
</label>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Over £450K" id="over450">
Over £450K
</span>
</label>
</form>
<div class="selections">
</div>

Add/Remove values to field from checkbox values in Javascript

I have two fields: one is a checkbox (built with Scala), one is an input/text field. I am trying to add and remove values from the checkbox to the input field. I am trying to take multiple values and string together with a comma.
Here are my HTML fields:
<div class="column column1">
#for(service <- servicesList) {
<label><input type="checkbox" name="selectServices" value=#service.name><span>#service.name</span></label>
}
</div>
<input name="services" id="services">
I am using jQuery in a tag to try to record the onchange event:
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('#selectServices');
$selectServices.change(function(){
for (var i = 0, n = this.length; i < n; i++) {
if (this[i].checked) {
$services.val($services.val() + this[i].value);
}
else {
$services.val($services.val().replace(this[i].value, ""));
}
}
});
});
However, it seems that this will not "fire" when checking and unchecking the checkbox. I do not receive any errors or messages, so I am guessing it is not working or the code is incorrect.
I appreciate the help!
Try this example, you don't have to search and replace all the time, just set a new value:
$(function() {
$('input[name=selectServices]').on('change', function() {
$('#services').val($('input[name=selectServices]:checked').map(function() {
return this.value;
}).get());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label>
<input type="checkbox" name="selectServices" value='1'><span>1</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='2'><span>2</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='3'><span>3</span>
</label>
<label>
<input type="checkbox" name="selectServices" value='4'><span>4</span>
</label>
</div>
<input name="services" id="services">
does the $(function() {} go into the $(document).ready(function(){}?
No, it is short-hand or equivalent for the same.
This is just an addition on #Halcyon his answer so you can create a nicer list, in stead of the replace method. #Halcyon is most definitely the correct answer why your check boxes aren't working. This is just a better solution handling values.
$(document).ready(function(){
var $services = $('#services');
var $selectServices = $('.selectServices');
$selectServices.change(function(){
updateServices();
});
function updateServices() {
var allVals = [];
$('.selectServices:checked').each(function() {
allVals.push($(this).val());
});
$services.val(allVals);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Foo"><span>Foo</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="Bar"><span>Bar</span></label>
<label><input class="selectServices" type="checkbox" name="selectServices[]" value="FooBar"><span>FooBar</span></label>
</div>
<input name="services" id="services">
$('#selectServices') selects by id, there are no elements with that id. Ids must be unique so you can't use them in this case. I also wouldn't recommend using name because input elements should have unique names. You can use class:
<label><input type="checkbox" class="selectServices" ...
Then use .selectServices in jQuery. And:
var $selectServices = $('.selectServices');
$selectServices.change(function(){
if (this.checked) {
$services.val($services.val() + this.value);
} else {
$services.val($services.val().replace(this.value, ""));
}
});
Your code will fire if you add ID's to your inputs:
<input type="checkbox" name="selectServices" id="selectServices" value="" />
and
<input name="services" id="services" type="text" />

jQuery checking radio box status and showing an element

I'm trying to show a div of another set of radio boxes but only depending on which radio button is first selected.
If option option one is selected, I would like condition one div to show and if option two is selected I would like condition two div to show.
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
if ($("id=[option-one]").is(":checked")) {
$('#visible-condition-one').show("slow");
} else if ($("id=[option-two]").is(":checked")) {
$('#visible-condition-two').show("slow");
};
});
<div id="always-visible">
<label class="control-label">Would you like option 1 or option 2</label><br>
<label class="radio-label"><input type="radio" id="option-one" name="option-info"> Option 1</label>
<label class="radio-label"><input type="radio" id="option-two" name="option-info"> Option 2</label>
</div>
<div id="condition-one">
<label class="control-label">If you pick option 1, you see this div</label><br>
<label class="radio-label"><input type="radio" id="option-three" name="option-info-group-two"> Option 3</label>
<label class="radio-label"><input type="radio" id="option-four" name="option-info-group-two"> Option 4</label>
</div>
<div id="condition-two">
<label class="control-label">If you pick option 2, you see this div</label><br>
<label class="radio-label"><input type="radio" id="option-five" name="option-info-group-three"> Option 5</label>
<label class="radio-label"><input type="radio" id="option-six" name="option-info-group-three"> Option 6</label>
</div>
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
$("#option-one").on("change", function() {
if($(this).is(":checked")) {
$('#condition-one').show("slow");
}
});
$("#option-two").on("change", function() {
if($(this).is(":checked")) {
$('#condition-two').show("slow");
}
});
});
In your code, the action must be taken on user input, in this case, a radio box. You must attach a 'change' event to your radio boxes and when user changes status, the callback function is triggered.
How about the following:
//Cache our deciding radio buttons
var $radio = $('#always-visible :radio'),
//An array of the available radio/div identifiers
ids = ['one', 'two'];
//Bind an event to your deciding radio buttons
$radio.change(function(){
//That will loop through your radio buttons
$.each(ids, function(_, n){
//See if this one is checked
var checked = $('#option-' + n).prop('checked');
//If so, show the relevant block, otherwise hide it
$('#condition-' + n).toggle(checked);
});
//Trigger the event on page load
}).change();
JSFiddle
i just did something similar(working)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
$(".radio-label").on("change", function() {
if ($('.radio-label#1').is(':checked')) { // if the radiolabel of id=1 is checked
$('#condition-one').show("slow"); //show condition one
$('#condition-two').hide();
} else if ($(".radio-label#2").is(":checked")) {
$('#condition-two').show("slow");
$('#condition-one').hide("slow");
}
});
});
</script>
</head>
<body>
<input type="radio" class="radio-label" id="1" name="option-info"></input>
<input type="radio" class="radio-label" id="2" name="option-info"></input>
<div id="condition-one">
test1
</div>
<div id="condition-two">
test2
</div>
</body>

Control Radio Buttons with a Checkbox

I'm using a CMS that hides form elements behind tags, because of some system quirks I've had to set up a checkbox that controls the radio buttons so if the checkbox is ticked the "yes" radio button is selected if not the "no" is selected. I also want the radio buttons to have option "no" checked by default but I don't have control over the line of code for the radio buttons.
I found some Javascript that does a small part of this but I want to integrate it into the jQuery that displays and hides content when the box is ticked.
Here's what I have so far:
$('#checkbox1').change(function() {
$('#content1').toggle("slow");
});
The Javascript I have is this:
function ticked(){
var ischecked = document.getElementById("checkbox").checked;
var collection = document.getElementById("hideradio").getElementsByTagName('INPUT');
if(ischecked){collection[0].checked = true;}else{collection[0].checked = false;}
}
Can you please help write a version of the Javascript but integrate with my jQuery?
Thanks,
You can try this, I assume your html as like this.
<input type="checkbox" id="checkbox1" /> Check Box
<div id="content1" >
Some Content <br />
Some Content <br />
Some Content <br />
Some Content
</div>
<div id="hideradio">
<input type="radio" name="rgroup" value="yes" /> Yes
<input type="radio" name="rgroup" value="no" /> No
</div>
JQuery
$(function(){
$('#hideradio input[type=radio][value=no]').attr('checked',true);
$('#content1').hide();
});
$('#checkbox1').on('change', function() {
$('#content1').toggle("slow");
var self = this;
if(self.checked)
$('#hideradio input[type=radio][value=yes]').attr('checked',true);
else
$('#hideradio input[type=radio][value=no]').attr('checked',true);
});
A Quick DEMO
Try this code
​
$(function(){
$('#checkbox1').on('click' , function() {
var isChecked = $(this).is(':checked');
if(isChecked){
$('#radio1').attr('checked' , true);
$('#content1').toggle("slow");
}
else{
$('#radio1').attr('checked' , false);
}
});
});​
Check [FIDDLE]
If I don't understand correctly then let me know.
I don't know your HTML code so I provide one
<form>
<input type="checkbox" name="test_ck" id="test_ck" />
<br/>
<input type="radio" name="test_radio" id="test_radio" />
</form>
<div id="content"> A content !!! </div>
and javascript jquery
$(function(){
$("#test_ck").on("change", function(){
$("#test_radio").prop("checked", $(this).is(":checked"));
$("#content").toggle("slow");
});
});
Example -> jsfiddle
UPDATED jsfiddle
http://jsfiddle.net/6wQxw/2/
jsfiddle
$(document).on('change', '#checkbox', function() { toggle(this); });
var toggle = function(obj) {
var checked = $(obj || '#checkbox').is(':checked');
$(':radio[value=no]').prop('checked', !checked);
$(':radio[value=yes]').prop('checked', checked);
$('#content').toggle(checked);
}
toggle();
This is a pure JavaScript solution, no need to use jQuery:
<body>
<label for="a">Male</label>
<input type="radio" id="a">
<br/>
<label for="b">Female</label>
<input type="radio" id="b">
<script type="text/javascript">
var nodes = document.querySelectorAll("input[type=radio]");// get elements
var arr = Array.prototype.slice.call(nodes); // convert nodes to array for use in forEach
arr.forEach(function(obj){
obj.addEventListener("change",function(e){
arr.forEach(function(obj){
obj.checked = false;//make other radio false
});
this.checked = true;// make this radio ture
});
});
</script>
</body>

hiding div based on unchecking checkboxes

I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox

Categories