开发者

jQuery Clear Appended Textbox

开发者 https://www.devze.com 2023-03-07 08:04 出处:网络
Here\'s the code: function newRow(){ var sourceRow = $(\'table#listings tr.row\').html(); $(\'table#listings > tbody:last\').append(\'<tr>\'+sourceRow+\'</tr>\');

Here's the code:

function newRow(){
    var sourceRow = $('table#listings tr.row').html();
    $('table#listings > tbody:last').append('<tr>'+sourceRow+'</tr>');
    return false;
}

HTML:

<table id='listings'>
<tbody>
    <tr>
        <td><input type='text' name='entry[]' value='ENTRY1' />
    </tr>
</tbody>
</table>

The code works but how will i automatically clear the newly appended row textbox? Because it copies whatever the previous row has. I tried:

var sourceRo开发者_如何学Gow = $('table#listings tr.row').html();
var x = $(sourceRow).('input').children().val(''); //problematic line
$('table#listings > tbody:last').append('<tr>'+sourceRow+'</tr>');
return false;

but didn't work.

I want to have an ouput:

<table id='listings'>
<tbody>
    <tr>
        <td><input type='text' name='entry[]' value='ENTRY1' />
    </tr>
    <tr>
        <td><input type='text' name='entry[]' value='' />
    </tr>
</tbody>
</table>


What about this?

You should not serialise HTML to a string when you can avoid it. You want to clone the element.

Also cache the selector to the table. This means you only need to select it once.

function newRow(){
    var table = $('table#listings'),
        newRow = table.find('tr:first').clone();

    newRow.find(':input').val('');
    table.find('> tbody:last').append(newRow);
}


This might work:

$('table#listings > tbody:last > tr:last input').val('')


You had some problems in your selectors... and then what you were doing with your selectors. : )

function newRow(){
   var sourceRow = $('table#listings tr').html();
   var destRow = $('<tr>'+sourceRow+'</tr>');
   destRow.find('input').val('');
   $('table#listings > tbody:last').append(destRow);
   return false;
}

I've made it a bit more atomic so that it is easier to read.

Fiddle


Added: note that there is nothing with a class of 'row' in your example.

0

精彩评论

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

关注公众号