在特定的隐藏字段javascript / jquery上分配值

时间:2013-12-08 00:53:42

标签: javascript jquery

美好的一天!

如何使用JavaScript或jQuery将值放在行中的隐藏字段中?

继承人我的js:

function removeRow(){

 $('input#deleteId').val("yes");
 $(this).closest('tr').hide();
 return false;

 };

但上面的代码在我的表上用deleteId类更改了所有隐藏字段,我的问题是如何更改我单击删除按钮的特定行的隐藏字段值?我的表结构是这样的:

<table>
<tr>
   <td>itemName</td>
   <td>itemPrice<input type="hidden" id="deleteId" /><td>
   <td><a href="#">remove</a></td>
<tr>
</table>

并且wat是一个外部的js文件。

非常感谢你的时间!

2 个答案:

答案 0 :(得分:4)

您可以在输入中使用id="deletedId"。但是页面的id应该是唯一的,所以在你的情况下使用类“标识符”可能更合适。

JsFiddle:http://jsfiddle.net/B9De7/

$(function(){
    $('a').on('click', function(){
        removeRow(this);
    });
});

function removeRow(anchorElementClicked){
     var row = $(anchorElementClicked).closest('tr');
     row.find('input.hidden-deleted-id').val("yes");
     row.hide();
     //no need to return false or stop eventPropagation
}

<table>
    <tr>
       <td>itemName</td>
       <td>itemPrice<input type="hidden" class="hidden-deleted-id" /><td>
       <td><a href="#">remove</a></td>
    <tr>
</table>

答案 1 :(得分:1)

你的代码没有做你想要的,因为它不正确, 试试这个:

<table>
<tr>
   <td>itemName</td>
   <td>itemPrice<td>
   <td><a class='removeRow' id='element-id'>remove</a></td>
<tr>
</table>

$(".removeRow").click(function(e) {
    $.post( "page.php", { id: $(this).attr("id") })
    // if you want the answer from the php page, ex to tell user if the remotion succeeded or not
    .done(function( data ) {
        $(this).parent().parent().hide();
        // for example, "data" could be yes/not
        alert( "Removed: "+data );
    });
    e.preventDefault();
});

// PHP PAGE
<?php
//DB Connection stuff
$_POST['id'] is what you get, then you have to 
echo "yes/not" depending on the esit of the query.
that echo is sent back to ajax request.

它应*隐藏包含用户点击的元素。 e.preventDefault()必须不重页加载。

编辑:现在它应该将输入标记值设置为“是”并隐藏第一行。 为什么不在用户点击“删除”的同时使用ajax查询数据库? 如果你愿意我可以给你写代码。