如何在提交时捕获表单选项?

时间:2016-02-08 11:36:10

标签: javascript html

如何在提交时捕获表单选项?

我有一个简单的html表单,我可以在退出时调用JavaScript函数,但是如何从<select>元素中捕获所选的选项?

请参阅以下代码:

 <legend>Administration:</legend>
<script type="text/javascript">
  function handleIt(m){
      alert("hello");
      }

</script>
</head>
<body>
  <form action="javascript:handleIt(select.name)"/>
  <select name="num" required>
  <option value="1">Add Anouncment</option>
  <option value="2">Del Anouncment</option>
  <option value="3">Aprove </option>
  <option value="4">unAprove </option>
  </select> 
<input name="Anouncement" type="text" required> 
  <input name="Submit"  type="submit" value="Update"/>
</form>

2 个答案:

答案 0 :(得分:0)

首先,HTML语法中存在错误。

这将在“提交”时获取数据。按下按钮(jsfiddle)

$('#submit_btn').on('click', function(e) {
    e.preventDefault();
  console.log($('[name="num"]').val());
});

<form id="main-form" method="get">
  <select name="num" required>
  <option value="1">Add Anouncment</option>
  <option value="2">Del Anouncment</option>
  <option value="3">Aprove </option>
  <option value="4">unAprove </option>
  </select> 
  <input name="Anouncement" type="text" required> 
  <input name="Submit"  type="button" value="Update" id="submit_btn"/>
</form>

答案 1 :(得分:0)

您可以使用它来检索所选选项

<script type="text/javascript">
  function handleIt(){
      var v=document.getElementById("s1");
       alert(v.options[v.selectedIndex].text) ;   
      }

</script>
</head>
<body>
  <form action="javascript:handleIt()"/>
  <select name="num" id="s1" required>
  <option value="1">Add Anouncment</option>
  <option value="2">Del Anouncment</option>
  <option value="3">Aprove </option>
  <option value="4">unAprove </option>
  </select> 
<input name="Anouncement" type="text" required> 
  <input name="Submit"  type="submit" value="Update"/>
</form>