Home » JavaScript

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.