Jquery更改子元素的id

时间:2010-12-06 10:06:46

标签: jquery

我希望tds(文本框)具有唯一的id,以便我可以获取在这些文本框中输入的值。如何为文本框提供唯一的ID并获取在这些文本框中输入的值?

这是我的代码:

<html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
    div{
        padding:4px;
    }
</style>

</head>

<body>


<script type="text/javascript">

$(document).ready(
    function(){
    var counter = 2;
        $('a.add').live('click',
            function(){
                if(counter>5){
                    alert("Only 5 textboxes allowed");
                    return false;
                }   
            $(this)
                 .closest('tr')
                 .clone()
                 .appendTo('table');
            $(this)
                 .text('Remove')
                 .removeClass('add')
                 .addClass('remove');
            counter++;
            });
        $('a.remove').live('click',
            function(){
                $(this)
                    .closest('tr')
                    .remove();
                    counter--;
            });
        $('input:text').each(
            function(){
                var thisName = $(this).attr('name'),
                    thisRrow = $(this)
                                .closest('tr')
                                .index();
                //$(this).attr('name', 'row' + thisRow + thisName);
               // $(this).attr('id', 'row' + thisRow + thisName);
            });
     $("#getButtonValue").click(function () {
        var msg = '';
        for(i=1; i<counter; i++){
            msg += $('').val();
        }
              alert(msg);
        });
    });
</script>
</head><body>

<table>
    <tr>
        <th>Min Value</th>
        <th>Max Value</th>
    </tr>
    <tr>
        <td><input type="text" name="col1" id="col1" /></td>
        <td><input type="text" name="col2" id="col2" /></td>
        <td><a href="#" class="add">Add</a></td>
    </tr>
    <tr><input type='button' value='Get TextBox Value' id='getButtonValue'></tr>
</table>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

添加新行时,必须将ID分配给其文本框:

var i=0;
$(this)
    .closest('tr')
    .clone()
    .appendTo('table')
    .children()
    .each(function(){
        $(this)[i].id="textbox" + counter + (i++)}

我选择了一个id,第一个数字标识行,第二个数字标识列。

答案 1 :(得分:1)

创建新行时使用此选项...

        var newRow = 
            $(this)
                 .closest('tr')
                 .clone()
                 .appendTo('table');
        var i=1;
        $('input',newRow).each(function(){
            $(this)[0].id="Col"+counter+"_"+(i++)}
        );

答案 2 :(得分:0)

要为页面中的每个<input>框添加唯一ID,请使用:

        var i=0;
        $('input').each(function(){
            $(this)[0].id="TextBox"+(i++)}
        );

这会为他们提供TextBox0TextBox1等的ID

但是我注意到在HTML中发布的所有输入框都已经有了唯一的ID。您是否计划在运行时动态添加更多内容?

相关问题