使用jquery从onsubmit处理程序访问表单元素

时间:2016-11-24 09:24:15

标签: javascript jquery html forms

我在页面上有几个表单都带有onsubmit处理程序doSomthing()。如何访问实际调用处理程序的表单元素?如何将它传递给函数。

<script>
    function doSomthing( getThePassedElement ){

        // Do some changes in the form values

        return false;

    }
</script>


<form action="#" onsubmit="doSomthing( PassSomthingHere )">
    <input type="text" class="name">
    <input type="submit">
</form>

<form action="#" onsubmit="doSomthing( PassSomthingHere )">
    <input type="text" class="name">
    <input type="submit">
</form>

4 个答案:

答案 0 :(得分:2)

只需通过thisthis将引用当前元素form

  this中的

inline event-handler参数指的是 HTML DOM Object 事件属于!

function doSomthing(getThePassedElement) {
  console.log(getThePassedElement);
  return false;
}
<form action="#" onsubmit="return doSomthing(this);">
  <input type="text" class="name">
  <input type="submit">
</form>

<form action="#" onsubmit="return doSomthing(this);">
  <input type="text" class="name">
  <input type="submit">
</form>

使用jQuery jQuery.on事件使用submit处理程序!

$('form').on('submit', function(e) {
  e.preventdefault();
  console.log($(this).find('input.name').val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="#">
  <input type="text" class="name">
  <input type="submit">
</form>

<form action="#">
  <input type="text" class="name">
  <input type="submit">
</form>

使用DOM-API

var forms = document.querySelectorAll('form');
[].forEach.call(forms, function(elem) {
  elem.addEventListener('submit', function(e) {
    e.preventDefault();
    console.log(this);
  })
});
<form action="#">
  <input type="text" class="name">
  <input type="submit">
</form>

<form action="#">
  <input type="text" class="name">
  <input type="submit">
</form>

答案 1 :(得分:1)

这是使用不引人注目的submit

将事件处理程序绑定到javascript的方法
$(function(){
    $('form').submit(function(event){
        //Use $(this) to access the form
    });
});


<form action="#">
  <input type="text" class="name">
  <input type="submit">
</form>

<form action="#">
   <input type="text" class="name">
  <input type="submit">
</form>

答案 2 :(得分:0)

为每个表单添加简单的ID就可以了。试试这段代码

    <script>
        function doSomthing( id ){
           var form = $('#'+id); // this is your form handle
           // Do some changes in the form values
           return false;
        }
    </script>

HTML:

<form action="#" id="form1" onsubmit="doSomthing( 1 )">
    <input type="text" class="name">
    <input type="submit">
</form>

<form action="#" id="form2" onsubmit="doSomthing( 2 )">
    <input type="text" class="name">
    <input type="submit">
</form>

答案 3 :(得分:0)

通过&#39; this.form&#39;到被叫函数。

<form action="#" onsubmit="doSomthing( this.form )">
    <input type="text" class="name">
    <input type="submit">
</form>