【发布时间】:2015-10-21 23:06:12
【问题描述】:
背景信息:
我编写了一些逻辑来将下拉框从页面上的位置 A 复制到表格中的新位置。 我(尝试)从下拉列表中选择一个值......然后在提交表单时,该值应包含在表单中。
问题
表单缺少下拉列表中的值(称为 location_id)。所以以下面的代码为例,当表单发布时,我应该有“location_id=4”
Jquery 代码:
这是复制下拉列表并尝试选择正确值的代码:
//edit button handler
$(".edit").click(function(e){
e.preventDefault(); //don't submit the form <input type="image"> is also treated as submit trigger
var location_id = this.id;
var menu = $( "#location_id" ).clone(); //clone the global list
//locate the associated "location_name" field for the selected row & hide the column
var location_name=$(this).parent().siblings().children("#location_name").hide();
var row_name = $(this).parent().siblings().children("#name").hide();
//replace location_name with the new menu
$(location_name).replaceWith(menu);
menu.find('option').each(function(i, opt) {
// OFFENDING LINE OF CODE???
if($(opt).attr('value') == location_id.toString()) $(opt).attr('selected', 'selected');
});
//change row name to input box for editing
var input = $(document.createElement('input'));
$(input).attr('type','text');
//$(input).attr('name','edit_row_name');
$(input).attr('value', $(row_name).text());
//replace exiting row_name with this new input box.
$(row_name).replaceWith($(input));
//show save button
var save_btn = $(this).siblings(".icon").show();
});
当此代码完成运行时,GUI 会在下拉列表中显示正确的值。但是,当我使用 Firefox 中的“Inspector”功能检查底层 HTML 时,我可以看到“selected”属性未设置。
所以不要像这样:(注意“selected”属性)
<select tabindex="1" name="location_id">
<option value="0">-- NONE --</option>
<option value="1">WWX</option>
<option value="2">Canada</option>
<option value="3">USA</option>
<option value="4" selected="">NYNY</option>
</select>
我会得到这样的东西:
<select tabindex="1" name="location_id">
<option value="0">-- NONE --</option>
<option value="1">WWX</option>
<option value="2">Canada</option>
<option value="3">USA</option>
<option value="4">NYNY</option>
</select>
但 NYNY 将是下拉菜单中显示的值。当您单击下拉菜单时,它会在列表中突出显示 NYNY。
因此,根据值在列表中选择正确项目的 javascript 代码似乎无法正常工作。 但我不确定出了什么问题,因为它“有点”工作。
谢谢。
编辑 1
这是我修改前表格的样子 http://pastebin.com/dXXFDrmd
这是我添加自定义逻辑后呈现的 html: http://pastebin.com/kxbU0fYZ
【问题讨论】:
-
根据我的经验,这是典型的浏览器行为。它不会更新 HTML 以显示
selected属性,但它已被选中。 -
选择的属性没有更新,但选择的属性是
-
@Stryner 那么如何获得为表单提交设置的值?
-
一旦将 HTML 加载到 DOM 中,页面的典型更改会更改 DOM,而不是加载的原始 html。
-
@A.Wolff ...嗯...尽管我使用了 attr 方法?
标签: javascript jquery html