删除jQuery中的子字符串

时间:2012-02-27 19:57:34

标签: jquery autocomplete combobox substring

我正在使用jQueryUI组合框。如果用户在option元素中输入的字符串不是select,则会使用该值创建新的option元素。问题是它目前在输入的值前面加上'undefined'。如何在提交之前删除'undefined'子字符串?这是代码:

change: function(event, ui) {
    if (!ui.item) {
        var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
            valid = false;
        select.children("option").each(function() {
            if ($(this).text().match(matcher)) {
                this.selected = valid = true;
                return false;
            }
        });
        if (!valid) {
            new_value = self.options.precede_new_with + $(this).val();
            option = $('<option value="' + new_value + '">' + $(this).val() + '</option>');
            select.append(option);
            select.val(new_value);
            return false;
        }
    }
}​

4 个答案:

答案 0 :(得分:2)

你的意思是这条线?

new_value = self.options.precede_new_with + $(this).val();

创建组合框的实例时,请将此选项设置为空字符串:

$( "#combobox" ).combobox({
    precede_new_with: ''
});

或者更改实现以通过在这种情况下返回空字符串来检查可能的未定义:

new_value = (self.options.precede_new_with || '' ) + $(this).val();

答案 1 :(得分:2)

看来问题是self.options.precede_new_with正在返回'undefined'。

答案 2 :(得分:0)

在附加option时,您可以检查它是否未定义,然后在前面添加空字符串。这样,您在提交表单时无需进行任何处理。

试试这个。

if ( !valid ) {

   new_value = (self.options.precede_new_with || '') + $(this).val();
           //this will prepend empty string if undefined

   option = $('<option value="' + new_value + '">' + $(this).val() + '</option>');
   select.append(option);
   select.val(new_value);
   return false;
}

答案 3 :(得分:0)

感谢您的建议,抱歉我花了一点时间回来,我一直都很忙。无论如何,我最终只需要设置new_value等于$(this).val()并摆脱self.options.precede_new_with