admin管理员组文章数量:1391987
I use <template>
element to render a table's row. A <select>
element inside in a row and I try to set selected value but the code didn't work for me.
<template id="template">
<tr>
<td>
<select class="form-control status">
<option value="1">In Progress</option>
<option value="2">Done</option>
<option value="3">Canceled</option>
</select>
</td>
</tr>
</template>
Than I call this function below.
$.each(data.Object, function (index, item) {
var template = document.querySelector('#template');
template.content.querySelector('.select > option[value="' + item.Status + '"]').selected = true;
var cloneAction = document.importNode(template.content, true);
var tbody = document.querySelector("#mytbody");
tbody.appendChild(cloneAction);
})
I use <template>
element to render a table's row. A <select>
element inside in a row and I try to set selected value but the code didn't work for me.
<template id="template">
<tr>
<td>
<select class="form-control status">
<option value="1">In Progress</option>
<option value="2">Done</option>
<option value="3">Canceled</option>
</select>
</td>
</tr>
</template>
Than I call this function below.
$.each(data.Object, function (index, item) {
var template = document.querySelector('#template');
template.content.querySelector('.select > option[value="' + item.Status + '"]').selected = true;
var cloneAction = document.importNode(template.content, true);
var tbody = document.querySelector("#mytbody");
tbody.appendChild(cloneAction);
})
Share
Improve this question
asked Apr 21, 2017 at 7:47
user6212651user6212651
2
-
Use
$('#template select > option[value="' + item.Status + '"]').prop('selected', true);
– Tushar Commented Apr 21, 2017 at 7:49 - didnt work ..... – user6212651 Commented Apr 21, 2017 at 7:52
1 Answer
Reset to default 2A couple of things:
- First of all, your selector needs to be
select ...
and not.select ...
- An easier way to set the selected option is to set the
value
on the<select>
element itself. - And finally:
It looks like some state info is lost on document.importNode()
, so you need to wait until you have the cloned element to set that state:
var template = document.querySelector('#template');
//Works:
template.content.querySelector('label').textContent = item.Name;
template.content.querySelector('input').checked = true;
//Doesn't work until the elements is cloned:
//template.content.querySelector('select').value = item.Status;
var cloneAction = document.importNode(template.content, true);
//Now it works:
cloneAction.querySelector('select').value = item.Status;
Example: https://jsfiddle/8pervtto/
本文标签: javascriptsetting selected value via querySelector functionStack Overflow
版权声明:本文标题:javascript - setting selected value via querySelector function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744765429a2624009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论