I have a checkbox. I need to filter by choosing them.
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india"/>India</label>
</div>
</div>
Below the div which should be filtered
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan</h2>
</div>
</div>
Below my script. But I cannot take a value of checkboxes. How should I do. Is there some methods except of a lot of if?
<script>
var choose = document.getElementsByClassName('chechbox');
const div = document.getElementsByClassName('result');
if (choose.value){
result.style.display = "block";
}
</script>
Please, help me to write the script
Both choose and div are list of Elements, not a single Element. You need to iterate them.
var checkboxes = document.getElementsByClassName('checkbox');
Array.from( checkboxes ).forEach( function( checkBox ){
///rest of the code
})
Demo
var checkboxes = document.querySelectorAll('[type="checkbox"]');
var fnDisplayDivs = () => {
Array.from(checkboxes).forEach(function(checkBox) {
var div = document.querySelector("." + checkBox.getAttribute("rel"));
if (checkBox.checked) {
div.style.display = "block";
} else {
div.style.display = "none";
}
})
};
Array.from(checkboxes).forEach(function(checkBox) {
checkBox.addEventListener( "change", function(){
fnDisplayDivs();
})
});
fnDisplayDivs();
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india"/>India</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan</h2>
</div>
</div>
The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
So you have to use element` index in order to access it. For instance,
if (choose[0].value){
result.style.display = "block";
}
I suppose you want to display div based on checkbox value. Also, you have to bind a change event handler to your checkboxes.
function change(){
var checkboxes = document.getElementsByClassName('checkbox');
var chekboxInputs = Array.from(checkboxes).map(a => a.querySelector('input'));
var allAreUnselected = chekboxInputs.every(function(elem){
return !elem.checked;
});
if(allAreUnselected){
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = 'block';
});
});
}
else {
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = input.checked ? 'block' : 'none';
});
});
}
}
change();
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada" onchange="change()"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china" onchange="change()"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa" onchange="change()"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india" onchange="change()"/>India</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan</h2>
</div>
<div class="india">
<h1>India</h1>
<h2>Alan2</h2>
</div>
</div>
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
if($(this).is(':checked')){ $('.'+$(this).attr('rel')).css('display','block');
}else{
$('.'+$(this).attr('rel')).css('display','none');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china"/>China</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="usa"/>USA</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="india"/>India</label>
</div>
</div>
<div class="result">
<div class="canada" style="display:none">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china" style="display:none">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="usa" style="display:none">
<h1>USA</h1>
<h2>Micheal</h2>
</div>
<div class="india" style="display:none">
<h1>India</h1>
<h2>Alan</h2>
</div>
</div>
Related
Here I want to add multiple switch buttons on the same page. I had added but querySelector is not working. Can anyone guide me on what might be the reason the switch is not working.
allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
allOnOffButtons.forEach(button => {
button.addEventListener('click', handleVisibility);
})
function handleVisibility(e) {
// check if the button was on or off
const clickedButtonId = e.srcElement.id;
const clickedinnerDiv = e.srcElement.closest(".case-inner-info").querySelector(".inner_div");
// find all divs inside the given inner_div
const allDivsInsideInnerDiv = clickedinnerDiv.querySelectorAll("div");
// check if they should be shown or hidden
allDivsInsideInnerDiv.forEach(div => {
if (div.id === clickedButtonId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" id="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" id="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<input type="radio" class="switch-input" id="on" checked>
<label for="on" class="switch-label switch-label-on">On</label>
<input type="radio" class="switch-input" id="off">
<label for="off" class="switch-label switch-label-off">Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" id="on1">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" id="off1">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<input type="radio" class="switch-input" id="on1" checked>
<label for="on1" class="switch-label switch-label-on">On</label>
<input type="radio" class="switch-input" id="off1">
<label for="off1" class="switch-label switch-label-off">Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
The jQuery import wasn't needed, so I removed it. You can easily get the relative paths to switch your display using data-attributes (I used data-ref) instead of IDs with:
e.target.closest('.case-inner-info')
.querySelectorAll('.inner_div [data-ref]')
.forEach(i => i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
const handleVisibility = (e) => {
e.target.closest('.case-inner-info').querySelectorAll('.inner_div [data-ref]').forEach(i => i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
}
const allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
allOnOffButtons.forEach(button => {
button.addEventListener('click', handleVisibility);
})
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" data-ref="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" data-ref="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<label class="switch-label switch-label-on">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
On</label>
<label class="switch-label switch-label-off">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" data-ref="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" data-ref="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<label class="switch-label switch-label-on">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
On</label>
<label class="switch-label switch-label-off">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
There is a solution here but I have a problem . when check box is checked and unchecked i wanted it to be empty but it results in
{
"category": []
}
but I wanted it to empty {}
const array = {};
$('[name^="pgggo-"]').on('click', function() {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
const id = attr.split('[')[0];
const checked = $(this).prop('checked');
array[taxonomy] = array[taxonomy] || [];
const index = array[taxonomy].indexOf(id);
index == -1 ? array[taxonomy].push(id) : array[taxonomy].splice(index, 1);
console.log(array);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pgggo-list-taxon">
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-56[]">
<div class="icon-box">
<div name="development">Development</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-14[]">
<div class="icon-box">
<div name="food">Food (category)</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-home-sep-14[]">
<div class="icon-box">
<div name="food">Food (home)</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-8[]">
<div class="icon-box">
<div name="medical">Medical</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-1[]">
<div class="icon-box">
<div name="uncategorized">Uncategorized</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-2[]">
<div class="icon-box">
<div name="wordpress">WordPress</div>
</div>
</label>
</li>
</div>
Please help
well there should be nothing wrong with that. But still if you want to remove the related property, you can use delete object.property to delete it when all the items have been unchecked as following
const array = {};
$('[name^="pgggo-"]').on('click', function() {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
const id = attr.split('[')[0];
const checked = $(this).prop('checked');
array[taxonomy] = array[taxonomy] || [];
const index = array[taxonomy].indexOf(id);
index == -1 ? array[taxonomy].push(id) : array[taxonomy].splice(index, 1);
if(array[taxonomy].length == 0){
delete array[taxonomy];
}
console.log(array)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pgggo-list-taxon">
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-56[]">
<div class="icon-box">
<div name="development">Development</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-14[]">
<div class="icon-box">
<div name="food">Food (category)</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-home-sep-14[]">
<div class="icon-box">
<div name="food">Food (home)</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-8[]">
<div class="icon-box">
<div name="medical">Medical</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-1[]">
<div class="icon-box">
<div name="uncategorized">Uncategorized</div>
</div>
</label>
</li>
<li>
<label>
<input type="checkbox" name="pgggo-category-sep-2[]">
<div class="icon-box">
<div name="wordpress">WordPress</div>
</div>
</label>
</li>
</div>
$('input').on('change', function() {
var self = $(this);
if (self.is(':checked')) {
self.closest('.label-wrap').clone().addClass("clone")
.appendTo("header");
self.closest('.label-wrap').find('label').addClass("is-checked");
} else {
$('header label[for="' + self.attr('id') + '"]').replaceWith('');
self.closest('.wrap').find('.clone').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6">
<header></header>
</div>
<form class="col-md-6">
<div class="wrap">
<div class="label-wrap">
<label for="one">Checkbox 1</label>
<input id="one" type="checkbox" />
</div>
</div>
<div class="wrap">
<div class="label-wrap">
<label for="two">Checkbox 2</label>
<input id="two" type="checkbox" />
</div>
</div>
<div class="wrap">
<div class="label-wrap">
<label for="three">Checkbox 3</label>
<input id="three" type="checkbox" />
</div>
</div>
</form>
</div>
here what i want to achieve is on checking box1 it has to create a clone element (clonedcheckbox1) and on unchecking cloned checkbox(clonedcheckbox1) hide that checkbox and uncheck parent checkbox(checkbox1)
[.]checkbox1 [.]clonedcheckbox1
[]checkbox2
[.]checkbox3 [.]clonedcheckbox3
You can delegate a change event so that your binding can be done onready to remove the clone and uncheck the original when the clone is unchecked:
$('.checkbox').on('change', function() {
var $this = $(this);
var $parent = $this.parent();
if (this.checked) {
// if checked clone without events and append
$parent.after($parent.clone().addClass('clone'));
} else {
// otherwise remove clone
$parent.next('.clone').remove();
}
});
$('.wrap').on('change', '.clone .checkbox', function() { // delegate your event for dynamically added elements
// can only be unchecked
var $this = $(this);
$this.closest('.wrap').find('.checkbox').prop('checked', false); // use prop to uncheck original
$this.parent().remove(); // remove clone
});
.wrap {
display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6">
<header></header>
</div>
<form class="col-md-6">
<div class="wrap">
<div class="label-wrap">
<label for="one">Checkbox 1</label>
<input id="one" type="checkbox" class="checkbox" />
</div>
</div>
<div class="wrap">
<div class="label-wrap">
<label for="two">Checkbox 2</label>
<input id="two" type="checkbox" class="checkbox" />
</div>
</div>
<div class="wrap">
<div class="label-wrap">
<label for="three">Checkbox 3</label>
<input id="three" type="checkbox" class="checkbox" />
</div>
</div>
</form>
I have a div with some radio buttons, and the input names are cty_1. If i add more div the input names inside that divs should become cty_2, cty_3, etc.respectively.
Here's my code:
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
If another div is added, i want that like
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_2" id="3" value="phone">
<label for="3">phone</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_2" id="4" value="computer">
<label for="4">computer</label>
</div>
</div>
NB: i don't know javascript.
If you're using jQuery then this is pretty easy. Using the following code, every time you click "Go" a new category element will be appended and the name and id attributes will increment:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div class="container">
<btn class="btn btn-primary">Go</btn>
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
</div>
</body>
<script>
$('.btn-primary').on('click',function(){
var idx = parseInt($('.category').last().index())+1;
$('.category')
.last()
.clone()
.find('input[type=radio]')
.each(function(index){
$(this)
.attr('name','cty_' + idx)
.attr('id','cty_' + idx + "_" + index)
.parent()
.find('label')
.attr('for','cty_' + idx + "_" + index)
.end()
})
.end()
.insertAfter($('.category').last());
});
</script>
Try this: updated fiddle
//Html
<div id="divMain">
</div>
//jQuery Code
var valuesArr=["car","bike","truck","Test4","Test5"];
var cityCounter=1;
var idCounter=1;
var addCategoryFlag=false;
function CallHtml(){
var html="";
for(var i=0;i<valuesArr.length;i++){
if(idCounter%2!=0){
html+='<div class="category">';
}
else{
addCategoryFlag=true;
}
html+='<div class="col-md-6">';
html+=' <input type="radio" name="cty_'+cityCounter+'" id="'+idCounter+'" value="'+valuesArr[i]+'">';
html+=' <label for="'+idCounter+'">'+valuesArr[i]+'</label>';
html+='</div>';
if(addCategoryFlag){
html+='</div>';
addCategoryFlag=false;
cityCounter++;
}
idCounter++;
}
$("#divMain").html(html);
}
CallHtml();
Hi I have multiple checkboxes of similar kind. I am applying javascript on the checkbox to show hidden fields. I have created a js code which works for a single checkbox, I want to apply a code that will work for all checkboxes.
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox" type="checkbox">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox" type="checkbox">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
JS Code :-
var checkbox = document.getElementById('checkbox');
var box = document.getElementById('box');
checkbox.onclick = function() {
console.log(this);
if (this.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
};
Now the thing is i can make individual javascript for all checkboxes but that will contain numerous js code, I want that a single javascript function can unhide the elements from every checkbox when clicked. A single js code should work for all checkboxes. Kindly please provide a way of doing it with plain javascript or jquery.
Try this
on your check box's onchange event call function onchange="showHiddenField(this)"
and function is like
function showHiddenField(currentObject) {
var inputDiv = $(currentObject).parent().next();
if ($(currentObject).is(":checked")) {
$(inputDiv).show().focus();
}
else {
$(inputDiv).hide();
}
}
Use javascript function to make it.
function toggleFields(boxId, checkboxId) {
var checkbox = document.getElementById(checkboxId);
var box = document.getElementById(boxId);
checkbox.onclick = function() {
console.log(this);
if (this.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
};
}
toggleFields('box1', 'checkbox1');
toggleFields('box2', 'checkbox2');
<link href="//cdn.bootcss.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<!--<input id="checkbox" type="checkbox">-->
<input id="checkbox1" type="checkbox">
</div>
<!--<div class="col-md-4" id="box" style="display: none;">-->
<div class="col-md-4" id="box1" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<!--<input id="checkbox" type="checkbox">-->
<input id="checkbox2" type="checkbox">
</div>
<!--<div class="col-md-4" id="box" style="display: none;">-->
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
Okay this is how this works, each checkbox will have the id of its box as a class, so that when ever that checkbox is clicked, we will use its class to make its box visible. This will work even if you have 1000 checkboxes
var checkbox = document.querySelectorAll("#check1, #check2");
for (i = 0; i < checkbox.length; i++) {
checkbox[i].onclick = function() {
if (this.checked) {
document.getElementById(this.getAttribute('class')).style['display'] = 'block';
} else {
document.getElementById(this.getAttribute('class')).style['display'] = 'none';
}
};
}
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check1" type="checkbox" class="box">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check2" type="checkbox" class="box2">
</div>
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
Yes you can do this. Solution in below code. i did this using JQuery.
$('input[type="checkbox"]').click(function(){
console.log(this);
// $(this).parent().next().css('display','block');
$(this).parent().next().toggle('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input name="chkbox" type="checkbox">
</div>
<div class="col-md-4" data-box="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input name="chkbox" type="checkbox">
</div>
<div class="col-md-4" data-box="box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
First Please note down in your mind "id" is only apply on a single elemnt on each page for multiple element you can apply a "class"
id="checkbox" replace with class="checkbox"
in Jquery
$(document).ready(function(){
$(".checkbox").change(function(){
if($(this).prop("checked")){
$(this).parents(".row").find(".box").show();
}else{
$(this).parents(".row").find(".box").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input class="checkbox" type="checkbox">
</div>
<div class="col-md-4 box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input class="checkbox" type="checkbox">
</div>
<div class="col-md-4 box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
You can use querySelectorAll("[type='checkbox']") to select all checkbox and iterate through the elements using for loop.
Note : The id should be unique for each element.
var checkbox = document.querySelectorAll("[type='checkbox']");
for (i = 0; i < checkbox.length; i++) {
checkbox[i].onclick = function() {
if (this.checked) {
document.getElementById(this.getAttribute('class')).style['display'] = 'block';
} else {
document.getElementById(this.getAttribute('class')).style['display'] = 'none';
}
};
}
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check1" type="checkbox" class="box">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check2" type="checkbox" class="box2">
</div>
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
The most narrowed (static) suggestion from your code:
$(document).ready(function() {
$('input[type=checkbox]').change(function(){
if($(this).prop('checked')){
$(this).parent().next().show();
}else{
$(this).parent().next().hide();
}
});
});
Use class attribute to get dynamic process.
Tested on google Chrome works.
gets id of input takes the number after "checkbox(gets_target)" string. creates a id with adding this number to end of "box"+number string
HTML :
<input onChange="display_hidden_field(this)" id="checkbox2" type="checkbox">
<div id="box2" style="display:none;">content</div>
Javascript :
function display_hidden_field(checkbox){
var box_id = checkbox.id;
var search_pattern = /checkbox(.*?)$/g;
var number = search_pattern.exec(box_id);
number = number[1];
box_id = 'box'+number;
var box = document.getElementById(box_id);
if(checkbox.checked){
box.style.display = 'block';
}else{
box.style.display = 'none';
}
}
You can use code like this what i did in this your every checkbox id create like this "checkbox_1" and your box id like this box_1 and so on other numbers please check below code you will get idea what you need to do with your html and java script.
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox_1" type="checkbox" onclick="myfunction(this);">
</div>
<div class="col-md-4" id="box_1" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox_2" type="checkbox" onclick="myfunction(this);">
</div>
<div class="col-md-4" id="box_2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
<script>
function myfunction(obj)
{
var element_index = obj.id.split("_");
console.log('box_'+element_index[1]);
var box = document.getElementById('box_'+element_index[1]);
if(obj.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
}
</script>
Here in script i have given function name myfunction but you can set your function name as per your need. may this is helpful for you.