从下拉列表html php中选择项目时显示文本框?

时间:2017-10-12 16:06:38

标签: javascript php html

 <div class="control-group">
              <label class="control-label">
                <span class="red">*</span>Camera name</label>
              <div class="controls">
                <select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
                  <option>Select camera:</option>
                  <option>canon</option>
                  <option>nicon</option>
                  <option>sony</option>
                  <option>pentex</option>
                  <option>olympus</option>
                  <option>others</option>
                </select>
              </div>
            </div>
            <div class="control-group" id="dvPassport" style="display: none">
              <label class="control-label">Your camera name:</label>
              <div class="controls">
                <input type="text" placeholder="Enter model" name="cam_name" class="input-xlarge">
              </div>
            </div>

的javascript

<script type="text/javascript">
function ShowHideDiv() {
    var ddlPassport = document.getElementById("ddlPassport");
    var dvPassport = document.getElementById("dvPassport");
    dvPassport.style.display = ddlPassport.value == "others" ? "block" : "none";
}

php code

$camname = $_POST['cam_name'];// user name
if(empty($camname)){

      $errMSG = "Please enter camera name";

    }

当我选择&#34;其他&#34;从下拉列表...它工作正常 但问题是当我选择canon或nicon else时...隐藏div的输入标签在使用if(empty($ camname))进行cheking时在php代码中给出错误。

2 个答案:

答案 0 :(得分:1)

为select和input标签指定不同的名称。并且是添加选项值的好习惯

<select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
<option value="">Select camera:</option>  // null
<option value="canon">canon</option>
<option value="nicon">nicon</option>
<option value="sony">sony</option>
<option value="pentex">pentex</option>
<option value="olympus">olympus</option>
<option value="others">others</option>
</select>

// give a new name for this input
<input type="text" placeholder="Enter model" name="other_cam_name" class="input-xlarge">

PHP代码:

 $camname = $_POST['cam_name'];// cam name
 $other_camname = $_POST['other_cam_name'];// other cam name
 // if both select and input values 
 if(empty($camname) || ($camname =='others' && empty($other_camname))){
    echo $errMSG = "Please enter camera name";
 }else{
    echo $cam_name =  ($camname =='others') ?  $other_camname : $camname;
 }

答案 1 :(得分:0)

您需要明确定义option值。例如:

<option value="cannon">canon</option>