简体   繁体   中英

Append text inputs based on value provided by the user w/ jQuery

HTML:

<input type="text" id="inputsNum" />
<div id="content"></div>

jQuery:

$("#inputsNum").bind('change paste keyup', function () {
    var count = $(this).val(),
        content = "";
    for (var i = 0; i < count; i++)
    {
       content += $(this).append($('<input>').prop('type', 'text'));
    }
    $(this).next().html(content);  
});

Hi,

want to let the user to add multiple text inputs based on value he provided

i wrote the above code but i'm getting [object Object] error repeated actually based on the value i provided , means its working but why its doesn't append the text inputs !

need your help

thank you

Here is the working JS Fiddle

$(document).ready(function() {
    $("#inputsNum").bind('change paste keyup', function () {
        var count = $(this).val(),
            content = "";
        for (var i = 0; i < count; i++)
        {
           content += '<input type="text" />';
        }
        $('#content').html(content);
    });
});

You can try replacing content += $(this).append($('<input>').prop('type', 'text')) with content += "<input type='text' />";

The append function that you are using returns an object and not the HTML as string like you expect it to. Thus when you add it as a string, the toString() method of the object converts it to [object Object] and that gets appended to your HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM