function executed twice after checkbox checked - javascript

I use the below code
$("#cc1").unbind('click').click(function(e) {
//somefunction
});
in order to execute a function after cc1 button is clicked. With this code everything works great.
When I use the below code
$("#cc1").unbind('click').click(function(e) {
if($('#cc').is(':checked')){
}
//somefunction
});
in order to execute the same function as above but when cc checkbox is checked and button pay is clicked the function is executed more than once and I receive errors in db reading...
What is the problem?
when pay button is clicked the app passes some vars to a function in order to update - import data into a db. If cc is checked the app passes different data.
The above page contains a button (pay) that when is pressed the payment is made by cash. If cc is checked the payment is made by credit card.

According to your description, may be the following code can help you:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div>
<form id="form">
<input type="button" name="cc1" value="cc1" id="cc1">
<input type="button" name="pay" value="pay" id="pay">
<input type="checkbox" name="cc" id="cc">
</form>
<script>
$("#cc1").unbind('click').click(function(e) {
//somefunction
alert("test cc1");
});
$("#pay").unbind('click').click(function(e) {
if($('#cc').is(':checked')){
//somefunction
alert("credit");
}
else{
//anotherfunction
alert("cash");
}
});
</script>
</body>

This problem would appear if you have a dynamic listener being bound & this condition happens. This would trigger 2x clicks, as the 2nd listener doesn't have an unbind on it. These clicks stack.
HTML:
<input type="checkbox" id="cc1"> Double Click<br>
<input type="checkbox" id="cc2"> Single Click
JS: jsfiddle
// Static Listener
$("#cc1").unbind('click').click(function(e) {
checkClicked($(this));
});
$("#cc2").unbind('click').click(function(e) {
checkClicked($(this));
});
/* Dynamic Listener - Typically happens when Ajax data is being loaded,
* DOM nodes are being added & listeners are being re-attached to the
* new form fields:
*/
$("#cc1").click(function(e) { // .unbind('click')
checkClicked($(this));
});
$("#cc2").unbind('click').click(function(e) {
checkClicked($(this));
});
function checkClicked(chkBx) {
console.log('clicked');
if(chkBx.prop('checked')){
console.log('isChecked: yes');
} else {
console.log('isChecked: no');
}
}
So make sure that your code doesn't have incorrect dynamic listeners being attached to it. If .unbind('click') is added to the 2nd dynamic listener, then it'll only have 1 click action.
Oh, btw: .is(':checked') doesn't work in jQuery. You'll have to use .prop('checked') to get the true/false condition on the checkbox.

Related

How to enable/disable a button via checkbox and keep the button active or inactive after refreshing the page

I have a button and I want to do the following
Disable this button by clicking on the checkbox that refers to it
Keep it disabled even after refreshing the page
Do the same, but instead. The button is disabled and now I would like to enable it again by clicking on the checkbox that references it keeping it that way after refreshing the page
I found two references that do exactly what I need, but I don't know how to put the two solutions together. This and this
HTML code
<div id="billing">
<input type="checkbox" id="billing-checkbox" checked>
<input type="button" value="Hello Javascript!">
</div>
Javascript code
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('billing-checkbox').onchange = toggleBilling;
}, false);
function toggleBilling() {
var billingItems = document.querySelectorAll('#billing input[type="button"]');
for (var i = 0; i < billingItems.length; i++) {
billingItems[i].disabled = !billingItems[i].disabled;
}
}
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
Thank you so much!
This will give a script error in the snippet, probably because it is a sandbox and doesn't allow for localStorage. But this is tested and works. See comments in the code for explanations. You can set the checkbox on or off and when you refresh the page, it will 'remember' it's state
$(document).ready(function() {
// first thing is to set the checkbox based on the localStorage key that we may have set in the past
$('#billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled");
// then we run our toggle billing
toggleBilling()
// we set up our change handler.
$('#billing-checkbox').on('change', toggleBilling);
});
function toggleBilling(e) {
// we set the disabled based on the check button status
$('#billing input[type="button"]').attr('disabled', !$('#billing-checkbox').prop('checked'))
// we set the localStorage based on the button disabled
localStorage.setItem('buttonDisabled', $('#billing input[type="button"]').attr('disabled'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="billing">
<input type="checkbox" id="billing-checkbox" checked>
<input type="button" value="Hello Javascript!">
</div>

Jquery - Stop Event of Other Class

This is what I want
Jquery:
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
alert();
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
Why I am doing this
Upper class is different for all buttons
But loader class is same for all buttons it shows loader inside clicked button
I found
e.stopPopagation();
But that works if I use it in loader click callback But I want to stop when button is clicked and url is empty
Cannot check url=="" inside loader click call back cause it is same for all button i dont want to check on other buttons click too so checking for single button
I would recommend using classes to check for condition.
$("body").on('click','.js-loader',function(){
var _this = $(this)
if(_this.hasClass('js-loader') && _this.hasClass('js-validate-url')){
// if both classes js-loader, js-validate-url are present on button
alert()
}else{
alert("js-loader") // if only js-loader present on button
}
});
I'm not sure if I understand what you are trying to do, but I guess you can merge your events into a single one and use an external function only when it met a condition.
You could also use removeEventListener but I don't believe you need it for your problem.
var myFunction = function(){
alert('loader');
};
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if (url){ alert('validate: '+url); }
else myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="google.com" class="url"/>
<button class="js-validate-url js-loader">Bt1</button>
<button class="js-loader">Bt2</button>
This is what I did and is working fine as per my requirement
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
$(this).removeClass("js-diable");
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-scud-disabled')){
//NOTHING TO DO
}else{
alert();
}
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url js-disable"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-loader js-validate-url')){
alert();
} else {
if(url==""){
} else {
}
}
});

condition on radio button onclick, if false don't check

onclick of one radio button i have to check one condition if true i have to check it or restore to same old status,
html
<input type="radio" name="test" id="radio0" onclick="myFunction()" checked />
<input type="radio" name="test" id="radio1" onclick="myFunction()" />
<input type="radio" name="test" id="radio2" onclick="myFunction()" />
JS
globalCondition = false;
function myFunction()
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
As I said in comment return in the function will not do anything as you're not returning the function value in the in-line code.
Although the other solutions offered are correct, to keep your code unobtrusive, you should not have inline JS at all (remove the onclick='s).
I realize the question was not tagged jQuery, but maybe it should have been: Instead on onclick you should use a jQuery event handler, selecting only the set of radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/KVwL3/1/
globalCondition = false;
$(function(){
$("[name=test]").click(function(e){
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false;
// or
e.preventDefault();
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
});
});
Notes:
DOM ready event:
$(function(){ YOUR CODE HERE }); is a shortcut for $(document).ready(function(){ YOUR CODE HERE});
Selectors
If an attribute [] selector = value contains special characters it needs to be quoted:
e.g.
$('[name="IstDynamicModel[SD_WO_CREATE]"]')
There are any number of selectors that will choose just the three radio buttons. As this is a simple one-off connection, at startup, there is no real speed difference between any options, but you would normally try and make the selector specific in ways that might make use of various lookup tables available to the browser:
e.g.
$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')
This will be slightly faster as it will reduce the slowest check (the name=) to only radio inputs.
try this:
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
e.preventDefault();
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
USe like this
<input type="radio" name="test" id="radio1" onclick="return myFunction()" />
javascript
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
return true;
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}

use button to write text to the page

I can do this with a alert but I want to print the results of a function directly to the web page.
When the user clicks the car button I want the results from the car() function to write into my id="mainContent" div.
if the user clicks the Ice Cream button I want the results from the ice cream button to replace what ever is in the mainContent div with the results from the iceCream() function
var mainContent = document.getElementById('mainContent');
carButton.onclick = function() {
mainContent.appendChild(document.createTextNode(car()));
}
Assuming you have some code like this:
<form id="ice_cream_form" action="fake" method="post">
<input type="submit" value="Ice Cream" />
</form>
You could use some JavaScript code like this:
var form=document.getElementById("ice_cream_form");
var mainContent=document.getElementById("mainContent");
if(form.addEventListener) {
form.addEventListener("submit", submitted, false);
}else if(form.attachEvent) {
form.attachEvent("onsubmit", function() {
return submitted(window.event);
});
}
function submitted(event) {
if("textContent" in mainContent) {
mainContent.textContent=iceCream();
}else{
mainContent.innerText=iceCream();
}
event.preventDefault();
event.stopPropagation();
return false;
}
If iceCream returns HTML you want to display rather than plain text you want to display, you'll probably want to replace the part that changes textContent to just set innerHTML.
Alternatively, you could use inline event handlers (although I don't really like this method because it mixes content and behavior):
<input type="button" value="Ice Cream" onclick="document.getElementById('mainContent').textContent=iceCream(); return false;" />
When, for example, the car button is clicked, this code should be run:
document.getElementById("mainContent").appendChild(
document.createTextNode(car())); /* ← there is the magic */
If you don’t know how to register this function to be launched in case of clicking the button.
Then do it like this:
var button = document.getElementById("idOfTheButton");
button.addEventListener("click",
function()
{
document.getElementById("mainContent").appendChild(
document.createTextNode(car()));
}, 1);
Adapt this code appropriately for the other button and it will work too.

How do I check if a checkbox is checked with JQuery?

I am trying to allow a click function if the user has checked a checkbox on the page. Otherwise, I want to add a class to the #additional_foreign button.
I think I am close, but it doesn't seem to be working.
Here is my code:
if($('#foreign_checkbox').attr('checked')) {
$('#additional_foreign').click(function() {
alert('This click function works');
});
} else {
$('#additional_foreign').addClass('btn_disable');
}
When I check the checkbox, it doesn't allow the click function and when I uncheck the checkbox, it also doesn't add the class as it should.
What am I doing wrong?
EDIT:Here is my HTML for clarification.
<input id="foreign_checkbox" type="checkbox" />
<span id="additional_foreign">Click Me</span>
try using $('#foreign_checkbox').is(":checked") - rest of the code looks fine
If this was my code I'd do something like this to make it work:
<input id="foreign_checkbox" type="checkbox" />
<span style='display:none' id="additional_foreign">Click Me</span>
<script type="text/javascript">
$(document).ready(function() {
$("#foreign_checkbox").click(function() {
if($('#foreign_checkbox').is(':checked')) {
$('#additional_foreign').show();
} else {
$('#additional_foreign').hide();
}
});
$('#additional_foreign').click(function() {
alert('This click function works');
});
});
</script>
The problem is that the code doesn't run continually, only when the page loads, when all the boxes are unchecked. You need an action that fires when the box is checked or unchecked, which adds an action or a class to the button:
$('#foreign_checkbox').change(function(){
if (this.checked){
$('#additional_foreign').click(function() {
doSomething();
});
} else {
$('#additional_foreign').addClass('btn_disable');
}
});

Categories