开发者

assign multiple element attributes with .each?

开发者 https://www.devze.com 2023-04-12 08:55 出处:网络
So I have the following table, and I\'d like to set all the name attributes to a new value when I add a row to the table.(You probably guessed it: I use the buttons to add and delete rows, and I calcu

So I have the following table, and I'd like to set all the name attributes to a new value when I add a row to the table. (You probably guessed it: I use the buttons to add and delete rows, and I calculate a new name attribute based on the row index).

<table id="orderstable" >
            <tbody>
    <tr>
        <td align="top"><img src="/images/images/add_button_sm.gif" id="add_" align="top" border="0">
                <img src="/images/images/delete_button_sm.gif" id="del_" border="0">
        </td>
        <td><input name="orderBoxes[0].A" size="3" value="0.0" type="text"></td>
        <td><input name="orderBoxes[0].B" size="3" value="0.0" type="text"></td>
        <td><input name="orderBoxes[0].C" size="3" value="0.0" type="text"></td>
        <td><select name="orderBoxes[0].D">
            <option value="fifty">50</option>
            <option value="oneHundred" selected="selected">100</option>
            <option value="twoHundred">200</option>
            <option value="threeHundred">300</option></select>
        </td>
    </tr>
            </tbody>
</table>

I've tried to use .each to get all the elements and then get at the input.name attribbute.... but I can't get it to work. Any thoughts? My code may not be the most efficient... I'm still a noob:

$("#orderstable > tbody > tr > td > img[id=add_]").click( function(event){
            var row = $(this).closest("tr").get(0);
            var rowCopy=$(row).clone(true);
            $(ro开发者_如何学JAVAw).closest("tbody").append(rowCopy);

            $('#orderstable tbody>tr:last>td').each(function(){
                            $(this.input).attr(name);
                            }).val = "test";
            row.className+="add_";


This will grab the last row, and all input form elements. Then you can just set the name via $(this).attr('name')

$('#orderstable tr:last td :input').each(function(){
   $(this).attr('name', 'setyournamehere')
})


In your .each function, you need to use the arguments to get at the element and find the input:

$("#orderstable > tbody > tr > td > img[id=add_]").click( function(event){
        var row = $(this).closest("tr").get(0);
        var rowCopy=$(row).clone(true);
        $(row).closest("tbody").append(rowCopy);

        $('#orderstable tbody>tr:last>td :input').each(function(i, e){
                var n = $(e).attr('name');
            alert(n);
                        }).val = "test";
        row.className+="add_";
});

http://jsfiddle.net/swatkins/LFvwh/


Your selector does not seem to be correct. Your table doesn't have the id 'orderstable' and does not have a <tbody>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号