2017-09-16 52 views
0

我有4個複選框,其中之一是Others有文本框,我想獲得用戶檢查的所有值,如果他檢查其他選項從文本框中獲取值與Others複選框關聯。如何從文本框中的值在複選框在php

HTML代碼

<div class="row"> 
    <div class="col-sm-4"> 
     <label class="Modallabel">Available Products:</label> 
    </div> 
    <div class="col-sm-8"> 
     <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Cacao">Cacao</label> 
     <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Coconuts">Coconuts</label> 
     <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" value="Bananas">Bananas</label><br> 
     <label id="Pro_chkbox" class="checkbox-inline"><input name="check_list[]" type="checkbox" id="optcheck" value="Others">Others</label> 
     <input type="text" id="Other_pro" name="otherproduct"><br> 
     <label id="Note">(Separate Products with commas)</label> 
    </div> 
</div> 

PHP代碼

$checked_count = count($_POST['check_list']); 

    if ($checked_count > 1) 
    { 
     $productlist = implode(', ', $_POST['check_list']); 
     echo $productlist; 
    } 
    elseif ($checked_count == 1) 
    { 
     foreach($_POST['check_list'] as $selected) { 
      $productlist = $selected; 

      //To check if Others checkbox is checked or not to get the values in textbox 
      if ($productlist == "Others") 
      { 
       $productlist = $_POST["otherproduct"]; 
      } 
      echo $productlist; 
     } 
    } 
+0

所以如果用戶檢查'others',你是否只需要文本框的值或者兩者都檢查和文本值 –

+0

備註:ID's應該是唯一的,並且你所有的複選框都帶有'id =「Pro_chkbox」'和你標記爲「javascript」,沒有支持的代碼;這是爲什麼? –

+0

我需要檢查和文本值,例如:如果用戶檢查香蕉和其他人,並在文本框中輸入蘋果,所以結果應該是:「香蕉,蘋果」 – Bnabil

回答

1

這將這樣的伎倆爲您

$checked_count = count($_POST['check_list']); 
$productlist = ''; //initialize an empty string for product list 
if ($checked_count > 1) //check if multiple check-boxes are checked 
{ 
    $productlist = implode(', ', $_POST['check_list']); //implode all checkbox values in list string 
    if(in_array('Others', $_POST['check_list'])) { //check if others is checked 
     $productlist .= ', '.$_POST['otherproduct']; //con-cat text in text box lined with others in list string 
     $productlist = str_replace('Others,', '', $productlist); //remove others from the list string (skip if you want others to be in your result' 
    } 
} elseif ($checked_count == 1) { 
    $productlist = ($_POST['check_list'][0] == 'Others') ? $_POST['otherproduct'] : $_POST['check_list'][0]; //if only one checkbox is checked then check its value and use the value 
} 
echo "<br/>".$productlist; 

另外,你可以把客戶端和服務器端驗證至 確保您從表單中獲得正確的輸入值。

此外,您可以使用Java腳本使您的表單更具交互性。

+0

非常感謝 – Bnabil