[英]jQuery SELECT with Textarea
只是想知道是否有人可以幫助我解決問題,我不完全了解為什么它不起作用。
我有這個小提琴, http://jsfiddle.net/uomt99zp/
它在做什么:從下拉框中選擇時,將該單詞插入到textarea中。 當textarea沒有被“觸及”時,它做了什么。
如果您在框中鍵入內容,然后嘗試選擇一個項目,它將無法正常工作。
我不確定為什么這不會更新textarea。 也許有人可以對這個問題有所了解?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
要回答“為什么”它不起作用,這是因為,textarea的內容代表其默認值。 因此,當您將元素追加到textarea時,您可以更改此textarea的默認值。
因此,只要您沒有輸入,它就會更改textarea。一旦您輸入,即使您刪除了textarea的所有文本,也不會再使用默認值。
通過使用.append,你只是簡化你的輸出字符串,如果你只想要下拉元素,最好使用.text()或.val()方法
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(),. html()和.text()方法不適用於表單元素,用於設置/獲取from元素的值。應該使用.val()方法:
你的代碼正在運行...我在visual studio中嘗試過....只有我所做的改變是我將腳本保留在選項控件下...我不確定。對我來說它的工作正常。
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
您應該使用val()方法控制輸入值
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
只需用文字替換附加
這是更新的小提琴
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('。template')。val(text); 這不適用於IE <= 7});
http://jsfiddle.net/rrehan/uomt99zp/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.