Check number of checkboxes depending on input - javascript

I have this following checkbox on my page
<div class="col-sm-6">
<label>Product Show</label>
<input type="checkbox" name="edprodShow" value="1" >Shape<br>
<input type="checkbox" name="edprodShow" value="2" >Color<br>
<input type="checkbox" name="edprodShow" value="3" >Design<br>
</div>
I would get values like 1 or 2 or 3(Externally, like in a JSON and i would extract that data). I want to set first check box if 1 and 1st and 2nd if two check box and all three if I get 3.(i.e) Get only shape for 1 and color + shape for 2 and color+shape+design for 3
I have tried many sources and ways but not finding the appropriate output how can I do it ?
Edit :
Code I tried to do
if(split_data[7].toString() === "1"){
$('#edprodShow').prop('checked', true);
}else if(split_data[7].toString() === "2"){
}else if(split_data[7].toString() === "3"){
$('#edprodShow').prop('checked', true);
}
where split_data[7] gives me 1,2 or 3

Try this.
Sample Json from server
var json = { edprodShow: [1,2,4]};
Code
var checker = function(data){
$("[name='edprodShow']").attr('checked', false);
$.each(data.edprodShow, function(i, value){
$("[name='edprodShow'][value='"+ value +"']").attr('checked', true);
}
}
Call the function
checker(json);

I got the solution dear ☺
you can do this by javascript :
$(document).ready(function(){
var $checkboxes = $('#devel-generate-content-form td input[type="checkbox"]');
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
// $('#count-checked-checkboxes').text(countCheckedCheckboxes);
$('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
})
Here you can see Demo

Related

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

How to make jQuery output only one value at a time from .each iteration

I have the following jQuery conditional code which I forked from CodePen. I have extended the code to use a select field as well and everything works fine except that when I use multiple values in data-cond-val jQuery outputs all of the values and only the last value is executed.
For example in the code provided below, when I use data-cond-val="no, maybe", only maybe value is used/executed on event change whether its used on a select option, input check or input radio.
Here's the HTML code
<div id="demo">
<select name="" data-cond="example1">
<option name="example1" data-cond="example1" value="yes">Yes</option>
<option name="example1" data-cond="example1" value="no">No</option>
<option name="example1" data-cond="example1" value="maybe">Maybe</option>
</select>
<div class="conditional" data-cond-opt="example1" data-cond-val="yes">
<label><input type="checkbox" name="example2" data-cond="example2"><span></span> Are you sure?</label>
<label><input type="checkbox" name="example3" data-cond="example3"><span></span> Really super sure?</label>
<div class="conditional" data-cond-opt="example2" data-cond-val="on">
Hooray!
</div>
<div class="conditional" data-cond-opt="example3" data-cond-val="on">
Don't get cocky!
</div>
</div>
<div class="conditional" data-cond-opt="example1" data-cond-val="no, maybe">
<p>
That's a shame. Will you change your mind?
</p>
<label><input type="radio" name="example4" data-cond="example4" value="yes"><span></span> Yes</label>
<label><input type="radio" name="example4" data-cond="example4" value="no"><span></span> No</label>
<label><input type="radio" name="example4" data-cond="example4" value="maybe"><span></span> Maybe</label>
<div class="conditional" data-cond-opt="example4" data-cond-val="yes">
Great!
</div>
<div class="conditional" data-cond-opt="example4" data-cond-val="no, maybe">
Maybe
</div>
</div>
</div>
<script>
$('.conditional').conditionize();
</script>
Here's the jQuery code
(function($) {
$.fn.conditionize = function(options){
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(listenTo, listenFor, $section) {
//checkbox and radio input types
if ($(listenTo + ":checked").val() == listenFor) {
$section.slideDown();
}
// select box
else if ($(listenTo + "option:selected").val() == listenFor) {
$section.slideDown();
} else {
$section.slideUp();
}
}
return this.each( function() {
var listenTo = "[data-cond=" + $(this).data('cond-opt') + "]";
// check if data att has multiple values
var multiVals = $(this).data('cond-val').split(' ').join(',');
var len = multiVals.indexOf(',');
// if data att has multiple values
if ( len > 0 ) {
// create an array from the values
var dataVals = $(this).data('cond-val').split(' ');
var listenFor;
$.each(dataVals, function (i, dataVal) {
listenFor = dataVals[i];
});
} else {
var listenFor = $(this).data('cond-val');
}
var $section = $(this);
//Set up event listener
$(listenTo).change(function() {
$.fn.showOrHide(listenTo, listenFor, $section);
});
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(listenTo, listenFor, $section);
});
}
}(jQuery));
The Question: How do I make jQuery to take each of the multiple values separately on each event change?
I'm not sure what am messing up in my syntax! I'll be glad if someone can help by showing me how to make it work.
Here is my CodePen forked DEMO - http://codepen.io/peter2015/pen/ZGoJom
In my demo above, When you select No and Maybe, they should both output the same section, but only Maybe option shows the section and No doesn't show anything when selected.
Not sure about this:var multiVals = $(this).data('cond-val').split(' ').join(',');.
A single split should be enough var multiVals = $(this).data('cond-val').split(',');
Or var multiVals = $(this).data('cond-val').replace(/ /g,'').split(','); if you wanna get rid of spaces in the attribute.
http://jsfiddle.net/pwjrev9v/

javascript modify variable

I have this:
var category = "3%2C16%2C6%2C10%2C1%2C19";
in witch category id are 3 16 6 10 1 19 and the %2C is the space between category.
What i want is here:
if (document.getElementById("3").checked = false) {
category = "16%2C6%2C10%2C1%2C19";
}
else {
category = "3%2C16%2C6%2C10%2C1%2C19";
}
I want to make this for all the checkbox that i have, but you can't deselect all the checkbox because the servers don't send you back any data.
This is for filtering the results
It would be easier to use an array, then convert it to this string representation, when needed.
var categories = [];
$('#category-form input').change(function () {
var id = $(this).attr('data-id'),
index = categories.indexOf(id);
if (this.checked && index === -1) {
categories.push(id);
} else if (!this.checked && index !== -1) {
categories.splice(index, 1);
}
});
You can see my working code in this fiddle.
(with multiple checkboxes, string representation, and at least one check)
Try
if (document.getElementById("3").checked === false) {
notice the extra double equals to do a typesafe check
or better still
if (!document.getElementById("3").checked) {
However, as you're using jQuery and you appear to be munging a string together from checked states, which is going to be really brittle with hardcoded strings so maybe something like:
var category = "";
$( "input:checked" ).each(function() {
category = $(this).id + "%2C";
};
Only calling that when you need the output e.g. button press.
As you are using jquery, you can listen to the change event for the checkboxes, then build the list each time one is checked or unchecked. To store the values you can either use the value attribute for the checkbox or add data- attributes.
Getting an array of values and joining them will avoid the trailing %2C.
var category = '';
(function($) {
// cache collection of checkboxes
var cboxes = $('input[type=checkbox]');
cboxes.on('change', function() {
// find the ticked boxes only, and make an array of their category values, then join the values by a space
category = $.makeArray(cboxes.filter(':checked').map(function() {
return $(this).data('category');
//return $(this).val(); // if you store them in value="3"
})).join('%2C');
// output for debug purpose
$('#categoryOutput').html("'" + category + "'");
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="c1" data-category="3" />
<input type="checkbox" id="c2" data-category="16" />
<input type="checkbox" id="c3" data-category="6" />
<input type="checkbox" id="c4" data-category="10" />
<input type="checkbox" id="c5" data-category="1" />
<input type="checkbox" id="c6" data-category="19" />
</form>
<div id="categoryOutput"></div>
Side Note: try to avoid starting element ids with numbers - it is technically invalid and can break things in some scenarios.

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.
I tried using this
<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked" />
and the javascript
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).checked=false;
}else{
document.getElementById(commen).checked=true;
}}​
It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.
Just do this:
<input type="checkbox" id="someid" checked="checked"/>
<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
if(document.getElementById('yourtextBox').value!=' ')
{
document.getElementById('checbox').checked=false;
}
Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield
//Function get called when you type each letter
function OnChangeTextField(){
//getting the length of your textbox
var myLength = $("#myTextbox").val().length;
if(myLength > 0){
$("#myCheckbox").attr("checked", false);
}else{
$("#myCheckbox").attr("checked", true);
}
}
<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
$("#box").prop("checked", this.value == "");
});
EDIT: You can also use jQuery
$("#comment").on("keyup blur", function() {
$("#box").prop("checked", this.value == "");
});
Try jQuery, This works for me...

Categories

Resources