First of all, is it even possible to write if/else statements directly in html with onclick attribute? And if so, why is my code not working?
So this is a button. The "Calc.Input.value" refers to a text input and I want to display an error message if that field is 0 or blank. In all other cases I want some other things to happen as you can see. This is not relevant though, as everything after the "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;';}">
Example If statement: When the user clicks any of the radio buttons, we use the onclick event handler to call the analyzeColor1() function. When we call that function, we pass in the value of the radio button (using this. value ). The function then takes that value and performs an if statement on it.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.
Just DON'T put it in the onclick attribute.
Use
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With