简体   繁体   English

动态添加文本框

[英]Dynamically add text box

Newbie at web.. 网络新手。

This should be simple. 这应该很简单。 I have text box the user should write City. 我有文本框,用户应写城市。 I'd like the user to press on "Add City" and another text box will be shown (do this up to 3 times). 我希望用户按下“添加城市”,然后将显示另一个文本框(最多执行3次)。 can you give me headstart on how to implement this? 您能为我提供如何实现此目标的先机吗?

<section class="row-inner clearfix">
    <section class="form-field">
        @Html.TextBoxFor(m => m.Cities, new { @class = "autocomplete-init-no-img"})
        <label>Cities</label>
    </section>

    <section class="form-field">
        <a href="#">Add City</a>
    </section>
</section>

You will need to do this client side via JS. 您将需要通过JS进行此客户端。 The examples I am showing you use JQuery. 我向您展示的示例使用JQuery。

Something like 就像是

$("#button").click(function(){
   $("#section").append("<input type='text' name='City1'/>");
});

The problem with this is that you will end up dynamically having to deal with parameters. 这样做的问题是,您最终将不得不动态地处理参数。 If you know you only want to have 3, then that is fine. 如果您只想拥有3个,那很好。

If you wanted to use more of the built in controls, you could do something like. 如果您想使用更多的内置控件,可以执行类似的操作。

<div>@Html.TextBoxFor(...city1...)</div>
<div class="hidden">@Html.TextBoxFor(....city2....)</div>

Then for the JS, you could just find the first hidden one and unhide it. 然后对于JS,您可以找到第一个隐藏的JS并将其取消隐藏。

$("#button").click(function(){
   $(".hidden").first().show();
});

You will also want to hide the "add city" button after all the cities that can be added have been added. 在添加了所有可以添加的城市之后,您还希望隐藏“添加城市”按钮。

Hope that helps. 希望能有所帮助。

Javascript to create textbox with properties... Javascript创建具有属性的文本框...

var input = document.createElement('input'); 
input.type = "text"; 
//...    
container.appendChild(input);

make a button and add an onClick function 制作按钮并添加onClick函数

<button id="myButton" onClick="javaScriptFunction();"> button Text </button>

in the function create the button (see code above) and add it to the HTML body ... 在函数中创建按钮(请参见上面的代码)并将其添加到HTML主体中...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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