문제

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