Javascript - check/uncheck checkbox after summing different inputs - javascript

I have a ‘parent’ <div>, and ‘child’ divs which are shown after clicking parent <div>.
All divs have <checkboxes> and <input> to put quantity.
Parent <checkbox> checks when at least one child <checkbox> is checked.
When child <checkbox> is checked/unchecked the quantity in <input> is automatically changed into ‘1’ or ‘’.
Parent quantity <input> is disabled and it is supposed to show the sum of all children quantities.
I have two problems.
First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child <checkbox>) the summing script does not react on such change.
Secondly I wasn’t able to uncheck the parent <checkbox> when all child checkboxes are unchecked.
However I’m assuming if the summing script will start working properly I will be able to bind the parent <checkbox> with the sum (if (sum> 0){ $('#checkbox0').prop('checked', true);}else{$('#checkbox0').prop('checked', false);}
Html:
<div class="divCell" id="click1">
<div class="checkbox_div" style='pointer-events:none;'>
<input type="checkbox" id="checkbox0">
</div>
<div class="div_name_divcell">Parent - click to open</div>
<div class="div_quantity_divcell">
<input type="text" name="parent_1" class="quantity_class_parent_1" id="quantity_parent_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)" disabled="disabled">
</div>
</div>
<div id="hidden1" style="display: none;">
<div class="divCell" id="child_click1">
<div class="checkbox_div">
<input type="checkbox" id="checkbox1">
</div>
<div class="div_name_divcell">Child1</div>
<div class="div_quantity_divcell">
<input type="text" name="child_1" class="quantity_class_child" id="quantity_child_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
</div>
</div>
<div class="divCell" id="child_click2">
<div class="checkbox_div">
<input type="checkbox" id="checkbox2">
</div>
<div class="div_name_divcell">Child2</div>
<div class="div_quantity_divcell">
<input type="text" name="child_1" class="quantity_class_child" id="quantity_child_2" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
</div>
</div>
</div>
Css:
.divCell {width: 500px;height: 35px;margin: 2px 0;display: inline-block;background-color: #D4F78F;}
.div_quantity_divcell{float:right; padding:9px 1px 0 0}
.checkbox_div {width: 25px;position: relative;margin: 5px;float: left;}
.div_name_divcell {line-height: 35px;width: auto;float: left;}
JavaScript:
$(document).ready( function() {
event.preventDefault();
$('#checkbox1').click(function() {
if(this.checked){
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
}else{
$('#quantity_child_1').val('')
//$('#checkbox0').prop('checked', false);
}});
$('#quantity_child_1').keyup(function(){
$('#checkbox1').prop('checked', this.value > 0);
$('#checkbox0').prop('checked', true);
})
//second child
$('#checkbox2').click(function() {
if(this.checked){
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_2').val('1')
}else{
$('#quantity_child_2').val('')
//$('#checkbox0').prop('checked', false);
}});
$('#quantity_child_2').keyup(function(){
$('#checkbox2').prop('checked', this.value > 0);
$('#checkbox0').prop('checked', true);
})
});
// suming script
$(document).on('change', '.quantity_class_child', function(){
var sum = 0;
$('.quantity_class_child').each(function(){
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
});
//opening script
$(document).ready(function() {
$('#click1').click(function() {
if ($('#hidden1').is(':hidden')) {
$('#hidden1').show(500);
} else {
$('#hidden1').hide(500);
}
});
});
JSFiddle: https://jsfiddle.net/mamzj4tw/6/

This is an updated version of your version
https://jsfiddle.net/mamzj4tw/13/
It uses each() to better (and clean) add actions to inputs.
You can create your custom events like do-sum and fire when you want.
In this case I defined that the sum is executed when
$(document).trigger('do-sum');
fires do-sum event.
and I've set a listener that executes your routine:
$(document).on('do-sum', function(){
var sum = 0;
$('.quantity_class_child.active').each(function(){
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
var parentChecked = false;
$('#hidden1 input[type="checkbox"]').each(function(i, e){
if($(e).is(':checked')) {
parentChecked = true;
}
});
$('#checkbox0').prop('checked', parentChecked);
});
I also use class active to set valid inputs (and quick sum them).
PS you don't need event.preventDefault(); after document ready event.

Ok, Here are the things that you can do to achieve,
First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child ) the summing script does not react on such change.
The thing is change event will not be triggered if you are setting/changing the value from the javascript. For this you can manually call the change event to trigger the effect. Or, Create a separate function for summation calculation and call it on uncheck event of the checkbox.
eg.
Either
$('#checkbox1').click(function() {
if (this.checked) {
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
} else {
$('#quantity_child_1').val('')
$(".quantity_class_child").trigger("change");
//$('#checkbox0').prop('checked', false);
}
});
OR
$('#checkbox1').click(function() {
if (this.checked) {
$('#checkbox0').prop('checked', this.checked);
$('#quantity_child_1').val('1')
} else {
$('#quantity_child_1').val('');
summation();
}
});
function summation(){
var sum = 0;
$('.quantity_class_child').each(function() {
sum += +$(this).val();
});
$('#quantity_parent_1').val(sum);
}
Now for the second part,
Secondly I wasn’t able to uncheck the parent when all child checkboxes are unchecked.
Just check the length of the checked input box during the summation process and uncheck it if the the length is zero.
Hope this help you cause.

Your code was a bit to complicated, so i have rewritten what you tried to archive ( without the css part). fiddle here
three little html div's
<div class="parent" id="parent">
<span class="input">
<input type="checkbox" name="parent" value="">
<label for parent>parent - click to open</label>
<input type="text" name="sum">
</span>
</div>
<div class="child" id="child1">
<span class="input">
<input type="checkbox" class="inputCheckbox" name="child1" value="child1">
<input type="text" class="inputSum" name="sum1">
</span>
</div>
<div class="child" id="child2">
<span class="input">
<input type="checkbox" class="inputCheckbox" name="child2" value="child2">
<input type="text" class="inputSum" name="sum2">
</span>
</div>
and a bit of jquery
$('.child').hide();
// check if parent checkbox is checked
$('input[name="parent"]').click ( function () {
if ( $(this).is(':checked') ) $('.child').show(); else $('.child').hide();
})
// check if childcheckbox is checked , if true trigger keyup and sum
$('.inputCheckbox').on ( 'change', function () {
if ( $(this).is(':checked') ) $(this).next().val('1').keyup();
// if not , trigger parent
if ( ! $('.inputCheckbox').is(':checked') ) $('input[name="parent"]').click ();
})
// check if value is entered and sum it on keyup
$('.inputSum').on('keyup', function () {
var sum = 0;
$('.inputSum').each ( function () { sum += ( $(this).val() - 0) })
$('input[name="sum"]').val(sum)
})
HTH

You can add new elements https://jsfiddle.net/mamzj4tw/34/
$(document).ready( function() {
$('.drop-down #checkbox').on('change',function(){
$(this).closest('.divCell').find('#quantity_child')
.val(this.checked ? 1:'').trigger('keyup');
});
$(document).on('keyup click', '.quantity_class_child', function(){
$(this).closest('.divCell').find('#checkbox').prop("checked",+$(this).val());
var sum = 0;
$('.quantity_class_child').each(function(){sum += +$(this).val()});
$('#quantity_parent_1').val(sum ||'');
$('#checkbox0').prop("checked", sum);
});
$('#click1').click(function() { $('#hidden1').toggle(500); });
});

Related

Checkbox Hidden Div Unchecked

I have a checkbox hidden div with text field. If checkbox is checked this text field will showed, but if checkbox unchecked text field not show. This Code :
<script type="text/javascript">
$(function () {
$("input[name='checkbox1']").click(function () {
if ($("#checkyes1").is(":checked")) {
$("#dvcheckbox1").show('lainnya');
} else {
$("#dvcheckbox1").hide('lainnya');
}
});
});
</script>
<div style="margin-left: 29%; margin-top: -2%;">
<label for="checkyes1">
<input type="checkbox" id="checkyes1" name="checkbox1" value="lainnya" />
Lainnya
</label>
<div id="dvcheckbox1" style="display: none;">
<?php echo $form->textField($model,'lainnya'); ?>
</div>
</div>
But, How this checkbox is checked if there something value on textfield? and text field shown. Because in form Update, value was show but checkbox is checked. I want checkbox is checked
For example Like this:
Click to show example
Instead use with change event with .toggle(boolean) method:
// on page load check of the div contains any text
$("#dvcheckbox1").toggle(function(){
var $v = $(this).find('input').val();
$("input[name='checkbox1']").prop('checked', $v.trim().length !== 0)
return $v.trim().length !== 0;
});
$("input[name='checkbox1']").change(function () {
$("#dvcheckbox1").toggle(this.checked);
});
There are a few things here:
1 - Better if you use document ready, because it waits until all the elements are loaded.
2 - You should hide the element$("#dvcheckbox1").hide('lainnya') when the page is loaded.
3 - A listener in the input:text is a good idea. It enables the checkbox if the textbox is empty.
Please, have a look at the next piece of code:
<div>
<label for="checkyes1">
<input type="checkbox" id="checkyes1" name="checkbox1" value="lainnya" />
Lainnya
</label>
<div id="dvcheckbox1">
<label for="myValuye"/>
<input type="text" id="myValue" name="myValue" value=""/>
</div>
</div>
<script>
$(document).ready(function() {
$("input[name='checkbox1']").click(function () {
// Always use some logs to check what line are you reaching.
console.log("Clicked checkbox!!!");
if ($("#checkyes1").is(":checked")) {
$("#dvcheckbox1").show('lainnya');
} else {
console.log("Value: " + $("#myValue").val());
$("#dvcheckbox1").hide("lainnya");
}
});
$("#myValue").bind("change paste keyup", function() {
if ($(this).val() == "") {
$("#checkyes1").removeAttr("disabled");
} else {
$("#checkyes1").attr("disabled", true);
}
});
// First of all we hide the #dvcheckbox1
$("#dvcheckbox1").hide('lainnya');
})

jquery radio button click and change function not working

I want to hide and show div according to radio buttons value.
HTML code is,
<div id="share_to_others">
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type">
</div>
And jquery code that i tried is,
$("#share_to_others input[name='fx_sharepl_type']").click(function () {
alert("test");
});
$("#share_to_others input[name='fx_sharepl_type']").change(function () {
alert("test");
});
$("#fx_sharepl_type").change(function () {
alert("asdas");
});
$("input[name=fx_sharepl_type]:radio").change(function () {
alert("click fired");
});
$(document).on('change', 'input:radio[name=fx_sharepl_type"]', function (event) {
alert("click fired");
});
Many of them from jsfiddle working demo, But not working for me, i dont know why.
Am i doing anything wrong?
You have to give unique id to each radio button then after do like this way.
$("#r1, #r2, #r3").change(function () {
$(function() { // DOM loaded event handler
var show_duration = 0;
var content_33 = $("#content_33");
var content_22 = $("#content_22");
var content_11 = $("#content_11");
var bloc_radio_share = $("#share_to_others");
// Take an html element in parameter and show it
function show_content(content_id) {
content_id.show(show_duration);
}
// Take an html element in parameter and hide it
function hide_content(content_id) {
content_id.hide(0);
}
hide_content(content_22);
hide_content(content_11);
bloc_radio_share.change(function() {
var radio_checked_val = $('input[name=fx_sharepl_type]:checked', '#share_to_others').val();
if (radio_checked_val == 33) {
hide_content(content_22);
hide_content(content_11);
show_content(content_33);
}
else if (radio_checked_val == 22) {
hide_content(content_33);
hide_content(content_11);
show_content(content_22);
}
else { // case content == 11
hide_content(content_33);
hide_content(content_22);
show_content(content_11);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="share_to_others">
<label>
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type" checked />
33
</label>
<label>
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type" />
22
</label>
<label>
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type" />
11
</label>
</div>
<div id="content_33">
This div is displayed because of click on radio button 33
</div>
<div id="content_22">
Radio button 22 has been clicked so I appear
</div>
<div id="content_11">
If you click on radio button 11 you'll see me, like now
</div>
Here is an example of algorithm that fits your need. Logic may be not the best or the fastest but that is a begin.
Your code wors but you forgot to include a JQuery source version located to the left side of the JSFiddle window.
Selecting any version of JQuery will make your code work.

Get output of .change() function in .click() function

I have two radio buttons which both have values. When one is selected, and a button/link is clicked, the value of the selected radio button needs to be outputted to a text box.
Here is my HTML:
<form class="discount-choice" method="post" action="#">
<ul>
<li>
<input type="radio" value="1" name="discount" id="1-month" class="discount-checkbox" />
<label for="1-month">1 Month - no discount</label>
</li>
<li>
<input type="radio" value="0.95" name="discount" id="4-months" class="discount-checkbox" />
<label for="4-months">4 months - 5% discount</label>
</li>
</ul>
Get Result
<input type="text" class="result" />
</form>
and my JavaScript (jQuery):
var discount = $(".discount-checkbox").on("click", function () {
return this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
When I click the button (after having selected a radio button), I just get [object Object] in the text box.
I'm not sure of the syntax for setting a variable to be a jQuery function so this is likely where I am going wrong. If anyone could give me some guidance that would be awesome.
Thank you for any help :)
discount is set to the jQuery object returned by $(".discount-checkbox"). You need to bind a click handler that updates a variable:
var discount = 0;
$(".discount-checkbox").on("click", function () {
discount = this.value;
});
Use this:
$(".get-result").on("click", function(e) {
e.preventDefault();
$(".result").val( $('.discount-checkbox:checked').val() );
});
You do not need the click handler on the checkbox as #billyonecan has mentioned in the comments.
And ... if you really need to attach an event handler to the checkboxes, that would be a change event handler instead of click.
Try This Code:
var discount;
$(".discount-checkbox").on("click", function () {
discount= this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
no need of discount-checkbox click event
$(".get-result").on("click", function() {
var discount = $(".discount-checkbox:checked").val();
$(".result").val(discount);
});

validating at least one checkbox selected on dynamically added fields

If you're dynamically adding form fields to an existing form, what's the best way of adding validation?
Consider this fiddle: http://jsfiddle.net/yWGK4/
<form action="#" method="post">
<div id="parent">
<div class="child">
<input type="checkbox" name="box1[]" value="1" /> 1
<input type="checkbox" name="box1[]" value="2" /> 2
<input type="checkbox" name="box1[]" value="3" /> 3
</div>
</div>
</form>
<button id="addBoxes">Add Boxes</button>
<script>
$(function() {
var parentdiv = $('#parent');
var m = $('#parent div.child').size() + 1;
$('#addBoxes').on('click', function() {
$('<div class="child"><input type="checkbox" name="box'+m+'[]" value="1" /> 1 <input type="checkbox" name="box'+m+'[]" value="2" /> 2 <input type="checkbox" name="box'+m+'[]" value="3" /> 3 </div>').appendTo(parentdiv);
m++;
return false;
});
});
</script>
On that form I'm adding new checkbox groups, and want to make sure at least one box from each group is checked (not one box across all groups). Anyone got any clever methods? Everything I've looked at would get very complicated due to the dynamically added fields.
It doesn't matter if the checkboxes are dynamic when validating on submit etc. so something like this would check if at least one checkbox per .child is checked :
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
FIDDLE
If you want to check it using jQuery you can use `.each()
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
You can find more about this jQuery functions in this links:
each()
find()
here's what I came up with. Basically you loop over the .child groups and test if they have a checkbox in the checked state..
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});

jquery - show textbox when checkbox checked

I have this form
<form action="">
<div id="opwp_woo_tickets">
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</form>
As of now, I'm using this jquery code to show textbox when checkbox checked.
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $('div.max_tickets').show();
else $('div.max_tickets').hide();
}).change();
});
It works fine, but it shows all textboxes when checked.
Can someone help me to fix it?
Here is the demo of my problem.
http://codepen.io/mistergiri/pen/spBhD
As your dividers are placed next to your checkboxes, you simply need to use jQuery's next() method to select the correct elements:
if ($(this).is(':checked'))
$(this).next('div.max_tickets').show();
else
$(this).next('div.max_tickets').hide();
Updated Codepen demo.
From the documentation (linked above), the next() method selects:
...the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Here we're selecting the next div.max_tickets element. However in your case just using next() with no parameters would suffice.
Assuming markup will stay in same order can use next()
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
$(this).next()[ this.checked ? 'show' : 'hide']();
}).change();
});
Change:
if ($(this).is(':checked')) $('div.max_tickets').show();
To:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
jsFiddle example here
Maybe try selecting the next element only?
change:
if ($(this).is(':checked')) $('div.max_tickets').show();
to:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
Put a div across your checkbox and text box
<form action="">
<div id="opwp_woo_tickets">
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</div>
</form>
and replace your jquery code with this one below,
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $(this).parent().children('div.max_tickets').show();
else $(this).parent().children('div.max_tickets').hide();
}).change();
});
I have tested it and it works.
While you may need a JavaScript solution for other reasons, it's worth noting that this can be achieved with pure CSS:
input + div.max_tickets {
display: none;
}
input:checked + div.max_tickets {
display: block;
}
JS Fiddle demo.
Or, with jQuery, the simplest approach seems to be:
// binds the change event-handler to all inputs of type="checkbox"
$('input[type="checkbox"]').change(function(){
/* finds the next element with the class 'max_tickets',
shows the div if the checkbox is checked,
hides it if the checkbox is not checked:
*/
$(this).next('.max_tickets').toggle(this.checked);
// triggers the change-event on page-load, to show/hide as appropriate:
}).change();
JS Fiddle demo.
Reference:
CSS:
:checked pseudo-class.
jQuery:
change().
next().
toggle().
protected void EnableTextBox()
{
int count = int.Parse(GridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBox cb1 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox2");
CheckBox cb2 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox3");
TextBox tb = (TextBox)GridView1.Rows[i].Cells[4].FindControl("txtration");
TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtjob");
TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[6].FindControl("txtaadhar");
if (cb.Checked == true)
{
tb.Visible = true;
}
else
{
tb.Visible = false;
}
if (cb1.Checked == true)
{
tb1.Visible = true;
}
else
{
tb1.Visible = false;
}
if (cb2.Checked == true)
{
tb2.Visible = true;
}
else
{
tb2.Visible = false;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
EnableTextBox();
}

Categories

Resources