Using "if / else" with OnClick

Firstly, is it even possible to write if / else statements directly in html with the onclick attribute? And if so, why is my code not working?

So this is the button. "Calc.Input.value" refers to text input, and I want to display an error message if this field is 0 or blank. In all other cases, I want some other things to happen, as you can see. This is not relevant, since everything after "else" worked fine before.

<INPUT TYPE="button" NAME="drop" id="dropbutton" style="background-color:#D1E8D5;" VALUE=" Släpp ankare " OnClick="if ("Calc.Input.value == ''" || "Calc.Input.value == '0'") {window.alert("Please enter a number");} else {document.getElementById('dropbutton').value=' Justera längd ';document.getElementById('length').innerHTML = Calc.Input.value;document.getElementById('dropbutton').style.cssText = 'background- color:#FFF6B3;';}"> 
+4
source share
5 answers

Just DO NOT put it in the onclick attribute.

Using

 <INPUT TYPE="button" NAME="drop" id="dropbutton" style="background-color:#D1E8D5;" VALUE="Släpp ankare "> <script> document.getElementById('dropbutton').onclick = function() { if (Calc.Input.value == '' || Calc.Input.value == '0') { window.alert("Please enter a number"); } else { document.getElementById('dropbutton').value=' Justera längd '; document.getElementById('length').innerHTML = Calc.Input.value; document.getElementById('dropbutton').style.backgroundColor = '#FFF6B3'; } return false; } </script> 
+15
source

The reason your code doesn't work is because you need to avoid quotation marks, " otherwise it will be interpreted as an HTML attribute symbol.

And I agree with others, it is a bad practice to write your inline JavaScript inside your HTML.

+4
source

sweetamylase's answer is better, but you might also think:

If your onclick = assignment is enclosed in double quotes (onclick = "..."), try using only single quotes inside these double quotes (or vice versa).

This will make things easier when you need to assign an onclick event when dynamically injecting elements and have separate script functions. This is not a good option.

Example:

 <button onclick="alert('Do this'+' and that')">Press This</button> 
+2
source

Hmm, but what about something like this:

 <a href="#" onclick="if (a_function_to_get_language() == 'en') { alert('Some message'); } else { alert('Some message in a different language'); }">Action</a> 
+1
source

Alert on the navigation page
  <script> function myFunction() { alert("You Are Not Signed In!"); } </script> 
0
source

Source: https://habr.com/ru/post/1468809/


All Articles