jQuery - both if else statements executing on page load -


edit: both if else statements executing. - have table buttons in it. on page load, if label of button 'hello', want change else. have if-else statement time, both if else statements being executed. not wrong here.

 $(document).ready( function() {     if($('button').val() == "hello" ) {       alert("hello in if");       $(this).removeclass('btn-danger');       $(this).addclass('btn-primary');       $(this).text('ifif');     }     else {      alert("hello in else");      $(this).removeclass('btn-primary');      $('button').addclass('btn-danger');      $('button').text('elseelse');     }   }); 

everytime, label of button changes elseelse when initial label of button 'hello'. first goes inside if , changes label ifif , goes inside else too.it works fine if put in click event function. on page load not work correctly.

your responses appreciated.

thanks

you should using text() method, not val() method button's text. also, please note $('button') select buttons in page, wich not want.

$('button').text() == "hello" 

additionnaly, noticed using $(this) in document ready handler, wich seems wrong, because this won't reference button. should like:

$(document.ready(function () {     var $btn = $('#your_button_id');      if ($btn.text() === 'hello') {         $btn.removeclass('btn-danger');         //...     } }); 

"actually want buttons selected."

according these different requirements, here's do:

http://jsfiddle.net/wpjpv/1/

html

<button class="btn-danger">hello</button> <button class="btn-danger">hello</button> <button class="btn-danger">hello></button> <button class="btn-danger">hello></button> <button class="btn-primary">yo</button> 

js

$(function () {     var classes = 'btn-danger btn-primary';      $('button:not(:contains(hello))').toggleclass(classes).text('elseelse');     $('button:contains(hello)').toggleclass(classes).text('ifif');  }); 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -