Listener CheckBox

0

I'm doing a js that responds to when I click on a checkbox:

function actionCheckbox(){
    var chkAp = document.getElementById("ahorroAP");
    var chkCa2 = document.getElementById("ahorroCa2");
    var chkAhorro = document.getElementById("ahorroDep");

    if(chkApv.value){
        agregarAp();    
    }else if(chkCta2.value){
        agregarPlanCa2();
    }else if(chkAhorroDeposito.value){
        agregarAhorroDep();
    }else{
        cleanfields();
    }           
}

The problem is that when I click on the second chkbox savingCa2, only the first if is executed.

Goal

My goal is to make a listener that gets the click event of any of those 3 checkboxes so that the corresponding% if is executed.

    
asked by Stevn 14.12.2016 в 15:58
source

2 answers

0

You can try that, since you need any of those 3 checkboxes, the last else I see unnecessary.

function handleClick(cb) {
  if(cb.id == 'ahorroAP' && cb.checked){
  	 //agregarAp(); 
     console.log("primer checkbox");
  } else if(cb.id == 'ahorroCa2' && cb.checked){
  	//agregarPlanCa2();
     console.log("segundo checkbox");
  } else if(cb.id == 'ahorroDep' && cb.checked){
  	 //agregarAhorroDep();
     console.log("tercer checkbox");
  }
}
<input type="checkbox" onclick='handleClick(this);'  id="ahorroAP"> ahorroAP<br>
<input type="checkbox" onclick='handleClick(this);'  id="ahorroCa2"> ahorroCa2<br>
<input type="checkbox" onclick='handleClick(this);'  id="ahorroDep"> ahorroDep<br>
    
answered by 14.12.2016 в 16:12
0

The response of the user siosi is valid and functional but if you would like to solve it without modifying your markup you could do it in the following way:

function actionCheckbox(){
    var chkAp = document.getElementById("ahorroAP");
    var chkCa2 = document.getElementById("ahorroCa2");
    var chkAhorro = document.getElementById("ahorroDep");

    if(chkAp.checked){
        agregarAp();    
    }else if(chkCa2.checked){
        agregarPlanCa2();
    }else if(chkAhorro.checked){
        agregarAhorroDep();
    }else{
        cleanfields();
    }           
}

In case you want this to work for more than one checkbox at a time you should modify the conditional as follows:

function actionCheckbox(){
    var chkAp = document.getElementById("ahorroAP");
    var chkCa2 = document.getElementById("ahorroCa2");
    var chkAhorro = document.getElementById("ahorroDep");
    var executed = false;
    if(chkAp.checked){
        agregarAp();    
        executed = true;
    }
    if(chkCa2.checked){
        agregarPlanCa2();
        executed = true;
    }
    if(chkAhorro.checked){
        agregarAhorroDep();
        executed = true;
    }

    if (executed == false){
        cleanfields();
    }
}
    
answered by 16.12.2016 в 18:13