Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve and modify textbox values with jQuery inside a php loop

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("");
    }
});

});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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("");
            }
        });
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading