如何从select
元素中获取父option
的ID。
我试过了:
if (formInput.value === "NC") {
//console.log($('option[value="NC"]').closest('select').attr('id'));
var a = $('option[value="NC"]').parent().attr('id');
console.log(a);
}
从formInput === "NC"
我想获得身份capability_32
<select class="form-control" id="capability_32" name="capability_32" onchange="showDropDown('nc32', this.value)">
<option value="0">-- Outcome --</option>
<option value="C">Compliant</option>
<option value="OBS">Observation</option>
<option value="NC">Non-Compliant</option>
<option value="NA">Not Applicable</option>
</select>
JS功能
var showDropDown = function showDropDown(div, value) {
'use strict';
var nc = document.getElementById(div);
if (value === "NC" || value === "OBS") {
nc.style.display = 'block';
} else {
nc.style.display = 'none';
}
}
function fetchOrderFromLocalStorage() {
localKey = $('#ddl').children(':selected').text();
var mcs = localStorage.getItem(localKey);
var jsn = JSON.parse(mcs);
if (mcs.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i],
$el = $("[name='" + formInput.name + "']"),
type = $el.attr('type');
switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="' + formInput.value + '"]').attr('checked', 'checked');
break;
case 'textarea':
$el.val(formInput.value);
default:
$el.val(formInput.value);
}
if (formInput.value === "NC") {
//console.log($('option[value="NC"]').closest('select').attr('id'));
var a = $('select').filter(':selected');
console.log(a);
$(a).css("display", "block");
}
}
}
答案 0 :(得分:0)
好的,所以它有效:证明如下(我把代码放在onchange函数中)
var showDropDown = function showDropDown(div, value) {
'use strict';
console.log(value);
var nc = document.getElementById(div);
if (value === "NC") {
//console.log($('option[value="NC"]').closest('select').attr('id'));
var a = $('option[value="NC"]').parent().attr('id');
console.log(a);
}
if (value === "NC" || value === "OBS") {
//nc.style.display = 'block';
} else {
//nc.style.display = 'none';
}
}
http://jsfiddle.net/18xdq19g/1/
让我相信你的formInput变量是错误的,还是代码的位置?你如何定义formInput?