Home > Net >  Using regEx to auto enable/disable button depending on characters and spaces
Using regEx to auto enable/disable button depending on characters and spaces

Time:11-29

I have been stuck on trying to create a submit button that auto enables/disables when the user types into an input box. I have successfully been able to create a submit button that starts out disabled and then enables when a user starts typing, but I want the button to disable if the user enters a number or anything else except a character or a string.

Here is the code I currently have for my script:

$(document).ready(function() {
$('#seed').on('keyup', function(){
    var regEx = /^[a-zA-Z\s]*$/;

    if($(this).val() != regEx) {
        $('#submit').prop('disabled', false);
    } else {
        $('#submit').prop('disabled', true);
    }
}); 
});

Along with my main index file with my form:

<head>
    <title>Story Ideas</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script defer src="js/script.js"></script>
</head>
    <div class="form-style">
    <form class="form" name="form" method="post" action="?v=ture">
        <label for="table">Select Your Story</label> <br />
        <select name="table" id="table">
            <option value="moons">Moons</option>
            <option value="lionbird">Lionbird</option>
            <option value="chik">Chik</option>
        </select>
        <br>
        <input type="text" id="seed" name="seed">
        <br>
        <input id="submit" type="submit" disabled="disabled">
    </form>
    </div>

    <?php
        include_once('includes/functions.php');
        if (isset($_GET['v']) && $_GET['v'] == true)
        {
            $t = $_POST['seed'];
            $table = $_POST['table'];
            echo genPoem($t, $table);
            echo "<br>";
            echo "<br>";
        }
    ?>
</body>

I tried using var regEx = /^[a-zA-Z\s]*$/; to prevent this. Have I missed something?

CodePudding user response:

You are not using the correct condition to check if your value matches the regex or not, your regex is fine just switch if($(this).val() != regEx) for if(regEx.test($(this).val())).

Reference for test method: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

CodePudding user response:

You could try $(this).val().match(regEx) instead of using !=, as documented in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

  • Related