选择2使用jquery选择随机选项

时间:2017-04-18 13:15:45

标签: javascript jquery select2

<tr class="form-row form-row-odd form-row-err  form-cols-2 form_element_company_id">
                    <th>Company&nbsp;<span class="required">*</span></th>
                    <td><select name="company_id" class="selectmenu input-inf select2-initialized select2-hidden-accessible" tabindex="-1" aria-hidden="true"><option value="">— None —</option>
<option value="1" class="sub-option-0 ">Option 1</option>
<option value="14" class="sub-option-0 ">Option 2</option>
<option value="45" class="sub-option-1 " data-parent-name="Option 2="14">Option 2-1</option>
<option value="46" class="sub-option-1 " data-parent-name="Option 2" data-parent-id="14">Option 2-2</option>
<option value="47" class="sub-option-1 " data-parent-name="Option 2" data-parent-id="14">Option 2-3</option>
<option value="29" class="sub-option-0 ">Option 3</option>
<option value="30" class="sub-option-0 ">Option 4</option>
<option value="31" class="sub-option-0 ">Option 5</option>
        </tr>

我尝试使用selenium IDE设置一些测试,但我很难确定如何使用jquery或js来选择随机选项。

1 个答案:

答案 0 :(得分:0)

function setUserCompany(){
var companyField = $('select[name="company_id"]');
if (companyField.length == 0) { 
return; 
}
var options = companyField.find('option');
if (options.length == 0) {
return; 
}
var randomIdx = Math.floor((Math.random() * options.length)+1);
var randomValue = $(options.get(randomIdx)).attr('value');
companyField.select2().val(randomValue).trigger('change'); 
}

我遇到的问题是它没有将我的$ select识别为jquery对象