0

Hi there,

am I doing something wrong with the if-statement? it either doesn't evaluate the conditions I've got in there or throw an error.

                $('button').click(function(){

                        var button = $($(this)).text();                     
                        console.log(button);   // this logs the value of button as night or day depending on the button I click

                        if(button == 'day'){
                            $('p').text(button);

                        }else if(button == "night"){
                            $('p').text(button);
                        }
3
Contributors
4
Replies
5
Views
4 Years
Discussion Span
Last Post by AleMonteiro
0

In 3 line you have error. You wrong get current element.

now

var button = $($(this)).text(); 

replace on

var button = $(this).text(); 
0

var button = $($(this)).text(); this works fine. but the problem with the if-statement.

2

Oh, I know why this is not evlauting because of the space I got in the button name

<button> day</button> != <button>day</button>

it looks exactly the same but the space needs to explicitly speicified in the condition.

0

Hello.

$($(this)).text() works but it's redundant. $(this) work as well and it's better for performance and code understanding.

About the white space, you can use the trim function: var text = $.trim($(this).text());
It will remove any extra white spaces.

And I'd also change <button>day</button> to <button id="btnDay" type="button">day</button>. And add the click handler as $("#btnDay").click(function{...});

Using type="button" will prevent any forms to be submited by mistake. By default, a button is of type submit, and this means that if the button is inside a form, it'll submit the form when clicked.

Using the ID btnDay will only add the click handler to btnDay button. Using the tag button will add the handler to all buttons of the page.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.