Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "if/else" with OnClick

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;';}">
like image 279
NollProcent Avatar asked Mar 12 '13 19:03

NollProcent


People also ask

Can you put an if statement in Onclick?

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.

Can Onclick run 2 functions?

Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.

How do you use if else?

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.

How does if Else statement work?

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.


1 Answers

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>
like image 173
kay Avatar answered Sep 18 '22 21:09

kay