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);
                        }

Recommended Answers

All 4 Replies

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

now

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

replace on

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

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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.