Here is the original post: Multiple dynamic input text javascript

Here is my attempt: http://jsfiddle.net/AZz6R/

I found that the difference between my attempt and the original post might possibly be how JavaScript and jQuery treat the return statement. In the original post, the code will still execute after the return statement for some reason.

My question is can anyone help me to make the code work in jQuery instead of plain JavaScript?

有帮助吗?

解决方案

Try this:

$('#myDiv').on('keyup', 'input', function() {
    if($(this).val() == ''){
        $(this).next().remove();
        return;
    }
    else if($(this).next().val() == '') {
        console.log('here');
        return;
    }

    var newTxt = $(this).clone();
    var id = newTxt.attr('id');
    newTxt.attr('id', 'txt_' + (parseInt(id.substring(id.indexOf('_') + 1))));
    newTxt.val('');
    $(this).parent().append(newTxt);

});

jsFiddle

其他提示

main issue in your code is the if conditions. change it as follows should work:

if($(this).val()==''){
    $(this).next().remove();
    return;
}
else if($(this).next().val()) {
    console.log('here');
    return;
}

Second issue is, value is not getting empty for cloned input. change it as below will work:

newTxt.val('');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top