2012-12-18 123 views
5

嗨我试图将onclick事件上的变量传递给javascript函数。我正在尝试以下方法,我无法在javascript函数中获得输入值(我期待1的警报)。这是做这个的正确方法吗?请帮忙。将onclick事件的父窗体传递给javascript函数

<head> 
    <script> 
     function submit_value(form) { 
      alert(form.ip.value); 
     } 
    </script> 
</head> 
<table> 
    <tr> 
     <form> 
      <td> 
       <input id="ip" type="text" value="1"> 
      </td> 
      <td> 
       <a href="javascript:;" onClick="submit_value(this)">Button</a> 
      </td> 
     </form> 
    </tr> 
</table> 

回答

3

您的脚本不知道什么form是。您需要改为指定document.forms[0].ip.value

如果文档中有多个表单,那么将表单元素首先存储在变量中会更好。你可以有一个ID的形式为上...

<form id="formID">

和submit_value功能,可以

var myForm = document.getElementById('formID'); alert(myForm.ip.value);

编辑:

您可以使用this.form用于onClick的锚标签。

+1

更好的是给你的表格的名称,然后使用document.formName.ip.value – Ankit

+0

点是可以有n这样的动态表单的数量。 document.forms [0] .ip.value就像知道我想发送的表单。我想将表单父项传递给锚标签。我该怎么做? – user1051505

0

功能改成这样:

function submit_value(form) { 
     alert(document.getElementById('ip').value); 
    } 

当你写submit_value(this)this的值实际上是元素<a>本身,而不是形式。

+0

点是可以有n个这样的动态形式。我想将表单父项传递给锚标签。我该怎么做? – user1051505

+1

如果有很多动态表单,那么你不应该使用'id =“ip”'因为ids必须是唯一的 –

+0

ok,class应该在那里 – user1051505

0

我假设你可以使用jQuery。选择器很简单。

变化从

<form> 
     <td> 
      <input id="ip" type="text" value="1"> 
     </td> 
     <td> 
      <a href="javascript:;" onClick="submit_value(this)">Button</a> 
     </td> 
</form> 

以下表格的html

<form> 
     <td> 
      <input id="ip" type="text" value="1"> 
     </td> 
     <td> 
      <a href="" class="mySubmitButton">Button</a> 
     </td> 
</form> 

然后你的JS会像

$('.mySubmitButton').click(function() { 

    var inputBox = $(this).prev(); 
    alert(inputBox.val()); 
    return false; //This prevents the default function submit . Similar to event.preventDefault 
}); 
0

jQuery是无处不在。你不需要JQuery。 为什么人们忘记了DOM对象模型? 他做了几乎正道一切:

<head> 
 
     <script> 
 
      function submit_value() { 
 
       alert(document.forms[0].ip.value); 
 
      } 
 
     </script> 
 
    </head> 
 
    <table> 
 
     <tr> 
 
      <form> 
 
       <td> 
 
        <input name="ip" type="text" value="1"> 
 
       </td> 
 
       <td> 
 
        <a href="javascript:;" onClick="submit_value()">Button</a> 
 
       </td> 
 
      </form> 
 
     </tr> 
 
    </table>

或者,您可以添加表格ID

<head> 
 
     <script> 
 
      function submit_value() { 
 
       alert(document.forms.formid.ip.value); 
 
      } 
 
     </script> 
 
    </head> 
 
    <table> 
 
     <tr> 
 
      <form id='formid'> 
 
       <td> 
 
        <input name="ip" type="text" value="1"> 
 
       </td> 
 
       <td> 
 
        <a href="javascript:;" onClick="submit_value()">Button</a> 
 
       </td> 
 
      </form> 
 
     </tr> 
 
    </table>

相关问题