我有一个这样的tr
<tr>
<td><input id="checked1" type="checkbox" class="cd" value="1" style="margin:6px 0 0 0;"></td>
<td style="padding:6px 0 0 0;"><b>Staff Courtesy</b></td>
<td>
<select name="questionType" id="questionType" class="qType QSelect" style="padding:3px;">
<option value="">--Select--</option>
<option value="1">text</option>
<option value="2">rating</option>
<option value="3">boolean</option>
<option class="show-checkboxes" value="4">option</option>
</select>
</td>
<td width="35%" style="padding:10px 0 0 0;" class="Fsize12 out" id="a1">Enter Some Text</td>
<td><input type="hidden" id="optionInputa1"></td>
</tr>
最初,第三个 td 不显示任何内容,但如果下拉菜单发生变化,则第三个 td 中会出现一些文本
例如,如果选择文本,则在第三个 td 中,它将显示文本位置。其代码如下
var option='<a href="#" class="checkbox-inline" onclick="getModal(this)">Get Options</a>';
var txt = 'Enter Some Text';
var bool = 'Yes or No';
var rating='place for rating';
$('#addNew .QSelect').change(function () { //alert(this.value);
if (this.value == '4') $(this).closest('tr').find('.out').html(option);
if (this.value == '1') $(this).closest('tr').find('.out').html(txt);
if (this.value == '3') $(this).closest('tr').find('.out').html(bool);
if (this.value == '2') $(this).closest('tr').find('.out').html(rating);
});
$('#addNew .QSelect').change(function() {
var cbs = $(this).closest('td').next().children();
if ($('.show-checkboxes', $(this)).is(':selected')) {
$(cbs).show();
} else {
$(cbs).hide();
}
}).trigger('change');
$('#addNew .cd').change(function() {
var checked = $(this).is(':checked');
// $('#optionSave').removeAttr('disabled');
if ($(".cd:checkbox:checked").length > 0)
{
$('#optionSave').removeAttr('disabled');
}
else
{
$('#optionSave').attr('disabled',true);
}
$(this).closest('td').siblings().find('select, input').prop('disabled', !checked);
}).trigger('change');
}
我的问题 我想以编程方式设置下拉菜单的值。例如,如果我想将下拉菜单设置为文本,那么我必须将其值设置为 1。
这是它的代码
$.each(data1.savedQuestionTypesList, function(index, currQueTyp) {
console.log("queeeeeeeeeeeee "+currQueTyp.pqid.qid.id + "qtid name"+currQueTyp.qtid.name);
$('#checked'+currQueTyp.pqid.qid.id).closest('tr').find('select').val(currQueTyp.qtid.id);
});
因此,随着下拉值的变化,第三个 td 也会发生变化。
例如
在上面的每个循环中,如果 currQueTyp.pqid.qid.id=1
和 currQueTyp.qtid.id=1
则下拉列表更改为 text
并且在第三个 td 文本位置将出现。
但是如果我使用按钮,那么为什么第三个 td 不会改变。
例如有按钮
<button type="button" id="testButton">test</button> and upon clicking I want to change the drop down value
$('#testButton').click(function(){
$('#checked1').closest('tr').find('select').val(1);
});
所以这里下拉值发生变化,但第三个 td 没有变化
最佳答案
<强> Working Demo
将此用于按钮事件,
- 在您的情况下,
#checked1
是一个完全错误的选择器。您有多个具有相同 ID 的复选框。那是行不通的。在这种情况下使用类选择器。 - 并且您需要选中复选框,因此
:checked
。
$('#testButton').click(function(){
$('.cd:checked').closest('tr').find('select').val(1).change();
});
关于javascript - 如何在td中动态追加html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24197785/