使用 jQuery 从下拉列表中获取所选文本

Get selected text from a drop-down list using jQuery

本文关键字:文本 获取 jQuery 下拉列表 使用      更新时间:2023-09-26

我在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进行比较。也许这就是问题所在。

//编辑

好的。请确保设置了正确的模板。你提到你使用茉莉花-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变量而不是字符串。