2013-10-30 85 views
0

我有一个项目列表。我希望能够点击一个按钮将项目添加到mySQL。在测试时,我只需使用conf box来显示ID。麻烦是我无法让它工作。我是jQuery和AJAX的新手。我认为这很容易。但经过一天早上从这里尝试了一堆不同的方法后,我想我会问我的确切代码。jQuery SelectButton旁边的隐藏输入值

<page loaded with> 
wp_enqueue_script('jquery'); 
wp_enqueue_script('jquery-ui-core'); 
wp_enqueue_script('jquery-ui-tabs'); 
wp_enqueue_script('jquery-ui-autocomplete'); 

<script> 
function addCharItem() { 
    var itemID = $(this).closest("td").find('input[name="itemID"]').val(); //this is close (I think) but message is showing as undefined. 
// var itemID = $("input").siblings(".itemID").val() //gets first ID in table only 
    confirm ('The item ID is ' + itemID); 
//adding ajax and other stuff later. 
} 
</script> 

<html> 
... 
<tr> 
    <td colspan="5"><dl><dt>Backpack (empty)</dt><dd></dd></dl></td> 
    <td><input name="hdnItemID" type="hidden" value="742"/> 
     <input name="btnAddItem" type="button" id="btnAddItem" value="+" onclick="addCharItem()"/></td> 
    <td><input name="btnBuyItem" type="button" id="btnBuyItem" value="$" /></td> 
</tr> 
... 
</html> 

这是全部从Wordpress中的模板php页面构建而成。我不认为这些东西有什么奇怪之处。但如果让我知道你还有什么需要的。感谢您的帮助和建议。我知道我必须错过一些小小的东西,我只是不知道这个东西足够好,还不知道是什么。

+0

到目前为止没有运气。我添加了以下内容:\t var thisValue = $(this); console.log(thisValue);看看这是什么选择。它在控制台中返回:[Window,jquery:“1.9.1”,constructor:function,init:function,selector:“”,size:function ...] 它不应该有选择器吗?它显示“”。也许这就是问题所在。为什么'this'不能抓住当前的元素呢? – user1518699

回答

0

因此,似乎出于某种原因,上面的代码没有被抓HTML元素。所以相反,我实现了jQuery按钮。

<script> 
    $(function() { 
    $("input[type=submit], a, button") 
     .button() 
     .click(function(event) { 
     event.preventDefault(); 
     var thisValue = $(this).val(); //to distinguish buttons 
     console.log(thisValue); 
     var itemID = $(this).prev('input[id="hdnItemID"]').val() 
     confirm ('The item ID is ' + itemID); 
      //do other stuff 
     }); 
    }); 
</script> 

<html changes> 
... 
<tr> 
    <td colspan="5"><dl><dt>Backpack (empty)</dt><dd></dd></dl></td> 
    <td><input class="itemID" id="hdnItemID" type="hidden" value="742"/> 
    <input type="submit" value="+" /></td> 
    <td><input class="itemID" id="hdnItemID" type="hidden" value="742"/> 
    <input type="submit" value="$" /></td></tr> 
... 
</html> 

我希望我能告诉你为什么它不起作用。看来,我尝试过许多不同的方式,本该工作。上面的建议也应该起作用。如果有人知道这是为什么,请让我知道。我,我确信还有其他人,很想知道这个“疑难杂症”问题。感谢所有提示!

1

您可以使用.siblings(selector)

$(this).siblings('input[name="hdnItemID"]').val() 

$(this).prev('input[name="hdnItemID"]').val() 
1

使用hdnItemID您的姓名,不itemID

$(this).closest("td").find('input[name="hdnItemID"]').val();