如何在用户输入提交后在同一页面中打印出表单字段值?

时间:2016-04-23 05:02:01

标签: javascript html css

我在点击提交后尝试在表单下方显示信息。请帮我解决这个问题。提交按钮不显示任何内容。有人可以解释一下吗? 这是我的HTML代码:

    <form id="myform" role="form">
        <label for="Name">Name:</label>
        <input type="text" class="form-control" id="Name"> 
        <div class="dropdown"> 
        <label for="countries">Country:</label> 
        <select class="form-control" id="countries">
          <option value="">Select a Country:</option>
        </select>
        <label for="states">State:</label>
        <select class="form-control" id="states">  
          <option value="">Select a State</option>
        </select>
        <input type="submit" onclick="showInput();">
    </form> 
    </div> 
        <label> Your input:</label>
        <p><span id='display'>
    </span></p>

以下是我的JavaScript代码:

function showInput() {
    var output_info =  document.getElementById("myform").value;

    document.getElementById('display').innerHTML = output_info;
}

2 个答案:

答案 0 :(得分:1)

试试这个

 <?php
if(isset($_POST["submit"]))
{

echo $_POST["Name"];
echo $_POST["countries"];
echo $_POST["states"];
}
?>
 <form id="myform" role="form" action="" method="post">
        <label for="Name">Name:</label>
        <input type="text" class="form-control" name="Name">  
        <label for="countries">Country:</label> 
        <select class="form-control" name="countries">
          <option value="">Select a Country:</option>
        </select>
        <label for="states">State:</label>
        <select class="form-control" name="states">  
          <option value="">Select a State</option>
        </select>
        <input type="submit"  name="submit">
    </form> 

答案 1 :(得分:0)

name内的inputselect个元素中尝试包含form属性;使用.querySelectorAll()与选择器"input:not([type=submit]), select"链接到form来选择form个元素; for循环迭代.querySelectorAll()

返回的元素

<script>
  function showInput(e) {
    e.preventDefault();
    var output_info = document.getElementById("myform");
    var display = document.getElementById("display");
    var data = output_info.querySelectorAll("input:not([type=submit]), select");
    for (var i = 0; i < data.length; i++) {
      display.innerHTML += "name:" + data[i].name + " value:" + data[i].value + "<br>"
    }
  }
</script>
<form id="myform" role="form">
  <label for="Name">Name:</label>
  <input type="text" class="form-control" name="Name" id="Name" />
  <div class="dropdown">
    <label for="countries">Country:</label>
    <select class="form-control" id="countries" name="countries">
      <option value="">Select a Country:</option>
      <option value="abc" selected>abc</option>
    </select>
    <label for="states">State:</label>
    <select class="form-control" id="states" name="states">
      <option value="">Select a State</option>
      <option value="123" selected>123</option>
    </select>
    <input type="submit" onclick="showInput(event);" />
  </div>
</form>
<label>Your input:</label>
<p><span id='display'>
    </span>
</p>