使用 jQuery 从下拉列表中获取所选文本
Get selected text from a drop-down list using jQuery
我在jquery上遇到了这个问题。我正在尝试测试两条路径:
it("should return true when country is valid", function() {
var validCountry = "Germany";
$("#fld_country option:selected").val(validCountry);
expect(isValid("#fld_country")).toBeTruthy();
});
it("should return false when country is invalid", function() {
var invalidCountry = "";
$("#fld_country option:selected").val(invalidCountry);
expect(isValid("#fld_country")).toBeFalsy();
});
validCountry
和invalidCountry
是从下拉列表中选择的选项。
这是 isValid 函数:
function isValid(selector) {
if (selector === "#fld_country option:selected") {
return validator.isSelectedField(selector);
}
else return validator.isFieldEmpty(selector);
}
这是isSelectedField
:
isSelectedField: function (selector) {
return $.trim($('selector option:selected').html())
问题是它由于以下原因而失败:
validate registration form should return true when country is valid
和
validate registration form should return false when country is invalid FAILED
我不知道问题出在哪里...有什么想法吗?
您的isValid
函数将始终返回validator.isFieldEmpty(selector)
,因为selector
值不匹配 - 您将#fld_country
与#fld_country option:selected
进行比较。也许这就是问题所在。
//编辑
好的。请确保设置了正确的模板。你提到你使用茉莉花-jquery夹具。在测试运行之前,您可以检查所选内容是否有任何选项。
我相信您正在尝试通过jquery设置选定的选项 - 这有一个错误,应该是:
$("#fld_country").val(validCountry);
如果您的<select>
看起来像这样,这将起作用(所以再次检查您的模板(
<select id="fld_country">
<option value="Poland">Poland</option>
<option value="Germany">Germany</option>
</select>
您遇到的另一个问题是isSelectedField
功能。而不是
return $.trim($('selector option:selected').html())
您可能希望拥有类似以下内容:
return $.trim($(selector + ' option:selected').html())
因为您想使用selector
变量而不是字符串。
相关文章:
- 使用谷歌应用程序脚本从工作表中获取值并将其显示在文本框中
- 如何获取经过编辑的文本
- 使用 jQuery 从下拉列表中获取所选文本
- 如何获取文本框组的值,并使用jquery将它们放入(key:Value)数组中
- 使用格式化文本获取 DIV 或跨度的动态宽度高度
- 通过搜索 td 文本获取嵌套表 ID
- 将 HTML 元素的文本获取到数组中
- 如何从响应文本获取 JSON 字符串到 JavaScript 中
- 如何根据选项文本获取选项索引
- 通过其文本获取dom节点
- 如何通过锚文本获取对象
- 在Javascript/JQuery中从超链接文本获取Href
- 如何将函数中的文本获取到此通知警报中
- 根据指定的文本获取标记
- 通过匹配文本获取json数据到数组中
- 如何通过id和输出文本获取选项元素
- 通过相邻的TH内部文本获取TD中的文本
- 如何将任何指定网页中的文本获取到变量中
- 通过内部文本获取所有元素
- 从给定的HTML文本获取JQuery