在提交之前显示选择的选项的值

时间:2015-10-21 10:40:46

标签: php forms

我希望在单击提交之前回显所选选项的值($_POST[cat]),如果我选择男性它应该回显或显示以下表单标签之外的男性代码:

<form name="form" method="post" action="" >
Gender:<br>
<select name="cat">
<option value="">select a gender</option>
<option value="male">male</option>
<option value="male">female</option>
</select>
</form>

<?php echo $_POST[cat]; ?>

3 个答案:

答案 0 :(得分:0)

使用PHP无法做到这一点。为此,您必须使用JavaScriptjQuery

以下是jQuery example

代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>change demo</title>
  <style>
  div {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<select name="sweets" multiple="multiple">
  <option>Chocolate</option>
  <option selected="selected">Candy</option>
  <option>Taffy</option>
  <option selected="selected">Caramel</option>
  <option>Fudge</option>
  <option>Cookie</option>
</select>
<div></div>

<script>
$( "select" )
  .change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $( this ).text() + " ";
    });
    $( "div" ).text( str );
  })
  .change();
</script>

</body>
</html>

答案 1 :(得分:0)

你去了

<form name="form" method="post" action="" >
Gender:<br>
<select name="cat" id="cat" onchange="checkCat();">
<option value="">select a gender</option>
<option value="male">male</option>
<option value="male">female</option>
</select>
</form>
<div id="div1">

</div>

<script>
function checkCat() {
var oS = document.getElementById("cat");
var gender = oS.options[oS.selectedIndex].value;
var para = document.createElement("p");
var node = document.createTextNode(gender);
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
}
</script>

答案 2 :(得分:0)

正如您在上一篇文章中所说,您可以使用jQuery或JS来完成。 这是另一个例子:

&#13;
&#13;
$(document).ready(function(){

    s = $('select[name="cat"]');
    
    $(s).change(function()
    {
        $("#gender-show span").html(s.val());    
    });
});
&#13;
*{padding:5px}
#gender-show span{font-weight:bold}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<form name="form" method="post" action="" >
Gender:<br>
<select name="cat">
<option value="">select a gender</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</form>
    
<div id="gender-show">Gender Choice: <span></span></div>
&#13;
&#13;
&#13;