JavaScript | Example of Ternary Operator

JavaScript | Ternary Operator Example: Here, we are going to learn about Ternary Operator with an Example.
Submitted by Pankaj Singh, on October 17, 2018

Example:

Here, we are inputting age of the person and checking whether person is eligible for voting or not in JavaScript?

JavaScript code (along with HTML):

<!DOCTYPE html>

<HTML>
    <HEAD>
        <SCRIPT>
            function Check(){
                var age=parseInt(document.getElementById("txtage").value);
                var status = (age>=18)?"Eligible":"Not Eligible";
                document.getElementById("ans").innerHTML=status;
            }
        </SCRIPT>
    </HEAD>
    <BODY>
        <h2>Ternary Operator</h2>
        <hr />
        <table>
            <tr>
                <td>
                    <label>Enter Age:</label>
                </td>
                <td>
                    <input type="text" name="txtage" id="txtage" />
                </td>
            </tr>
            
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    <input type="button" value="Check Vote Eligiblity" onclick="Check()" />
                </td>
            </tr>
             <tr>
                <td>
                    <label>Status</label>
                </td>
                <td>
                    <span id="ans">
                    
                    </span>
                </td>
            </tr>
        </table>
    </BODY>
</HTML>

Output

JS | Ternary Operator in JS

JavaScript Examples »





All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.