动态添加 html.TextArea用于使用 JavaScript



我正在尝试将文本区域元素(使用TextAreaFor)添加到模态主体中。为了演示,我有两个按钮。单击一个元素时,会将 TextBoxFor 元素添加到模式主体中。单击另一个按钮时,将改为添加 TextAreaFor 元素。

文本框工作正常,但我在正确呈现文本区域时遇到问题。我只是 JavaScript 的初学者,但似乎 textarea 元素的结束标签导致字符串在到达最终的">"之前结束。

因此,单击该按钮,并添加html:

btn.onclick = function () {
$('.modal-body').html('<label>Question Label</label>@Html.TextAreaFor(c => c.Response, new { @class = "form-control" })');
modal.style.display = "block";
}

但是,这呈现为:

$('.modal-body').html('<label>Question Label/label><textarea class="form-control" cols="20" id="Response" name="Response" rows="2">X
</textarea>

使用"X"是我得到"未捕获的语法错误:无效或意外的令牌"错误。任何关于如何绕过的建议将不胜感激。

你可以尝试类似的东西

$(document).ready(function(){
var counter=0;
$("#addButton").click(function () {

if(counter>=5){
alert("you can insert only 5 textareas")}
else{

var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<label>Question Label </label>' + '<textarea rows=5 cols=50 name="textbox" id="textbox" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
}
})

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>

计数器变量用于确保添加的文本区域不超过 5 个。

最新更新