Different way to generate divs via checkbox - javascript

Currently I am using the below method using JS to generate a block of text in a right column when a check box is clicked ticked in a left column.
This has been working fine, however each time I need to add a check box, I need to add a new class and new formContainer element. With the original 3 I had, wasn't a big deal. But now that I'm up to 10 and growing, getting a bit cumbersome.
What better possibilities exist to generate a div/block of text on a different part of the page as a result of a ticked check box?
Check Box
<input id="chk" data-detail="<br>Right 1" class="chkbox" type="checkbox" value="results" />1
Creating individual class
<div class="formContainer"></div>
Script
<script>
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
}
else
{
$('.formContainer').html('');
}
});
</script>

If you are wanting them in columns you can generate them using bootstrap gridsystem.
<div class="formContainer>
<div class="container">
<div class="row">
<div class="col-m-4"></div>
<div class="col-m-4"></div>
<div class="col-m-4"></div>
</div>
<div class="row">
...
</div>
</div>
</div>
If you are wanting to keep them in the same column you could just use .append()
$('.formContainer').append('<div class="new">'+$(this).data('detail')+'</div>');
These can be used together to generate a fluid system or just the append can be used to keep adding divs to your formContainer

I would suggest appending a form after your checkbox using the Jquery function .after(newElement);
Play with it on codepen
Html:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<style>
.formContainer{
height: 50px;
width: 100%;
background-color: gray;
}
</style>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
JQuery:
$(document).ready(function(){
$('.checkboxesThatAppends').click(function(){
var associatedFormId = $(this).attr('data-associated-form-id');
if(associatedFormId){
//if there is a form container associated with this checkbox already
//then let's remove that form.
//and remove the association from the checkbox
$('#'+associatedFormId).remove();
$(this).attr('data-associated-form-id', '');
}else{
//generate an Id for the new form to attach.
var newId = new Date().getTime();
$(this).attr('data-associated-form-id', newId);
$(this).parent().after('<div id="'+newId+'" class="formContainer"></div> ');
}
});
});

You can just use jQuery's append() and remove() methods in combination with wrapping HTML elements to achieve this effect.
JSFiddle: https://jsfiddle.net/xuc4tze0/1/
HTML
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 1" class="chkbox" type="checkbox" value="results" />1
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 2" class="chkbox" type="checkbox" value="results" />2
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 3" class="chkbox" type="checkbox" value="results" />3
</div>
</div>
CSS
.row {
display: flex;
width: 400px;
}
.left, .right {
flex: 0 0 50%;
}
Javascript / jQuery
$('.chkbox').on('click', function() {
if ($(this).is(':checked'))
// Find the row and add the 'right' column
$(this).closest('.row').append('<div class="right">' + $(this).data('detail') + '</div>');
} else {
// Find the 'right' column and remove it
$(this).closest('.row').find('.right').remove();
}
});

Depending on your need and the content of the divs I got a couple of suggestions :
Modal popups. If you these divs are just notifications then a popup would do (but doubt this is what you need).
List group, use bootstrap's neat class list group to show the needed info in an <ul> element, the JS that comes with these can be neat as well with special animations.
Use tooltips on each checkbox instead of getting a whole div appearing.
Last suggestion which I like least is putting all of your div's in a single container div on the right. Fix its width and height and set overflow attribute so you can scroll up and down the shown divs

Related

Find nearest div with class disableDiv and disable all of its contents

In this code I am checking the chekbox with class disableDivCheckbox and the code is disabling all of the div content with class disableDiv. But if I apply this combination to another checkbox and another div, this is not working properly. So I want to find closest div with class disableDiv and disable only that div. I am using disabale * because I want to disbale div and its contents.
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$('.disableDiv *').removeAttr("disabled");
}
else {
$('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
fiddle : https://jsfiddle.net/8c0x1pho/
You can try this approach:
Get checked state and save it in a variable
Navigate to all necessary elements using this. It will make your code more modular.
Try not to use * selector. Use more specific selectors as this will specify element types you are manipulating and make your code more reusable.
Instead of attr and removeAttr, you can just set value of disabled as true or false . You can just use !$(..).is(":checked")
Sample:
// Only call functions. DON'T declare any functions in ready.
$(document).ready(function() {
// Have a common function.
// If size grows, this can be exported to its own file
registerEvents();
// Initialise on load states.
updateUIStates("#addBusinessObjectivesCheckbox")
});
function registerEvents() {
$(".disableDivCheckbox").click(function() {
updateUIStates(this)
})
}
function updateUIStates(el) {
var isNotChecked = !$(el).is(":checked");
var inputs = $(el)
.parents(".checkbox")
.siblings(".disableDiv")
.find('input');
inputs.attr("disabled", isNotChecked)
isNotChecked && inputs.val('').prop('checked', false)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<fieldset id="AddBusinessObjectivesFieldset" class="">
<legend>
Add business objectives
</legend>
<div class="checkbox">
<label>
<input type="checkbox" value="addBusinessObjectivesCheckbox" name="addBusinessObjectivesCheckbox" class="disableDivCheckbox" id="addBusinessObjectivesCheckbox"> Add business objectives
</label>
</div>
<div style="border: 2px solid;margin-bottom: 5px;border-color: gray;padding: 0px 0px 0px 5px;margin-top: 5px;margin-right: 10px;" class="disableDiv">
<div class="form-inline" style="margin-top:5px;margin-bottom:5px;">
<table>
<tr>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="0" class=""> Fixed N
</label>
</div>
</td>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="1" class=""> Random upto N
</label>
<input type="text" placeholder="Enter N" id="indexTextboxAddBusinessObjectives" name="indexTextboxAddBusinessObjectives" style="width:70px" class="" />
</div>
</td>
</tr>
</table>
</div>
</div>
</fieldset>
Pointers
$(document).ready() is more like init function. Try to call functions instead of defining in it. This will make easier to understand as it will depict a flow.
Use pure functions and call then. Like onChange, you can call few functions: updateUIStates(), postDataToServer(), processResponse(), otherTodos(). This may look like overkill but in long run this will help.
Create a tree structure in your markup.
<div class="container">
<div class="checkbox-container">...</div>
<div class="input-containers">...</div>
</div>
This will ease navigation part. No matter what structure you use, keep it standardised. This will keep your JS clean.
Try this,
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$(this).closest('.disableDiv *').removeAttr("disabled");
} else {
$(this).closest('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
This means that, you will disable all content of only that disableDiv class to which disableDivCheckbox belongs.
Give it a try, this will work.

php javascript filtering content

I need a content filtering system for my website. By checking and unchecking of a checkbox, the according elements should be shown or hidden.
<form>
<p><input type="checkbox" checked="checked"><label>Plants</label></p>
<p><input type="checkbox" checked="checked"><label>Animals</label></p>
<p><input type="checkbox" checked="checked"><label>Humans</label></p>
</form>
The checkboxes above should toggle the visibility of the divs below with the according class, by changing display:block; to display:none;
<div class="Plants" style="display:block">
<p>Grass</p>
<div>
<div class="Humans" style="display:block">
<p>John</p>
<div>
<div class="Plants" style="display:block">
<p>Flower</p>
<div>
<div class="Animals" style="display:block">
<p>Lion</p>
<div>
For example:
By uchecking the Plants checkbox, the divs with Grass and Flower should be hidden.
What would be the most elegant way to accomplish that in php or javascript?
According to your HTML structure you may use:
change event
:checkbox selector
toggle(boolean)
next
As reported in the comment:
In your PHP file you have to include the jQuery library. The line you have to include is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In order to add to your PHP file the jQuery function you have to add a <script> tag and inside it you must copy the jQuery function.
It is not necessary to change the reaming part of your PHP file.
The snippet:
//
// When the document is Ready
//
$(function () {
//
// when you click a checkbox
//
$(':checkbox').on('change', function(e) {
var divClass = $(this).next().text();
$('.' + divClass).toggle(this.checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p><input type="checkbox" checked="checked"><label>Plants</label></p>
<p><input type="checkbox" checked="checked"><label>Animals</label></p>
<p><input type="checkbox" checked="checked"><label>Humans</label></p>
</form>
<div class="Plants" style="display:block">
<p>Grass</p>
</div>
<div class="Humans" style="display:block">
<p>John</p>
</div>
<div class="Plants" style="display:block">
<p>Flowesr</p>
</div>
<div class="Animals" style="display:block">
<p>Lion</p>
</div>

Javascript check bootstrap checkbox by id

I have the following form :
<form class="form-inline" role="form">
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox">
<label>
<input type="checkbox" name="discounting" onchange='handleChange(this);' id='check11' > Show only price-discounted products
</label>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox" id='check21'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
</div>
</div>
</form>
I'd like to be able to check the second checkbox automatically with JavaScript once I check the first one. I tried using the following script :
<script>
function handleChange(cb) {
if(cb.checked == true) {
alert('Message 1');
document.getElementById("check21").checked = true;
} else {
alert('Message 2');
var x = document.getElementById("check21").disabled= false;
}
}
</script>
But it doesn't work since I think with bootstrap is a question of classes.
The problem as Didier pointed out is that you have two elements with the same ID:
<div class="checkbox" id='check21'>
and
<input type="checkbox" name="discounting" onchange='' id='check21'>
The call to document.getElementById('check21') will probably (because the behavior is undefined) return the first one, which in this case is the <div> element, not the checkbox.
You must not use the same ID on two HTML elements, so you need to change the ID on one or the other of them.
http://jsfiddle.net/uywaxds5/2/
I included boostrap as an external reference.
<div class="checkbox" id='check22'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
Fixing the duplicate id seems to work.
If it does not works, the issue might be in another part of your code.
Use a different name for the second radio button
<input type="checkbox" name="discounting21">
There can only be one selected radio button belonging to the same group(ie. name).

Bootstrap collapse with wrong behavior

My problem is that I have 2 blocks in modal and when I click on .emailInbound checkbox it toggle .in-serv-container open, but when I click on .accordion-heading to open comment part it makes .in-serv-container collapse.
What can be a reason?
HTML:
<label class="checkbox">
<input class="emailInbound" type="checkbox" onclick="toggleInServ(this)">Использовать Email для регистрации обращений
</label>
<div id='in-serv-container'>
<div><strong>Настройка входящей почты</strong></div>
<div>
<input class="emailOutserver" type="text" placeholder="Сервер входящей почты">
<input class="emailOutserverPort" type="text" placeholder="Порт">
</div>
<div>
<select class="emailOutProtocol half" style="width: 49%!important;">
<option value='usual'>Обычный</option>
<option value='ssl'>SSL</option>
</select>
<input class="emailInFolder half" type="text" placeholder="Папка входящей почты">
</div>
<div class="modal-body-container">
<input type="text" placeholder="Опции">
</div>
<button class="btn btn-link">Проверить подключение</button>
<hr>
</div>
<div class="accordion" id="comment-wrapper">
<div class="accordion-heading" data-toggle='collapse' data-target='#emailComment' onclick='toggleChevron(this)'>
<strong>Комментарий</strong> <i class='icon-chevron-right'></i>
</div>
<div id="emailComment" class="collapse" data-parent="#comment-wrapper">
<textarea class="emailComment"></textarea>
</div>
</div>
JS:
function toggleInServ(box){
var checked = $(box).prop('checked');
if(checked){
$('#in-serv-container').css('height', '170px');
}else{
$('#in-serv-container').css('height', '0px');
}
}
function toggleChevron(o){
var icon = $(o).children('[class*=icon]');
if(icon.hasClass('icon-chevron-right')){
icon.removeClass('icon-chevron-right');
icon.addClass('icon-chevron-down');
}else{
icon.removeClass('icon-chevron-down');
icon.addClass('icon-chevron-right');
}
}
If I'm in the right track at this, you want each dropdown to stay on opened if the checkbox is ticked? What ever is the case here, please provide us with your CSS-styling as well. Would be best if you'd give us JSFiddle of your case.
Changing just the
height
attribute of your CSS seems like a bad idea. Instead of that, you could try using
display: block;
and
display: none;
So it would really be a hidden field before it gets selected. Not the answer to the question itself, but just something to note.
It was because of 'bubbling'. I added e.stopPropoganation() and it help.

add onto checked values in checkbox via jquery

Hi Im trying to add onto a checkbox's values selected, so maintain the selected values but add other selected values. however the attribute doesn't add selected values. here is my attempt (p.s how would I in turn remove values selected and keep existing values selected?) thanks
$('.add_button').click(function() {
var values = $('input:checkbox:checked.ssremployeeids').map(function () {
return this.value;
}).get();
$('.ssremployeeid').attr('selected',values);
<div class="grs-multi-select-area" style="height:120px;width:150px;">
<div class="grs-multi-select-box ">
<input id="ssrBox" class="ssremployeeid" type="checkbox" name="ssremployeeid[]"
value="1312">
Amanda Becker
</div>
<div class="grs-multi-select-box "> // same as above I just collapsed it for viewing purposes
<div class="grs-multi-select-box ">
<div class="grs-multi-select-box ">
</div> //closes main div
});
I am still not sure if I understood you question correctly, but based one what I understood here's something you could try:
Sample Fiddle: http://jsfiddle.net/HFULf/1/
HTML
<div id="div1">
<input type="checkbox" name="cb1" value="val1" checked="checked" />
<input type="checkbox" name="cb2" value="val2"/>
<input type="checkbox" name="cb3" value="val3"/>
</div>
<div id="div2">
<input type="checkbox" name="cb1" value="val1"/>
<input type="checkbox" name="cb2" value="val2"/>
<input type="checkbox" name="cb3" value="val3"/>
</div>
<button id="btn1">Add Selected</button>
<button id="btn2">Remove Selected</button>
jQuery
//add selected values from first set of check-boxes to the second set
$('#btn1').click(function(e){
$('div#div1 input[type="checkbox"]:checked').each(function(){
$('div#div2 input[type="checkbox"]').eq($(this).index()).prop('checked',true);
});
});
//remove values from second set of check-boxes if selected in first one
$('#btn2').click(function(e){
$('div#div1 input[type="checkbox"]:checked').each(function(){
$('div#div2 input[type="checkbox"]').eq($(this).index()).prop('checked',false);
});
});
Hope, this will help you a little if not solve your problem entirely.

Categories