2014-09-01 56 views
0

我必須從onSubmit上的三個表單調用相同的javascript函數(chek())事件並需要知道哪一個表單稱爲此功能。它是三個按鈕。如何在javascript函數chek()中調用表單的名稱,在提交表單上調用哪一個,然後在javascript中以form的名稱作爲變量進行操作。例如:如何從表單中提取名稱,在此jscript函數中調用javascript函數,然後使用與變量相同的js函數中的名稱

<form id="one" action="" method="post" onSubmit="chek();"> 
<input type="hiden" id="idfi11" name="idf1"> 
<input type="submit" id="idfi12"> value="B1" > 

<form id="two" action="" method="post" onSubmit="chek();"> 
<input type="hiden" id="idfi21" name="idf1"> 
<input type="submit" id="idfi22"> value="B2" > 

<form id="three" action="" method="post" onSubmit="chek();"> 
<input type="hiden" id="idfi31" name="idf1"> 
<input type="submit" id="idfi32"> value="B3" > 

這三個按鈕,並取決於哪一個是點擊的javascript赤()赤東西, 計數了一些成績。 JavaScript示例:

<script type="text/javascript"> 
function chek() 
{ 
var message1,message2,message3=""; 
var data=""; 
... count data string, and message1,message2, messag3.... 

if (callname = form one) // here I need name of called form 
    { 
    alert("Message one :"+ message1); 
    document.getElementById("idfi11").value = data; 
    } 
if (callname = form two) 
    { 
    alert(Message two : + message2); 
    document.getElementById("idfi21").value = data; 
    } 
if (callname = form three) 
    {alert("Message three :"+message3);document.getElementById("idfi22").value = data;} 
return (true); 
} 
</script> 

非常感謝你的答覆...

+0

你的表格沒有名字,他們有一個ID。爲了訪問它,只需將函數調用的元素作爲參數傳遞給函數 - 「onSubmit =」chek(this)「'。 – CBroe 2014-09-01 07:36:11

+0

如果使用jQuery,'.submit'將保存表單元素,您可以傳遞。 '$(this).attr('name')'將返回該元素名稱。 – Justinas 2014-09-01 07:36:12

+0

謝謝你們兩位。我新的,我還沒有使用jQueri .. @CBroe我已經這樣做了,並且警報消息爲allert(vform)形式是'this'是[對象] HTMLFormElement。以及如何獲取HTMLFormeElement的名稱或ID的變量? – Vranilac 2014-09-01 07:51:35

回答

3

嘗試是這樣的

HTML

<form id="one" name="one" action="" method="post" onSubmit="chek(this);"> 

JAVASCRIPT

function chek(obj){ 
    alert(obj.id);// will give you ID of form 
    alert(obj.name);// will give you NAME of form 
} 

不要忘記添加名稱屬性來形成。

0

我這樣做

<form id="one" action="" method="post" onSubmit="chek(this);"> 
... 

的Javascript

function chek(vforma) 
{ 
alert(vforma.id); // result= 'one' 
...  
} 
0

的Javascript:

赤(本);

Jquery的:

$(元件).closest( 「形式」)ATTR( 「ID」);

相關問題