My checkbox My checkbox My checkbox

Click event doesn't get triggered

77 Views Asked by At

I want the user to select the entire input box when he clicks on it.

In my case the input box is:

      <label for="bla">My checkbox</label>
      <input type="input" id="bla" name="check" value="checked" />

To do this I wrote the following JS:

function SelectAll(bar){   
    bar.focus();
    bar.select();
    console.log(bar);
}    
window.onload=function()
{
   var bla=document.getElementById("bla");
   bla.addEventListener('click',SelectAll(bla),false);       
};

But all i get in the console is <input type="input" value="checked" name="check" id="bla"> once and no matter how much I click I cannot get any more.

3

There are 3 best solutions below

0
zurfyx On BEST ANSWER

addEventListener callback reference should have no parameters.

.addEventListener('click', SelectAll)

By adding (bla), it is actually being called as SelectAll(bla)(element), which is not what you want.

2
Prakhar Pandey On

Try This :

$( "#bla" ).click(function() {
     bla.addEventListener('click',SelectAll(bla),false);    
    });
function SelectAll(element){   
    element.focus();
    element.select();
    console.log(element);
} 
0
Vringar On

Summing up my research i come to the following consclusions:

addEventListener callback reference should have no parameters since it passes the event to the function.

As such the correct way to implement the listener is .addEventListener('click', SelectAll, false).

Since the event is passed but you want to work with the actual element you will need to use bar.target to access it.