How to Linking two checkbox Array together JavaScript - javascript

I want to connect two checkbox together , so that When clicked main checkbox then checked its child.
with below code I retrieve data from database:
while($row = mysqli_fetch_array($query_show_all_receivers))
{
$option .= ' <pre> <input onclick="func()" type="checkbox" class="checkbox-inline" name="check_Main[]" value = "'.$row['user_username'].'">'. row['user_username'].'
<input type="checkbox" class="checkbox-inline" name="check_child[]" id="check_child[]" value = "'.$row['user_mobile'].'"> '.$row['user_mobile'].'
</pre>';
}
and show the items:
<?php echo $option; ?>
How possible if Main box checked then will checked its child too.
Its my JavaScript code but I think have to use via loop:
It just work first child not others.
<script>
function func()
{
document.getElementById('check_child[]').checked = true ;
}
</script>
Thanks for your consideration.

IDs should be unique. In your case, you could use the query's row number in order to build an unique ID with a common prefix, it's generally good practice.
Here's a CodePen that works
https://codepen.io/Raven0us/pen/abvJqLP
<label for="checkbox-parent">Parent</label>
<input type="checkbox" onchange="func(event)" name="checkbox_parent" id="checkbox-parent">
<div>
<label for="checkbox-child-1">Child 1</label>
<input type="checkbox" name="checkbox_child_1" id="checkbox-child-1" class="checkbox-child">
<label for="checkbox-child-2">Child 2</label>
<input type="checkbox" name="checkbox_child_2" id="checkbox-child-2" class="checkbox-child">
<label for="checkbox-child-3">Child 3</label>
<input type="checkbox" name="checkbox_child_3" id="checkbox-child-3" class="checkbox-child">
</div>
I changed onclick to onchange, some people prefer click, mostly for legacy reasons (I think?), but I wouldn't. Moreover, I passed the actual event to the function, so it's available if we want to check stuff about it.
function func(event) {
document.querySelectorAll('.checkbox-child').forEach(checkboxChild => {
checkboxChild.checked = event.target.checked;
})
}
The handler gets all the related checkboxes, based on a common class which can repeat, unlike IDs, and loop through the returned NodeList and update their value based on parent checkbox value. So, checking or unchecking parent will update children as well.

Parent and child checkboxes
with above script by #CoolEsh I could solve this problem and update with loop to specific every parents and their children :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"> </script>
<script>
var checkboxHandlerObj = {
init: function() {
$('#customerServices input:checkbox[class="parent"]').click(checkboxHandlerObj.parentClicked);
$('#customerServices input:checkbox[class^="parent-"]').click(checkboxHandlerObj.childClicked);
},
parentClicked: function() {
if ($(this).attr('checked')) {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').attr('checked', 'checked');
} else {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').removeAttr('checked');
}
},
childClicked: function() {
var temp = $(this).attr('class').split('-');
var parentId = temp[1];
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
} else {
var atLeastOneEnabled = false;
$('#customerServices input:checkbox[class="' + $(this).attr('class') + '"]').each(function() {
if ($(this).attr('checked')) {
atLeastOneEnabled = true;
}
});
if (!atLeastOneEnabled) {
$('#' + parentId).removeAttr('checked');
}
}
}
};
checkboxHandlerObj.init();
</script>
and PHP loop:
<div id="customerServices">
<?php
$x = 1;
$id = 1;
while($x <= 5) {
$x++;
$option .= '<input id="'.$id.'" class="parent" type="checkbox" name="check_Main[]" value = "1">1
<input type="checkbox" name="check_child[]" class="parent-'.$id.'" value = "2"> 2 <br> ';
$id++ ;
}
echo $option;
?>
</div>
It worked with unique Id. Thanks For #Ravenous and #evolutionxbox

Related

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

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"

Verify checked checkbox javascript

I'm trying to update in "real time" if I check and uncheck in a list of checkboxs.
With this code:
window.onload = function () {
var input = document.getElementById('listTaxi');
function check() {
var a = input.checked ? "checked" : "not checked";
console.log(a);
}
input.onchange = check;
check();
}
I can do this for one checkbox, but how can I make for multiple checkboxs? A list(div) of checkboxs?
Thanks!!
Assign a class on all checkboxes you want to check if checked or not.
Checkboxes
<input type="checkbox" class="checkboxes" id="checkbox1"/>
<input type="checkbox" class="checkboxes" id="checkbox2"/>
<input type="checkbox" class="checkboxes" id="checkbox3"/>
<input type="checkbox" class="checkboxes" id="checkbox4"/>
Pure Javascript
// getting all checkboxes
var checkboxes = document.getElementsByClassName('checkboxes');
// go through all checkboxes
for(var i = 0; i <= checkboxes.length - 1; i++){
checkboxes[i].onchange = function(e){
alert('Element with id ' + e.target.getAttribute('id') + ' is checked ' +e.target.checked);
}
}
Codepen http://codepen.io/todorutandrei/pen/rLBQOX
Or you can use JQUERY - is it more simple
$('.checkboxes').change(function(){
var item = $(this);
alert('Element with id ' + item.attr('id') + ' is ' + item.is(':checked'));
})
Codepen http://codepen.io/todorutandrei/pen/MegzwR
make them all the same class or give the all the same custom attribute
$(".classname")
$("input[name='customName'])
Jquery will then select all with those
$("#id").change(function() {//if using class name or custom attr loop through the return elements and use a function below to handle the cases
if($(this).is(":checked")) {
//code if checked
}
else{
//code if not checked
}
});

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

I'm trying to assign a variable to check-boxes and adding that variable to an output variable when it's checked

I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.

Categories

Resources