0

「ブランチ」ラジオボタンが選択されていない場合にPHP Postが実行されないようにするために、以下のコードに条件文を入れたいと思います。

これを正しく行うための構文が見つかりません。

条件ステートメントで HTML タグを参照する方法がわかりません。

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Data has been submitted!");
}
</script>
</head>
<body>

<h1>Reference Stats Input</h1>
<form  method="post">
<h2>Select Branch</h2>
<label><input type="radio" name="branches" value="AR">AR</label><br>
<label><input type="radio" name="branches" value="BK">BK</label><br>
<label><input type="radio" name="branches" value="BR">BR</label><br>
<label><input type="radio" name="branches" value="EM">EM</label><br>
<label><input type="radio" name="branches" value="MD">MD</label><br>
<label><input type="radio" name="branches" value="PT">PT</label><br>
<label><input type="radio" name="branches" value="UR">UR</label><br>
<label><input type="radio" name="branches" value="WA">WA</label><br>
<br>
<br>
<br>

Type of Reference question:<select name="refquestion" <br><br>
<option value="ADULT">ADULT</option>
<option value="CHILD">CHILD</option>
<option value="JUVENILE">JUVENILE</option>
</select><br><br>

<input name="Submit" type="submit" onclick="myFunction()" value="INPUT">

<?php
if(!empty("branches"){
$con = mysql_connect("localhost","root","REDACTED");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("refstats", $con);
$sql="INSERT INTO reftable (branch, statcat)
VALUES
('$_POST[branches]','$_POST[refquestion]')";

if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

mysql_close($con)
}
?>

</form>
</body>
</html>
4

2 に答える 2

3

php ではこれを行うことはできません。php はサーバー側であり、投稿した後にのみ選択を認識します。

これは、JavaScript のイベントハンドラーで行う必要があります。それを説明するために jQuery を使用した例を示します。ネイティブ JS に戻すことができるかどうかを確認します。

// jQuery style (and therefor requires jQuery to work)
$('form').on('submit', function(e){
    if( $('[name="branches"]:selected').length === 0){
        e.preventDefault();
        alert('please select a branch');
    }
});

// Or native Javascript (this isn't tested 100%, but something like this):
document.getElementById("form").onsubmit=function(){
    // get all options
    var options = document.getElementsByName("branches");
    var itemChecked = false; // start with false, se to true if there is a selected option
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked) { // if one option is found
            itemChecked  = true; // set to true
            break; // no need to continue the loop
        }
    }
    return itemChecked
};

オプションのデフォルトを常に選択することができます:)
重要:javascriptを信用しないでください!! 常にクライアント側の情報サーバー側を再確認してください。クライアント側の情報は常に悪と見なされるべきであり、そうでないことを確認する必要があります。

于 2013-08-28T17:23:46.957 に答える