2017-09-16 75 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

相关问题