doubu4826 2016-05-24 23:26
浏览 45
已采纳

如何使用Javascript来验证动态生成的PHP表单?

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:

<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){

    $title  = $newArray['title'];
    $length = $newArray['length'];
    $description = $newArray['description'];
    $image = $newArray['image'];

    //Echo statements will display query results on screen.

    echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
    echo "<td><image src=\"$image\"</td>";
    echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";

}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
//  echo "Select it.";
//}


?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>

As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:

<script>
function validate(){
    var radio = document.getElementById('wanted').checked;

    if(radio=="")
    {
        alert("Please select a film to continue making a booking.");
        return false;
    }
    return true;

}

</script>

The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?

  • 写回答

2条回答 默认 最新

  • dongsi4815 2016-05-24 23:46
    关注

    This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
    An Id should be unique.... So it's a bad practice.

    Remove the id and add a class instead:

    echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
    

    Then, the use of jQuery saves pain...

    Within your submit script:

    if(!$('.wanted').prop("checked")){
        alert("Please select a film to continue making a booking.");
        return;
    }
    

    Add this jQuery lib call in your head:

    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    


    EDIT - See comments
    Function validate should be this:

    function validate(){
        var wantedChecked=$(".wanted:checked");
        if (!wantedChecked.prop("checked")){
            console.log("false");
            return false;
    
        }else{
            console.log("true");
            return true;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?