Javascript: checkbox onchange/onclick function not working - javascript

I have this function for my computation that whenever the text fields are populated, it will add a stack to a variable and whenever a checkbox is checked on the text field, the text field wont add a value.
everything is working except the checkbox function, I already tried onchange and onclick but nothing happens. Can you check my codes?
Script:
function submission(){
x = 19;
ctr = 1;
ctr2 = 0;
days = ('<?php echo $query[0]->totaldays; ?>') - 1;
$('#payment').html('');
for(i = 1; i<=x ; i++){
if($('#guest'+i).val() != ""){
ctr++;
}
if(document.getElementById('kid'+i).checked){
ctr2++;
}
}
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseInt(ctr) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);
}
HTML:
<div class="row">
<div class="col-sm-10">
<label for="exampleInputtext1"><a style = "color:black; font-size: 10px;" ><input onchange="submission()" type="checkbox" name="kid1" id="kid1" > </a>Guest 1:</label>
<input type="text" class="form-control" onblur="submission()" name="guest1" id="guest1"/>
</div>
</div>

The onclick event handler will work for checkbox,you can try this code,
HTML:
<input onclick="submission(this)" type="checkbox" name="kid1" id="kid1" >
JS:
And you can check and see whether the checkbox is checked or not using the following code,
function submission(click){
....
var clicked=click.checked;
...
}
if it is true that means the checkbox has been checked and if it is false it has not been checked.

$("#guest1").change(function() {
if(this.checked) {
//Do this.
}
else{
// Do this.
}});
don't need to mention onclick function on html. just add this code in JS.
its calling auto based on id.
let me know if you need any help in understanding.
Ajay

thanks for your answers, it seems like I just messed up a little bit on my mathematical equation.
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseFloat(totalCount) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);

Related

Why my logic is wrong? Checkbox and line-through

I am a newbie in JS. Just want help to figure out why my logic is wrong, when I try to change the style of the text when the checkbox.checked === true.
Here is the code.
JS:
var c = document.getElementById("cbx");
var l = document.getElementById("cbxtxt");
if ( c.checked === true ) {
l.style.textDecoration = "line-through";
}
HTML:
<html>
<head></head>
<body>
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>
//<script type="text/javascript" src="cbx_test.js"></script>
</body>
</html>
Thanks in advance!
You need to wrap your logic in an event listener so that it runs every time the checkbox is checked / unchechecked. Also, you probably want to handle what happens when the checkbox is unchecked.
var c = document.getElementById("cbx"); // for checbox
var l = document.getElementById("cbxtxt"); // for label
c.addEventListener("change", function() {
l.style.textDecoration = c.checked ? "line-through" : "none";
})
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>
To explain this line:
l.style.textDecoration = c.checked ? "line-through" : "none"
As others have said c.checked === true isn't really necessary, as you can just directly use c.checked as your condition. To make the code a bit more concise, I use the conditional operator (?:) instead of a an if / else.
Finally, just to demonstrate how #A. Wolff's suggestion of using pure CSS would work:
#cbx:checked~label {
text-decoration: line-through;
}
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>
You need to subscribe to checkbox's change event, otherwise your code only runs once when the <script> element is parsed.
Consider this:
var c = document.getElementById("cbx"); // for checbox
var l = document.getElementById("cbxtxt"); // for label
c.addEventListener('change', function(evt) {
//this anonymous function will run each time the checkbox changes state
if (c.checked === true) {
l.style.textDecoration = "line-through";
} else {
l.style.textDecoration = "";
}
});
you need to add event listener
var l = document.getElementById("cbxtxt"); // for label
var c = document.getElementById("cbx"); // for checbox
c.addEventListener('change', (event) => {
if (event.target.checked) {
console.log('checked')
l.style.textDecoration = "line-through";
} else {
console.log('not checked')
l.style.textDecoration = "blink";
}
})
You would rather use classes instead of id attributes.
I guess you'll need to display different checkboxes, that in your case must have different ids (the same id is not recommended on the page).
That's why you can use my snippet to figure out how to work with multiple checkboxes.
var checkboxes = document.querySelectorAll(".my-form .my-custom-checkbox-class"); // Search all checkboxes in the form
for (var checkBox of checkboxes) {
checkBox.addEventListener("change", onCheckboxChangeHandler, false); // Add event listener to each checkbox
}
function onCheckboxChangeHandler(e) {
var clickedCheckbox = this
var formGroupContainer = clickedCheckbox.closest('.form-group'); // Find closest parent element with class .form-group
var label = formGroupContainer.querySelector('.my-custom-lbl-class'); // Find label closest to clicked checkbox
label.style.textDecoration = clickedCheckbox.checked ? "line-through" : "none"; //Do everything you need with styles
}
.my-form {
padding: 20px;
}
.form-group {
padding: 5px 10px;
font-size: 18px;
}
<div class="my-form">
<div class="form-group">
<input type="checkbox" id="cb1" class="my-custom-checkbox-class">
<label for="cb1" class="my-custom-lbl-class">Waterfall</label>
</div>
<div class="form-group">
<input type="checkbox" id="cb2" class="my-custom-checkbox-class">
<label for="cb2" class="my-custom-lbl-class">River</label>
</div>
</div>

Javascript: Triggering "for" loop using "if...else" statements not working

I am trying to make a simple script which automatically blocks the input boxes in the file when I tick a checkbox.
For this, I am trying to add/remove the "disabled" attribute by triggering a loop every time the checkbox is clicked. Looks something like this:
function locker() {
var boxes = document.querySelectorAll("input[type='text']");
var x = getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
boxes[i].disabled = true;
} else {
boxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
However, I can't seem to get it to work. I don't have much experience coding, and I feel like I am making a very basic mistake, but I couldn't find a solution to this problem so far... How can I solve this? Are there any other workarounds to get the same result?
Thanks in advance
You need to use document.getElementById("lock") instead of getElementById("lock") and use the correct variable names for your variables. You used inputBoxes and boxes while you meant to use the same variable.
function locker() {
var inputBoxes = document.querySelectorAll("input[type='text']");
var x = document.getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
inputBoxes[i].disabled = true;
} else {
inputBoxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>

Run function on input change and checkbox change

I have a Bootstrap modal with multiple forms in it. All the forms have an input field and checkbox. I try to run a function update_amounts_modal every time a change event takes place. This working when I change the input value but doesn't work when I check/uncheck the checkbox.
UPDATE I'VE CREATED A FIDDLE HERE
The function:
function update_amounts_modal(){
var sum = 0.0;
$('form').each(function() {
var qty = $(this).find('.qty input').val();
var price = $(this).find('.price input').val();
qty= parseInt(qty) || 0;
price= parseFloat(price) || 0;
var amount = (qty*price)
sum+=amount;
});
$('.total-modal').text('€'+sum.toFixed(2));
}
The change function:
update_amounts_modal();
$('form .qty').change(function(){
update_amounts_modal();
$('.total-modal').change();
});
HTML:
<form method="post" data-target="#modal" data-async="" action="action_url">
<div class="qty cell">
<input type="text" class="qty" value="1" name="quantity">
</div>
<div class="price cell">
<span class="euro">€</span><input type="text" disabled="" class="price" value="0.60">
</div>
<div class="checkbox cell">
<input type="checkbox" checked="" value="12933006" name="product[]" class="idRow">
</div>
</form>
//And more forms exactly like this but with different input values!
<div class="total-modal">€0.00</div>
What actually needs to happen is that by checking/unchecking the value needs to be recalculated with the function. So if you have set qty to 10 and you uncheck the checkbox then this amount (10x eg. €0.25) must be deducted from the total.
I thought something like this should work but that isn't:
$(".idRow").change(function(){
if($(this).attr("checked")){
update_amounts_modal();
}
else{
update_amounts_modal();
}
I don't get an error there's just nothing happening. Is there a better way to accomplish this?
I'm not sure figure out your question correctly or not but i think you are looking for something like this:
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text('€' + sum.toFixed(2));
}
$().ready(function () {
update_amounts_modal();
$('form .qty, form .idRow').change(function () {
update_amounts_modal();
});
});
Check JSFiddle Demo
Update:
If in some forms you don't have a CheckBox (in other words some prices aren't optional) so you have to check that CheckBox exist or not and if exist, so check that is checked or not.
in order to do that, modify the update function like this:
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var checkbox = $(this).find('.idRow');
if (checkbox.prop("checked") || checkbox.length == 0){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text('€' + sum.toFixed(2));
}
in this line: if (checkbox.prop("checked") || checkbox.length == 0){ we say that sum the value if checkbox is checked (checkbox.prop("checked")) or there is no CheckBox (checkbox.length == 0).
Check JSFiddle Demo
Try this : Instead of attr use prop
$(".idRow").change(function(){
if($(this).prop("checked")){
update_amounts_modal();
}
else{
update_amounts_modal();
}
});
u can do
<div class="checkbox cell">
<input type="checkbox"/>
</div>
jQuery("div.checkbox > input:checkbox").on('click',function(){
alert('asdasd');
});
http://jsfiddle.net/1r7rk21w/
If you expect the values to update based on the checked property, then your sum function needs to actually use that check box right?
JS:
$('form').each(function () {
if ($(this).find(".idRow").prop("checked") === true){
//
// The normal computations you had before...
//
}
});

Only one checkbox selected

I have a checkbox Yes and No so i want to user only able to use one. So if user tick Yes then No will cleared if Yes then no will clear
<input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "Yes" ? " checked" : "")/>Yes
<input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "No" ? " checked" : "")/>No
<script>
function selectOnlyThis(id) {
for (var i = 0; i <= 4; i++) {
document.getElementById("Check" + i).checked = false;
}
document.getElementById(id).checked = true;
}
</script>
The problem is that you are trying to access elements that do not exist
your loop goes from 0 to 4 but your elements are Check1 and Check2
So when it tries to set the checked property of Check0 (which does not exist) it throws an error and stops execution..
Use
function selectOnlyThis(id) {
console.log(id);
for (var i = 0; i <= 4; i++) {
var element = document.getElementById("Check" + i); // get element
if (element){ // if element was found only the set its checked property
document.getElementById("Check" + i).checked = false;
}
}
document.getElementById(id).checked = true;
}
Demo at http://jsfiddle.net/gaby/RHUVf/
or if your example html is the actual one you could just change your loop to
for (var i = 1; i <= 2; i++) {
As mentioned by others, you are describing the behavior of a radio button. However, it is possible to make a checkbox behave like this also.
jsFiddle demo
$('input:checkbox').click(function(){
$('input:checkbox').not($(this)).prop('checked',false);
});
The above code does the following:
$('input:checkbox') - selects all input elements of type checkbox
.not($(this)) - except this one
.prop('checked',false) - unchecks the checkbox
This code uses the jQuery javascript library, so you must reference this library (usually in the head tags of the document), thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
It would be a lot more helpful/easier to use HTML5 for this part
IF you choose HTML5 the following code WILL work but if you decide not to use it It wont help.
<input type="checkbox" name="<name>" value="<value"><*explanation*><br/><br/>
</form>
</div>
</div>
</body>

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

Categories

Resources