Unable to apply proper if condition | SoloLearn: Learn to code for FREE!

+1

Unable to apply proper if condition

Edit: I have put the code below. Please kindly help as much as you can. I will be grateful https://code.sololearn.com/W6I2TCWqa5En/# I wrote the following **if condition** so that if the the td is empty the innerHTML should be '0'. But even when the innerHTML is "X" and not ''(empty), it still change the (X) to 0. The first condition that turn it to X is: ``` if(w==2 && zero.innerHTML==''){ zero.innerHTML='X'; w=1; } else if(w==2 && one.innerHTML==''){ one.innerHTML='X'; w=1; } else if(w==2 && two.innerHTML==''){ two.innerHTML='X'; w=1; } ``` But still: ``` if(w==1 && zero.innerHTML==''){ zero.addEventListener('click',function(){ zero.innerHTML='O'; w=2; }) } if(w==1 && one.innerHTML==''){ one.addEventListener('click',function(){ one.innerHTML='O'; w=2; }) } if(w==1 && two.innerHTML==''){ two.addEventListener('click',function(){ two.innerHTML='O'; w=2; }) } ``` Changes it to 'X' to '0'. Please any help will be appreciated

5/23/2020 5:21:17 PM

maleeqB

7 Answers

New Answer

+1

Would be good to have the complete code as playground Link, to test it and check if there are other influences. Nevertheless, I'll just guess... With the second block you add handlers to the fields which are empty. You probably do that before every move of a user? That means that also fields which are filled with an 'X' later in the match, still contain this handler (even multiple times). Instead you should add a handler once in the beginning, checking for (w == 1 && {field}.innerHTML == '') before setting values.

+2

THANK SO MUCH BOSS. I AM GRATEFUL

+1

Alright, adjusted what I've mentioned and in addition changed the multiple if-statements to loops. https://code.sololearn.com/We2qrxSDHn22/?ref=app

+1

You are welcome

0

Please any advise for me? I need help/tip on how to write clean and precise code. I wrote that error code(with too many if statements) in more than 140 lines, you wrote a better variation of it in less than 70 lines

0

Maybe first one thing regarding this code: When you write the same stuff again and again get your head around the question, if you should make your code reusable (e.g. via loop, function or class). There is one well-known rule called DRY (Don't Repeat Yourself). But be aware to do not go to the other extreme. https://www.codementor.io/@joshuaaroke/dry-code-vs-wet-code-89xjwv11w Also have an eye on the SOLID principles. http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/

0

Thanks, would check the links out