javascript - 使用 jQuery 从下拉列表中获取选定的文本

标签 javascript 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();
});

validCountryinvalidCountry 是从下拉列表中选择的选项。

这是 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 。 也许这就是问题所在。

//编辑

好的。确保您设置了正确的模板。您提到您使用 jasmine-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变量不是字符串。

关于javascript - 使用 jQuery 从下拉列表中获取选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257943/

相关文章:

javascript - 使用 jquery 获取输入字符串

javascript - 为什么当我取消静音后,自动播放会停止工作?

javascript - PHP-Jquery-AJAX,显示弹出消息

javascript - 发送 AJAX 请求以获取 Google map 路线时出错(访问 header )

javascript - jQuery如何在一系列延迟后循环一个函数

javascript - HTML表格中的隐藏行导致问题

javascript - 水平条形图 y 轴对齐

javascript - d3.format 变量的千位分隔符?

jquery - 固定位置 div 仅垂直

javascript - 根据单击的类别过滤器隐藏/显示 li 项