[英]Set Select Dropdown with jQuery
The question has been asked multiple times, but this is not a repeat. 这个问题已被问过多次,但这不是重复。 I am using a for loop to search through a div of elements including select, input etc. It matches the class name to an objects parameter and if it matches it sets the value of the element.
我正在使用for循环来搜索包括选择,输入等在内的div元素。它将类名与对象参数匹配,如果匹配则设置元素的值。
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
$(editClone).find('.' +i).val(obj[i]);
}
}
It works fine on input elements, but with the select element it removes all the options and simply sets the value on the actual element tag. 它可以在输入元素上正常工作,但是使用select元素可以删除所有选项,而只需在实际元素标签上设置值即可。
This is the select statement before I run my javascript: 这是我运行JavaScript之前的select语句:
<select class="type">
<option value="Home">Home</option>
<option value="Work">Work</option>
<option value="Mobile">Mobile</option>
<option value="Other">Other</option>
</select>
And after I run the code (inspected in firebug to verify): 然后运行代码(在Firebug中进行检查以进行验证):
<select class="type">Mobile</select>
Why does it do this? 为什么这样做呢? I thought val() was supposed to set a matching option tag to selected.
我以为val()应该将匹配的选项标签设置为selected。 The object value and option tags are matching, but it does not do what it is supposed to.
对象值和选项标签是匹配的,但没有达到预期的效果。 What am I doing wrong here?
我在这里做错了什么?
Turns out I had the DIV I was trying to clone nested in the wrong place in the HTML as well as a bad clone call in the javascript. 原来,我尝试克隆的DIV嵌套在HTML的错误位置,以及JavaScript中的错误克隆调用。 Totally unrelated errors.
完全不相关的错误。 The answer below is correct, it just didn't work in my situation because I didn't understand the problem I was having.
下面的答案是正确的,因为我不了解自己遇到的问题,所以在我的情况下它不起作用。
<select class="type">Mobile</select>
Is not valid. 无效。 A select needs to have
option
tags inside of it 一个选择需要在其中包含
option
标签
Here's a working version of your code: 这是您的代码的有效版本:
<select class="type">
<option value="0">0</option>
<option value="A">A</option>
</select>
Script: 脚本:
$(function() {
var obj = { type: "A" };
var editClone = $(document);
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
$(editClone).find('.' + i).val(obj[i]);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.