使用jQuery将值传递给隐藏的输入

时间:2011-02-28 02:18:40

标签: php jquery forms post

我有一堆ID为1-n的链接,我希望将该ID传递给我表单中的隐藏输入(我有很多链接,但只想拥有一个表单而不是生成数千个额外的HTML行为每个ID制作表格。

链接如下所示:

<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>

任何帮助?

2 个答案:

答案 0 :(得分:2)

这会将隐藏input的值设置为ID元素的id,然后才会提交a

form

答案 1 :(得分: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 Segment

<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的查询字符串段将此请求直接传递给处理和操纵页面而不必进行整页重新加载。