Home > Software design >  How to retrieve and modify textbox values with jQuery inside a php loop
How to retrieve and modify textbox values with jQuery inside a php loop

Time:10-26

I want to provide a restriction to input fields inside a PHP loop, so that in each of the looped input fields, a user can not insert a value greater than 100. If the value is greater than 100, the user will be alerted that the value is greater than 100 and the field will be reset to empty ("") so that he can write the correct value. My issue is that the code only functions for the first input field and not for the rest of the loop.

Here is what I have tried.

while ($row = mysqli_fetch_array($query)) {
    echo "<label>Name</label>
    <input type='text' class='form-control' name='name' id='name' value='".$row['name']."' />";
    echo "<label>Score</label>
    <input type='text' class='form-control' name='score' id='score' value='' />";
}


$(document).ready(function(){
$("#score").keyup(function(){                
    var score=$(this).val();
    if (score > 100) {
        alert("Score cannot be greater than 100");
        $('#score').val("");
    }
});

});

CodePudding user response:

Please try this

php:

while ($row = mysqli_fetch_array($query)) {
    echo "<label>Name</label>
    <input type='text' class='form-control' name='name' id='name' value='".$row['name']."' />";
    echo "<label>Score</label>
    <input type='text' class='form-control score' name='score' id='score' value='' />";
}

js:

    $(document).ready(function(){
        $(".score").keyup(function(){                
            var score=$(this).val();
            if (score > 100) {
                alert("Score cannot be greater than 100");
                $(this).val("");
            }
        });
    });
  • Related