2011-02-28 187 views
0

我有一堆链接ID为1 - n,我想通过该ID到我的窗体中的隐藏输入(我有很多链接,但只想要一个窗体而不是为每个ID生成数千行额外的HTML表单)。将值传递给隐藏的输入与jQuery

链接看起来是这样的:

<a href='javascript:$("#removeSave").submit()' id="n">Remove</a> 

采用隐藏式输入的形式如下:

<form action="/php/removeSave.php" method="POST" id="removeSave"> 
    <input type="hidden" name="ID" value=""/> 
</form> 

任何帮助吗?

+4

给出的链接似乎没有ID。此外,为了清楚起见,ID不能以数字开头。 – kojiro 2011-02-28 02:22:06

+0

对不起,添加了链接ID。 – AKor 2011-02-28 02:30:31

回答

2

这个设置隐藏input与ID IDa元素的id值它提交form之前。

<a href='#' id='n' onclick='$("#ID").val(this.id);$("#removeSave").submit();'>Remove</a> 


<form action="/php/removeSave.php" method="POST" id="removeSave"> 
    <input type="hidden" name="ID" id="ID" value=""/> 
</form> 
+1

根据ISO8879(参见http://www.w3.org/TR/html4/types.html#h-6.2),ID属性必须以字母开头(并且所以'... id =“123 “......”是无效的,当然,你可以用“id”或其他东西加前缀,然后用'this.id.replace(/ \ D/g,“”)'数字字符出来。 – 2011-02-28 02:59:07

0

您没有提供的“删除”链接,其中ID会被注意到的完整的上下文,所以我会假设的格式,你可以从那里适应。

<!-- HTML //--> 

<!-- Format for Each Element. "123" is the ID here //--> 
<div id="element123"> 
    This is Element 123 (ID#123) 
    <a href="/php/removeSave.php?ID=123">Remove</a> 
</div> 

<!-- The Form at the Bottom of the Page //--> 
<form id="removeSave" method="POST" action="/php/removeSave.php"> 
    <input type="hidden" name="ID" value="" /> 
</form> 

jQuery的段这种方法的

<script type="text/javascript"> 
$(document).ready(function(){ 

// Clicks of Links starting with "/php/removeSave.php?ID=" 
    $('a[href^="/php/removeSave.php?ID="]').click(function(e){ 
    // Don't let the Link act as a basic link 
    e.preventDefault(); 
    // Get the Link HREF attribute 
    href = $(this).attr('href'); 
    // Derive the Form ID and ID Value 
    bits = href.match(/^\/php\/([^\.]+)\.php\?ID=(\d+)/); 
    formID = bits[1]; 
    elementID = bits[2]; 
    // Set the Field Values and Submit the Form 
    $form = $('#'+formID); 
    $form.find('input[name="ID"]').val(elementID); 
    $form.submit(); 
    }); 

}); 
</script> 

好处?

优雅的降级 - 只要你的PHP脚本也可以处理GET变量,如果这个页面是从没有启用Javascruipt的浏览器加载的,或者无法加载jQuery,点击“删除”链接仍然会执行预期的操作。

机遇AJAX-ification - 而不是.click(function(e){段内的所有这些其他操作,您可以使用jQuery的$.post()功能和链接的HREF的查询字符串段直传球此请求处理程序和操作页面,而无需做一个完整的页面重新加载。

相关问题