我正在尝试使用 jquery 在文本区域的末尾附加文本。
我的 html 代码如下所示:
<textarea class='form-control' placeholder="Write something..." id="message" name="message" size='20'></textarea>
<fieldset class="form-group">
<div class="checkbox">
<label for="deptList">
<label for="departments" id="deptList">Select a department
<small>use this in case you've set up your account to <a
href="#"> include a department</a> at the end
of the text
</small>
</label>
<input type="checkbox" value="" class="checkbox-inline" id="deptCheck">
<select class="form-control" id="departments">
<option>Dept. 1</option>
<option>Dept. 2</option>
<option>Dept. 3</option>
<option>Dept. 4</option>
<option>Dept. 5</option>
<option>Dept. 6</option>
<option>Dept. 7</option>
</select>
</label>
</div>
</fieldset>
我附加文本的脚本是:
$('#deptCheck').click(function() {
var theMessage = $("#message").text();
var theDepartment = $("#departments").find(":selected").text();
if ($(this).is(":checked")) {
console.log(theMessage + theDepartment);
$("#message").val(theMessage + theDepartment);
}else {
alert('you have included department in your text, please remove it to avoid extra charges');
}
});
到目前为止: - 我可以将下拉选项的值添加到文本区域,但是当我添加它时,它会清除所有现有文本。
我想要实现的是用户在文本区域中键入一些文本,然后用户从文本区域下方的下拉列表中选择一个选项,然后将下拉列表的文本添加到键入文本的末尾在文本区域。我已经尝试过在线资料,但我似乎做对了。我哪里出错了?
这里是一个指向相同 JS Fiddle 的 fiddle 的链接
最佳答案
要在 textarea
中获取 text
,您必须使用 val()
函数:
$("#message").val();
$('#deptCheck').click(function() {
var theMessage = $("#message").val();
var theDepartment = $("#departments").find(":selected").text();
if ($(this).is(":checked")) {
console.log(theMessage + theDepartment);
$("#message").val(theMessage + theDepartment);
} else {
alert('you have included department in your text, please remove it to avoid extra charges') //disable input
}
});
关于javascript - 使用 jQuery 将文本附加到文本区域的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36600264/