我试图使用jquery在textarea的末尾添加文本。
我的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
的小提琴的链接答案 0 :(得分:7)
要在text
内获取textarea
,您必须使用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
}
});
答案 1 :(得分:1)
用
替换你的两行var theMessage = $("#message").val();
var theDepartment = $("#departments").val();