user1592380
user1592380

Reputation: 36205

Javascript else if statement not working

I have the following:

HTML

<div class="tab-pane" id="message">
      <textarea rows="4" cols="50" id="send_message" placeholder="Enter text ...">  </textarea>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">OK</a>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">Cancel</a>

JavaScript

$('#message').click(function(){
    if($("a", this).is(":contains(OK)")) {
        console.log("im in OK!!");
    } else if($("a", this).is(":contains(Cancel)"))  {
        console.log("im in cancel!!");
    }
});

This works fine when I hit the OK button and executes as expected, however when I hit cancel the code in OK is executed only. The cancel code never executes! What am I doing wrong?

Upvotes: 1

Views: 909

Answers (3)

gen_Eric
gen_Eric

Reputation: 227190

this is the element the event is bound to. It's always #message, therefore $("a", this) will always be the both buttons. .is will scan both buttons to see if any of them contain "OK". The first one does, so it always goes to the 1st block.

You should be binding the events to the buttons themselves, not the entire div.

Upvotes: 9

Greeso
Greeso

Reputation: 8219

Fist, I noticed you have a missing closing div (</div>)

Just curious, why not do the following:

$("#OK").click (function() {
    console.log("im in OK!!");
});

$("#Cancel").click (function() {
    console.log("im in Cancel!!");
});

<div class="tab-pane" id="message">
    <textarea rows="4" cols="50" id="send_message" placeholder="Enter text ...">  </textarea>
    <a href="#message" id="OK" class="btn btn-large btn-info"  data-toggle="tab">OK</a>
    <a href="#message" id="Cancel" class="btn btn-large btn-info"  data-toggle="tab">Cancel</a>
</div>

Cheers.

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113335

Detect clicks on a from #message, instead. this will become the clicked <a>.

$('#message').on("click", "a", function(){
    if($(this).is(":contains(OK)")) {
        console.log("im in OK!!");
    } 
    else if($(this).is(":contains(Cancel)"))  {
            console.log("im in cancel!!");
    }
});

JSFIDDLE

Upvotes: 2

Related Questions