简体   繁体   中英

display textbox when item is selected from dropdown list html php?

 <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";

    }

When i select "others" from dropdown list...it works fine but the problem is when i select canon or nicon else...the hidden div's input tag gives error..in php code when cheking with if(empty($camname));

Have different names for select and input tags. And is good practice to add option values

<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 code:

 $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;
 }

You need to explicitly define the option values. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM