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
I am trying to convert checkbox into radio button which is working partially , but not deselecting previous selected radio button.I am looking solution to show one button at a time as a selected.
var layers = {
'Esri_WorldImagery': Esri_WorldImagery.addTo(this.baseMap),
'World_Topo_Map': World_Topo_Map//.addTo(this.baseMap)
};
var layerHtml = '<ul class="fa-ul">';
for (var key in layers) {
if (layers.hasOwnProperty(key)) {
var state = this.baseMap.hasLayer(layers[key]) ? 'checked="checked"' : '';
//layerHtml += '<li><label><input type="checkbox" ' + state + ' value="' + key + '" >' + key + '</label>';
layerHtml += '<li><label><input type="radio" ' + state + ' value="' + key + '" >' + key + '</label>';
}
}
layerHtml += '</ul>';
var widget = $('<div id="layer-control" class="sidebar-widget">' + layerHtml + '</div>');
widget.on('click', 'input[type="radio"]', function (e) {
var was_Active = $(this).prop('checked');
var value = $(this).val();
if (was_Active) {
layers[value].addTo(self.baseMap);
}
else {
self.baseMap.removeLayer(layers[value]);
}
});
First, regarding the current code with radio elements, as #Aswin Ramesh has told you, yo should add the name attribute. From MDN:
A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.
Besides the shape (circle vs square) that's the only difference between the radio and checkbox elements. So consider that checkboxes that behave like radio buttons might be confusing for the user.
That said, if you really want to replicate that functionality on checkboxes, use JavaScript to deselect all the elements but the one which raised the click event.
$('#checkboxes').on('click', ':checkbox', function(e) {
$('#checkboxes :checkbox').each(function() {
if (this != e.target)
$(this).prop('checked', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="radios">
<input type="radio" name="rOptions" value="radio1" checked>
<input type="radio" name="rOptions" value="radio2">
<input type="radio" name="rOptions" value="radio3">
</div>
<div id="checkboxes">
<input type="checkbox" value="checkbox1" checked>
<input type="checkbox" value="checkbox2">
<input type="checkbox" value="checkbox3">
</div>
Note: you forgot to close the <li> tags.
I have multiple checkboxes customized by CSS. With the function only one can be selected at the same time, like radios. I use toggle in onchange event to affect all changes in checkboxes.
<input type="checkbox" name="plus" onchange="toggleByClass('masinfo1');" class="plusultra" id="checkmas1" value=""><label for="checkmas1"><span></span></label>
<input type="checkbox" name="plus" onchange="toggleByClass('masinfo2');" class="plusultra" id="checkmas2" value=""><label for="checkmas2"><span></span></label>
<input type="checkbox" name="plus" onchange="toggleByClass('masinfo3');" class="plusultra" id="checkmas3" value=""><label for="checkmas3"><span></span></label>
The divs:
<div class="masinfo1 divmasinfo" id="masinfo1"><p class="infop">1111 11111 111111 11111 1111 1111</p></div>
<div class="masinfo2 divmasinfo" id="masinfo2"><p class="infop">222222 222 222 22222222222</p></div>
<div class="masinfo3 divmasinfo" id="masinfo3"><p class="infop">33333 3333 333 3333 33</p></div>
The function toggle:
function toggleByClass(className) {
$("."+className).toggle();}
The function only one checked:
`$`( document ).ready(function() {
`$`(function() {
$("input:checkbox").on('click', function() {
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
});
});
The problem is onchange don't close the div when I click another checkbox, and I don't understand why. Can anybody help me?
You should hide the displayed divs before toggling. Please try with this toggleByClass function. It hides the already displayed divs before toggling.
function toggleByClass(className) {
$(".divmasinfo").each(function(index, item) {
if(!$(item).is("." + className)) {
$(item).hide();
}
});
$("." + className).toggle();
}
I create a input list with this function:
function buildHTMLinputfields(data, form_id){
var row$ = '';
for(var i = 0; i < data.length; i++){
row$ = " <label for='check1'>" + data[i].Attribute_Name + "<input data-guid='" + data[i].GUID + "' type='checkbox' name='" + data[i].Name + "' value='" + data[i].Name + "' id='check1' checked='checked'> " + data[i].Name + " </label><br>";
$(form_id).append(row$);
}
}
Output on my website:
<label for="check1">
Adressierung
<input type="checkbox" checked="checked" id="check1" value="volladressierbar" name="volladressierbar" data-guid="17caabea-c313-48c9-b965-739ef8d09a1f"> volladressierbar
</label><br>
<label for="check1">
Adressierung
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" name="teiladressierbar" data-guid="d4419b55-3bb1-4efd-8f1c-f2ae3ed46988"> teiladressierbar
</label><br>
<label for="check1">
Empfänger
<input type="checkbox" checked="checked" id="check1" value="privat" name="privat" data-guid="c14733e5-64f1-4141-a366-a9fd5dfa0aff"> privat
</label><br>
<label for="check1">Empfänger<input type="checkbox" checked="checked" id="check1" value="Gewerbe" name="Gewerbe" data-guid="6febb58c-8c1d-4f84-a647-5409107c2002"> Gewerbe
</label><br>
So good... I've some input checkboxen.
Now I want to get a alert or console.log output if I click on one checkbox.
This is my function for it (Here is the problem I think):
function test(){
$('body').on('click', 'input', function(){
var text = '';
text = $('#check1').text(); // empty???
console.log(text); // Output -> (an empty string)
});
}
The console says me: (an empty string)
I search a whole time in Google and SO but I can't find my issue.
I try this (without success):
Click event on dynamically generated list items using jquery
For your information (I think it is important) - I initialize the functions here:
function ip_get_order_filters(){
var cookie_value_bearer = getCookie('ip_token');
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', "Bearer " + cookie_value_bearer);
};
$.ajax({
crossdomain: true,
url: 'https://testapi.***.de/***',
type: 'GET',
contentType: 'application/x-www-form-urlencoded',
beforeSend: setHeader,
dataType: 'json',
success: function (data) {
buildHTMLinputfields(data, '#filterform'); //generate the input list
test();
}
});
}
Use val instead of text and id must be unique. You can do it like following without concern of id using this.
$('body').on('click', 'input', function(){
var text = '';
text = $(this).val();
console.log(text);
});
So, instead of having a form in the HTML, I decided to create the form on fly and append it to another element (in my case a <section>, but that will be an option in the near future).
I'm using this method:
var formWrapper = ['<div class="content-login">','</div>'];
var form = [
'<form name="login-form" class="login-form" method="post" action="#">',
'<fieldset class="login-fields">',
'<fieldset class="username-wrapper">',
'<label for="username" class="user-img"><img src="assets/gfx/user.png" alt="Username" /></label>',
'<input type="text" name="username" class="username" placeholder="Username" value="" autocomplete="off" />',
'</fieldset>',
'<fieldset class="password-wrapper">',
'<label for="password" class="pass-img"><img src="assets/gfx/password.png" alt="Password" /></label>',
'<input type="password" name="password" class="password" placeholder="Password" value="" autocomplete="off" />',
'</fieldset>',
'<fieldset class="login-wrapper">',
'<button type="submit" name="login" class="login">Login</button>',
'</fieldset>',
'</fieldset>',
'</form>'
];
setTimeout(function () {
$(formWrapper.join('')).appendTo('section').hide();
$(form.join('')).appendTo('.content-login');
$('.content-login').fadeIn('slow');
}, 1500);
This way I have a nice fade in effect and it will give me the opportunity to change whatever I want after I fully develop it.
But my question is in fact the following: I have a form, so of course I will use Ajax to submit it, and I already have the script for that. The thing is now, when I click on the button, the .click event does not occur, it only takes me to the default action of the form which is "#" in my case. Why is that ?
Here is the other part of the script, for a better understanding :
$('.login-form .login').click(function(){
if($('input.username').val() == "" || $('input.password').val() == "")
{
console.log('Please enter Username & Password');
$('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
return false;
}
else {
$('.login-fields').fadeOut();
$('.login-form').spin("login", "#ffffff");
$.ajax
({
type: 'POST',
url: 'assets/class/login/process.php',
dataType: 'json',
data:
{
username: $('input.username').val(),
password: $('input.password').val()
},
success:function(data)
{
if(!(data.lockdown == true)) {
if(data.error === true) {
console.log(data.message);
$('.login-form').spin(false);
$('.login-fields').fadeIn();
$('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
}
else {
console.log(data.message);
$('.login-form').spin(false);
$('.login-fields').fadeIn();
$('.content-login').fadeOut();
var structure = [
'<div class="after-login">',
'<div class="inside">',
'<div class="row-one">',
'<h1>',data.message,'</h1>',
'</div>',
'<div class="row-two">',
'<a class="cancel" href="',links.cancel,'?logout">Cancel</a>',
'<a class="continue" href="',links.proceed,'">Continue</a>',
'</div>',
'</div>',
'</div>'
];
setTimeout(function () {
$(structure.join('')).appendTo('section').fadeIn('slow');
}, 1500);
}
}
else {
console.log(data.message);
$('.login-form').spin(false);
$('.content-login').fadeOut();
var structure = [
'<div class="system-lockdown">',
'<div class="inside">',
'<div class="row-one">',
'<h1>',data.message,'</h1>',
'</div>',
'<div class="row-two">',
'<a class="back" href="',links.goback,'">Back</a>',
'</div>',
'</div>',
'</div>'
];
setTimeout(function () {
$(structure.join('')).appendTo('section').fadeIn('slow');
}, 1500);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown)
{
console.log('A PHP error triggered this, check your PHP log file for more information');
}
});
return false;
}
});
$.click() will only work on elements that have been created before the handler was created.
Instead, use $.live() instead:
$('.login-form .login').live('click', function() {
// Your code
});
If you're using jQuery 1.7 or above, you can also use $.on() in a similar way:
$('.login-form .login').on('click', function() {
// Your code
});
The preferred way to handle events with dynamically added content is with on()—or delegate, since you're on jQuery 1.6
$(document).delegate('.login-form .login', 'click', function(){
});
Note that this will listen to every single click anywhere in your document. Ideally you'd like to identify some more narrow container from which all clicks will come, and listen to that. So if all these clicks will be coming from your section, you'd do this
$("section").delegate('.login-form .login', 'click', function(){
});