Вопрос

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