Please disable your adblock and script blockers to view this page
 

jQuery to check string as mathematical expression valid or not?

Introduction: In this article I am going to explain how to validate whether a string as a mathematical expression valid or not using Javascript’s eval() function. 
jQuery to check string as mathematical expression valid or not

Description: The eval() function evaluates or executes an argument.

Syntax: eval(string)

If the argument is valid expression, eval() evaluates the expression otherwise it will throw exception. We can use try/catch block to check whether expression is valid or not as shown in example below.

Implementation: Let’s understand by an example.
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        function ValidateExpression() {
            var expression = $('#txtExpression').val().trim();
            if (expression != '') {
                try {
                    var result = eval(expression);
                    $('#spnMessage').html('Expression in Valid and Result is: ' + result);
                }
                catch (e) {
                    $('#spnMessage').html('Expression in invalid.');
                }
            }
            else {
                $('#spnMessage').html('Please enter expression.');
            }
        }      
    </script>
</head>
<body>
    <input type="text" id="txtExpression" />
     <button type="button" onclick="ValidateExpression();">Submit</button><br /><br />    <span id="spnMessage"></span> 
</body>
</html>

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon