javascript change and send multiple checkbox values - javascript

H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});

Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();

The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>

Related

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

Javascript Sum of two values in one Input Text

I'm looking for a way to add another value into my input text. I have a read only input box, two radio buttons, and three checkboxes.
<div class="radios">
<label>
<input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
<input type="radio" name="extratreats" data-target="#extratreat"> Extra-Treats
</label>
</div>
<div id="extratreat" class="extratreat tab-pane collapse">
<label><h2>Extra Treats</h2></label>
<br />
<label><input id="treats" name="treats[]" value="Sweet Corner" type="checkbox" > Sweet Corner & Choco Fountain</label>
<label><input id="treats" name="treats[]" value="Popcorn Maker" type="checkbox" > Popcorn Maker</label>
<label><input id="treats" name="treats[]" value="Hotdog Roller" type="checkbox" > Hotdog Roller</label>
</div>
<div id="pricing">
<label><h2>Price</h2></label>
<br />
<input type="text" name="price-total" value="" autocomplete="off" readonly>
</div>
I've added a javascript to my radio button where if I click on non-exlusive the value of pricing will change to 279. But I don't know how to add more value to if I add from treats. For example the price of Sweet Corner is 2,500 and they also clicked on Non-Exlusive which has 279 as it's default value, how do I add 2,500 to the already specified 279?
Here's the script I tried using:
<script>
$(document).ready(function(){
$('[name=packages]').click(function() {
var val = $(this).val();
if (val == "non-exclusive") {
$('[name=price-total]').val('PHP 279');
} else if (val == "package1") {
$('[name=price-total]').val('PHP 300');
} else if (val == "package2") {
$('[name=price-total]').val('PHP 400');
}
});
$('[id=treats').click(function() {
var val1 = $(this).val();
var val = $('[name=price-total]').val();
if (val1 == "Sweet Corner") {
$('[name=price-total]').val(val.val+' 2500');
} else if (val1 == "package1") {
$('[name=price-total]').val('PHP 300');
} else if (val1 == "package2") {
$('[name=price-total]').val('PHP 400');
}
});
});
</script>
It gives me an "undefined value" if I click one of the checkboxes instead of adding it's value to the first value.
The problem was that you made a variable called val and then tried to access it with val.val + ' 2500' when it should have just been val + ' 2500'. val.val implies that there is a val object with a val property. Since there isn't, you got undefined.
You also have a syntax error with this:
$('[id=treats').click(function() {
As it should be:
$('[id=treats]').click(function() {
Also, I think that because of what your are testing, switch statements are more appropriate.
Lastly, you have multiple items with the same id, which isn't valid. After making them all unique, you should change your second click handler so that it accesses all the checkboxes by using the name attribute instead of id.
$(document).ready(function(){
$('[name=packages]').click(function() {
switch($(this).val()){
case "non-exclusive":
$('[name=price-total]').val('PHP 279');
break;
case "package1":
$('[name=price-total]').val('PHP 300');
break;
case "package2":
$('[name=price-total]').val('PHP 400');
break;
}
});
$('[name="treats[]"]').click(function() {
// Strip out non-numeric portion:
var val = $('[name="price-total"]').val().replace("PHP ", "");
switch($(this).val()){
case "Sweet Corner":
// Check to see if checkbox is checked...
if(this.checked){
// Must convert the value to a number and then you can do math
$('[name=price-total]').val("PHP " + (+val + 2500)); // <-- The problem was here
} else {
$('[name=price-total]').val("PHP 279");
}
break;
case "package1":
$('[name=price-total]').val('PHP 300');
break;
case "package2":
$('[name=price-total]').val('PHP 400');
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
<label>
<input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
<input type="radio" name="extratreats" data-target="#extratreat"> Extra-Treats
</label>
</div>
<div id="extratreat" class="extratreat tab-pane collapse">
<label><h2>Extra Treats</h2></label>
<br />
<label><input id="treats1" name="treats[]" value="Sweet Corner" type="checkbox" > Sweet Corner & Choco Fountain</label>
<label><input id="treats2" name="treats[]" value="Popcorn Maker" type="checkbox" > Popcorn Maker</label>
<label><input id="treats3" name="treats[]" value="Hotdog Roller" type="checkbox" > Hotdog Roller</label>
</div>
<div id="pricing">
<label><h2>Price</h2></label>
<br />
<input type="text" name="price-total" value="" autocomplete="off" readonly>
</div>

Check specific radio button is checked

I'm just trying to return true/false in one my my jquery methods depending on the check of a 2 radio buttons and if it's selected or not
I've tried several things but have not been able to get this right, it still submit the form without giving error that the buttons are not selected.
HTML Code
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" checked="" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" checked="true" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
Javascript
function checkOrderForm(frm) {
var paymentSelected = false;
var shippingSelected = false;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && frm.elements[i].checked) {
shippingSelected = true;
}
if (frm.elements[i].name == 'payment' && frm.elements[i].checked) {
paymentSelected = true;
}
}
if (!shippingSelected) {
alert(flow_no_shipping);
return false;
}
if (!paymentSelected) {
alert(flow_no_payment);
return false;
}
If I'm understanding your question correctly, you would only like this test to pass if BOTH of the radio buttons are checked. Currently, as long as one radio button in each group is checked, the code variable will be set to true, ignoring the state of the other radio button.
For example, if ONLY one of your shipping radio buttons was checked, the shippingSelected variable would be set to true and it would remain true.
A way to fix this is to begin with shippingSelected and paymentSelected set to true, and if one of the radio buttons are found to be unchecked, the variable will be set to false.
Here's an example:
var paymentSelected = true;
var shippingSelected = true;
// Check whether the payment method is selected
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].name == 'shipping' && !frm.elements[i].checked) {
shippingSelected = false;
}
if (frm.elements[i].name == 'payment' && !frm.elements[i].checked) {
paymentSelected = false;
}
}
You can use $("#payment_1").checked to check whether the radio is checked or not. Similarly you could use other ID's to check whether they are selected or not.
Here is the fiddle:
https://jsfiddle.net/bf8bo43t/
Try below code,
HTML
<form method="post" name="frm_payment_types">
<label class="checkout-item" for="payment_1">Cash On Delivery</label>
<input type="radio" name="payment" class="radio" id="payment_1" value="3" iscod="1" onclick="selectPayment(this)">
<label class="checkout-item" for="payment_2">Credit Card / Debit Card</label>
<input type="radio" name="payment" class="radio" id="payment_2" value="9" iscod="0" onclick="selectPayment(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_1">Home Delivery</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_1" value="3" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<label class="checkout-item" for="ECS_NEEDINSURE_2">Self-pickup</label>
<input name="shipping" type="radio" id="ECS_NEEDINSURE_2" value="8" supportcod="1" insure="0" class="radio" onclick="selectShipping(this)">
<br />
<input type="submit" name="submit" onclick="return checkOrderForm();" />
</form>
Javascript
<script type="text/javascript">
function validateForm(){
var payment_1 = document.getElementById('payment_1');
var payment_2 = document.getElementById('payment_2');
var ECS_NEEDINSURE_1 = document.getElementById('ECS_NEEDINSURE_1');
var ECS_NEEDINSURE_2 = document.getElementById('ECS_NEEDINSURE_2');
if((payment_1.checked == true || payment_2.checked == true) && (ECS_NEEDINSURE_1.checked == true || ECS_NEEDINSURE_2.checked == true)){
return true;
}
else if(payment_1.checked == false && payment_2.checked == false){
alert("Please select Cash On Delivery or Credit Card / Debit Card.");
}
else if(ECS_NEEDINSURE_1.checked == false && ECS_NEEDINSURE_2.checked == false){
alert("Please select Home Delivery or Self-pickup.");
}
return false;
}
</script>

checkbox - Check uncheck functionality is not working

My situation :
I am working on an shopping cart application and it contains some filters:
Filter by color (checkboxes)
Filter by style (checkboxes)
on selecting some of the colors my url becomes like this:
http://example.com/women/try.php?color=10,11,12,13
My issue :
On unchecking some colors the related params are not getting cleared from the url.
Also when I select some styles , I want the url to be like this:
http://example.com/women/try.php?color=10,11,12,13&style=1,2,3
Please help me how to achieve this functionality.
My code :
<?php
$colors = $_GET['color'];
$sel_colors = explode(',', $colors);
foreach($sel_colors as $k=>$v) {
$c['check'][$v] = $v;
}
for($i=10;$i<=14;$i++) { ?>
<input type="checkbox" name="color[]" value="<?php echo $i; ?>" <?php echo $check_value = ($c['check'][$i]) ? 'checked' : '0'; ?> >
<label>Color #<?php echo $i.'--'.$check_value; ?></label><?php
}
?><br/><br/><br/>
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" >
<label>style #2</label>
<input type="checkbox" name="type" value="3" >
<label>style #3</label>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
var baseUrl = 'http://website/women/try.php?color=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ',' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
</script>
Here is a code snippet of working solution. Name of the color checkbox is changed from color[] to just color
var baseUrl = 'http://website/women/try.php?';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
//Get all the selected color values
var queryString = "color="+$('[name="color"]:checked')
.map(function() {return this.value;}).get().join(',');
//Append all the selected styles
queryString += "&style="+$('[name="type"]:checked').map(function() {return this.value;}).get().join(',');
//reload page - commented for this snippet
//window.location = baseUrl + queryString;
alert(baseUrl + queryString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Color filter -->
<input type="checkbox" name="color" value="1" checked >
<label>Color 1</label>
<input type="checkbox" name="color" value="2" checked >
<label>Color 2</label>
<input type="checkbox" name="color" value="3" checked >
<label>Color 3</label>
<input type="checkbox" name="color" value="4" checked >
<label>Color 4</label>
<BR><BR>
<!-- Style filter -->
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" checked>
<label>style #2</label>
<input type="checkbox" name="type" value="3" checked>
<label>style #3</label>
Use map() function to get all checked color and style checkbox values like following.
var baseUrl = 'http://website/women/try.php?color=';
$('input[name="color[]"], input[name="type"]').change(function () {
var colors = $('input[name="color[]"]:checked').map(function () { return this.value; }).get().join();
var styles = $('input[name="type"]:checked').map(function () { return this.value; }).get().join();
window.location = baseUrl + colors + '&style=' + styles;
});

jquery click event resets check property of checkbox

I have a checkboxlist control, in this control I wan't every checkbox to fire an event whenever the checkbox is clicked (manually or programmatically).
Html code generated by checkboxlist lloks something like below:
<div id="divleft">
<table id="MainContent_CheckBoxList1">
<tbody>
<tr>
<td><input id="MainContent_CheckBoxList1_0" name="ctl00$MainContent$CheckBoxList1$0" onclick="router(this);" value="1" type="checkbox"><label for="MainContent_CheckBoxList1_0">Option1</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_1" name="ctl00$MainContent$CheckBoxList1$1" onclick="router(this);" value="2" type="checkbox"><label for="MainContent_CheckBoxList1_1">Option2</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_2" name="ctl00$MainContent$CheckBoxList1$2" onclick="router(this);" value="3" type="checkbox"><label for="MainContent_CheckBoxList1_2">Option3</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_3" name="ctl00$MainContent$CheckBoxList1$3" onclick="router(this);" value="4" type="checkbox"><label for="MainContent_CheckBoxList1_3">Option4</label></td>
</tr>
</tbody>
</table>
</div>
On click of checkbox I am hiding or showing div(s). The div looks like:
<div id="divright">
<div id="divoption1" style="display: none;">
I am in option1 div
</div>
<div id="divoption2" style="display: none;">
I am in option2 div
</div>
<div id="divoption3" style="display: none;">
I am in option3 div
</div>
</div>
</div>
I have a jquery code which does the heavy duty work for showing / hiding divs.
$(document).ready(function () {
RunOnce();
});
function uncheckAllCheckboxes(previouscheckedCheckboxValue, currentcheckedCheckboxValue) {
if (previouscheckedCheckboxValue != null && previouscheckedCheckboxValue != currentcheckedCheckboxValue) {
window.isRunOnce = 'false';
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
//variable used to avoid infinite loop
window.isRunOnce = null;
}
return currentcheckedCheckboxValue;
}
function router(control) {
if (control.value == '1') {
Option1Controller(control.value);
}
if (control.value == '2') {
Option2Controller(control.value);
}
if (control.value == '3') {
Option3Controller(control.value);
}
}
function Option1Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption1]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption1]').hide();
}
}
function Option2Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption2]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption2]').hide();
}
}
function Option3Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption3]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption3]').hide();
}
}
function RunOnce() {
Option1Controller('1');
Option2Controller('2');
Option3Controller('3');
}
Problem lies with function uncheckAllCheckboxes, in this function, I am unchecking previously checked checkboxes:
I have tried:
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false);
Above query unchecks the corresponding checkbox but does not fire the onclick event?
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').click(); just after the above query.
It fires the click event but also undoes 1, so it is useless.
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
This query also seems to do nothing
My requirement is simple: I need to pro grammatically check/uncheck checkboxes which are identified by parent id and the value of checkbox control. After checking/unchecking, the control should fire click event also.
Any help shall be appriciated.
Note: I am new to this jquery stuff, so any improvements in my code are also welcomed.
Have you considered using radio buttons instead of checkboxes? They have same behavior you trying to achieve with checkboxes. I've created a fiddle
HTML
<label for="checkbox1">Div 1</label>
<input type="checkbox" name="div" id="checkbox1" data-div-id="1">
<label for="checkbox2">Div 2</label>
<input type="checkbox" name="div" id="checkbox2" data-div-id="2">
<label for="checkbox3">Div 3</label>
<input type="checkbox" name="div" id="checkbox3" data-div-id="3">
<hr/>
<div id="div1">DIV1</div>
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
<br/>
<label for="radio1">Div 4</label>
<input type="radio" name="div" id="radio1" data-div-id="4">
<label for="radio2">Div 5</label>
<input type="radio" name="div" id="radio2" data-div-id="5">
<label for="radio3">Div 6</label>
<input type="radio" name="div" id="radio3" data-div-id="6">
<hr/>
<div id="div4">DIV4</div>
<div id="div5">DIV5</div>
<div id="div6">DIV6</div>
JS
$(document).ready(function() {
var checkboxes = $('input:checkbox'),
radios = $('input:radio'),
divs = $('div');
// hide all divs
divs.hide();
checkboxes.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
$('#div' + $(target).data('div-id')).toggle();
});
radios.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
divs.hide();
$('#div' + $(target).data('div-id')).toggle();
});
});
you can see the comparison between both. And wouldn't use inline js anymore and css when possible. And try to avoid using tables if it not for tabular data, they are known for causing performance issues. Read this
I think you are using too much code.
Check this:
$('input[type="checkbox"]').change(function () {
var this_index = $(this).closest('tr').index(); //check the index of the tr of this input
$("#divright > div").eq(this_index).show(); //show the div inside divright that has same index as this_index
});
And this demo. I removed all inline function calls. I think this is a easier way.

Categories