我有一个小胡子模板,呈现如下:
<script id="myTemplate" type="text/x-template">
<tr data-name="{{name}}">
<td>
<select id="titlesDropDown" name="SelectedTitleId"><option value="">--Select Title--</option>
<option value="1">Mr</option>
<option value="2">Miss</option>
<option value="3">Mrs/Corporate</option>
<option value="4">Dr</option>
<option value="5">Other</option>
</select>
</td>
<td class='hidden'><input type="text" name="Other" value=""/></td>
<td>{{name}}</td>
<td><input type="text" name="Age" value=""/></td>
<td>
<button type="button" class="removeRowBtn">
Remove Row
</button>
</td>
</tr>
</script>
您可以看到其他输入字段的td已隐藏。可以在表中添加多行,以便将多个人添加到我的数据库中。如果“其他”是下拉列表中的选定字段,我只需要显示此其他TD。但是使用删除按钮我发现隐藏了其他单元格时,删除按钮会在具有其他标题的表格标签的单元格中呈现。然后,如果用户选择其他类应该被删除,这将留下非常“跳跃”的行为。是否有更好的方法来解决这个问题?
我也发现该功能不能完全删除并显示其他输入文本框。我这样做的js目前是:
$(document).on('change', '#titlesDropDown', function () {
//var selectedValue = $("#titlesDropDownn option:selected").text();
// not selecting correctly if there are multiple rows in the table
var selectedValue = $('#titlesDropDown').closest('select').find(':selected').html();
// if else not quite working to show hide that Other td cell
if (selectedValue == 'Other') {
$(this).closest('td').next('td').find('input').show();
} else {
$(this).closest('td').next('td').find('input').hide();
}
});
答案 0 :(得分:1)
class="hidden"
而不是<td>
上有<input>
,但您隐藏并显示<input>
。您想隐藏/显示<input>
,而不是<td>
,因此请将class="hidden"
移至<input>
。这仍然没有完全解决&#34;跳跃&#34;行为。
您可以更改其<input>
样式,而不是隐藏和显示visibility
。这样你可以隐藏它,但它仍然会占用相同的空间。
HTML:
<td>
<input type="text" name="Other" value="" style="visibility: hidden;" />
</td>
JavaScript的:
if (selectedValue == 'Other') {
$(this).closest('td').next('td').find('input').css({ visibility: 'visible' });
} else {
$(this).closest('td').next('td').find('input').css({ visibility: 'hidden' });
}
当然,您还可以在<td>
上设置最小宽度,这样即使隐藏<input>
,它也会占用相同的空间。这是一个jsfiddle,与下拉列表中<input>
的{{1}}相同。
禁用/启用,而不是隐藏/显示,将是另一种选择。
还有一件事,如果您有多个包含<td>
元素的行,则不应该为其赋予<select>
值,因为多个元素将具有相同的id
。使用id
代替class
。
答案 1 :(得分:0)
您需要使用val()方法而不是html()方法:
var selectedValue = $('#titlesDropDown').closest('select').find(':selected').val();
答案 2 :(得分:0)
每行一个下拉列表,您无法为它们提供相同的ID。 Ids必须是唯一的。请改用class="titlesDropDown"
。
然后
$(document).on('change', '.titlesDropDown', function() {
if ($(this).val() == 'Other') {
$(this).closest('td').next('td').find('input').show();
} else {
$(this).closest('td').next('td').find('input').hide();
}
});