2015-08-25 83 views
1

這是我單選按鈕的代碼。我想添加條件,當一個單選按鈕沒有被用戶選擇,那麼它會出來警告有數據是空的。完成後,它會計算總和。單選按鈕不能清空

<form action="" method="post"> 
Player 1: 
male <input type="radio" name="gender[1]" value="1"> 
female <input type="radio" name="gender[1]" value="2"> 
<br> 
Player 2: 
male <input type="radio" name="gender[2]" value="1"> 
female <input type="radio" name="gender[2]" value="2"> 
<br> 
Player 3: 
male <input type="radio" name="gender[3]" value="1"> 
female <input type="radio" name="gender[3]" value="2"> 
<br> 
<input type="submit" name="submit" value="submit"> 
</form> 

<?php 
if (isset($_POST['submit'])) 
{ 
    $sum=0; 
    if (isset($_POST['gender'])) 
    { 
     $gender=$_POST['gender']; 
     foreach ($gender as $value) 
      { 
       $sum=$sum+$value; 
      } 
      echo $sum; 

    } 
    else 
    { 
     echo 'you did not choose any genders'; 
    } 
} 
?> 
+0

'回聲$ _POST [ '性別']''以上如果(isset($ _ POST [ '提交']))'? –

+0

我不確定我是否理解這個問題,您當前的代碼是否無效?此外,請前往[旅遊](http://stackoverflow.com/tour)看看:) – Epodax

+0

我的代碼工作,但是當我只選擇一個,它保持計數總和。當有一個數據爲空時,它不會計算總和 – henv

回答

0

如果所有單選按鈕被選中,count($_POST['gender'])將3.所以才替換

else 
{ 
    echo 'you did not choose any genders'; 
} 

if (count($_POST['gender']) < 3) { 
    echo 'you did not choose any genders'; 
} 
+0

count sum still show ... – henv

+0

不算'count($ sum)',因爲它可以在0到6之間的任何地方。你需要'count($ _ POST ['gender'])' – putvande

+0

好的謝謝。我會嘗試 – henv

0

這很簡單,你可以寫

if(!$_POST['gender']) echo ....; 

,或者,如果你想檢查單位置

if(!$_POST['gender'][0] && !$_POST['gender'][1] && !$_POST['gender'][2]) echo ...; 
+0

如果我的數組性別如此之多,我必須寫全部? – henv