40

This is really straight forward but I'm still fairly new to JavaScript and just found JSFiddle. I'm trying to find the element with the getElementById() to disable and enable a button. What am I missing?

<form name="frm" > 
  <div id="chkObj"> 
    <input type="checkbox" name="setChkBx" onclick="basicList.modifyAndEnableButton(this)"></input>        
</div>
<div id="Hello"> 
    <input type="button" name="btn" value="Hello"></input>        
  </div>
</form>

This is a list that I am using to add checkboxes because there is going to be more than one:

 var basicList = {
    'items': {},
    'modifyAndEnableButton': function(obj1) {
        var element = document.getElementsByName("btn");
        if (obj1.checked == true && element.getAttribute('disabled') == false) {
            element.getAttribute('disabled') = true;
            this.addRecord(obj2);
        } else if (element.getAttribute('disabled') == true) {
            if (hasItems == false) {
                element.getAttribute('disabled') = false;
            }
        } 
    }
};

http://jsfiddle.net/Arandolph0/E9zvc/3/

11
  • 7
    To downvoters, consider that currently the Google search for JavaScript click's top results are for w3schools and jQuery. I discuss this in meta here. Commented Jul 13, 2013 at 18:48
  • OP, if I were you I'd revert your edit. It makes your problem a lot more specific and a lot less applicable to the general audience, moreover, it contains a lot of syntax errors that you should probably look into and kind of ruins some of it. Commented Jul 13, 2013 at 18:52
  • dose every checkbox have a button associated with it? Commented Jul 13, 2013 at 19:03
  • No. Sorry about all the edits I realized after I posted that jsfiddle didn't save my changes and that included the code that was unedited. Please overlook. Commented Jul 13, 2013 at 19:11
  • @AprilRandolph Would you mind if I revert it to the original edit which I find more useful and generally applicable (and generally a better question)? Commented Jul 13, 2013 at 19:12

3 Answers 3

88

All browsers support this (see example here):

mySelectedElement.onclick = function(e){
    //your handler here
}

However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)

mySelectedElement.addEventListener("click",function(e){
   //your handler here
},false);

Here is a working example:

var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
    button.disabled = "true";
},false);

And html:

<button id='myButton'>Hello</button>

(fiddle)

Here are some useful resources:

Sign up to request clarification or add additional context in comments.

4 Comments

@AprilRandolph You have a typo. Please don't ask me to fix your typos in your variable names again :) You can use the Chrome developer tools to find these yourself.
@AprilRandolph Again, check my code, this is still a typo. Your event name is wrong. Again, you can use the developer tools to check which events are fired on an element . Happy coding! :)
what is false in addEventListener?
useCaptutr you can ignore it safely if you are not sure what capture is
6

Benjamin's answer covers quite everything. However you need a delegation model to handle events on elements that were added dynamically then

document.addEventListener("click", function (e) {
    if (e.target.id == "abc") {
        alert("Clicked");
    }
});

For IE7/IE8

document.attachEvent('onclick', function (e) {
    if (window.event.srcElement == "abc") {
        alert("Clicked");
    }
});

4 Comments

Sharing Knowledge :-) I try to advocate delegation so that people don't come across those nightmares on why an event is not working. It personally happened to me until I knew about it. Is there anything bad about delegation?
in addEventListener you should change e.srcElement.id to e.target.id and in attachEvent e.srcElement.id to window.event.srcElement.id
@Givi Thanks but they all worked in all the browsers. (Latest Versions, plus IE 10 in IE7/8 mode)
Gotcha! MDN says this event.target is the original element the event happened to. However, Internet Explorer calls it event.srcElement. In fact, Chrome and Safari started setting both. You can do this for maximum compatibility
3

You have a Error here

btnRush should be Rushbtn

This is a example of cross browser event's I just made (not tested) )

var addEvent = function( element, type, callback, bubble ) { // 1
    if(document.addEventListener) { // 2
        return element.addEventListener( type, callback, bubble || false ); // 3
    }
    return element.attachEvent('on' + type, callback ); // 4
};



var onEvent = function( element, type, callback, bubble) { // 1
    if(document.addEventListener) { // 2
        document.addEventListener( type, function( event ){ // 3
            if(event.target === element || event.target.id === element) { // 5
                callback.apply(event.target, [event]); // 6
            }
        }, bubble || false);
    } else {
        document.attachEvent( 'on' + type, function( event ){ // 4 
            if(event.srcElement === element || event.srcElement.id === element) { // 5
                callback.apply(event.target, [event]); // 6
            }
        });
    }

};

Steps

  1. Create a function that accepts 4 values ( self explaining )
  2. Check if the browser supports addEventListener
  3. Add event on the element
  4. else add event on the element for older IE
  5. Check that the (clicked) element is = to the passed element
  6. call the callback function pass the element as this and pass the event

    The onEvent is used for event delegation. The addEvent is for your standard event.

    here's how you can use them

The first 2 are for dynamically added elements

onEvent('rushBtn', 'click', function(){
    alert('click')
});

var rush = document.getElementById('rushBtn');

onEvent(rush, 'click', function(){
    alert('click');
});

// Standard Event
addEvent(rush, 'click', function(){
    alert('click');
});

Event Delegation is this basically.

Add a click event to the document so the event will fire whenever & wherever then you check the element that was clicked on to see if it matches the element you need. this way it will always work.

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.