使用模糊文本字段

时间:2012-04-14 13:13:32

标签: jquery

我有两个输入文本字段。一个用于输入文章的标题,一个用于文章的固定链接。我想要做的是在永久链接字段被禁用,直到文本被插入到标题字段中,并且当用户将焦点从标题字段中取出时,它运行自定义正则表达式以用连字符替换空格并用小写字母替换任何大写字母。 / p>

<input type="text" id="title" name"title" />
<input type="text" id="permalink" name="permalink" />

1 个答案:

答案 0 :(得分:6)

使用 jQuery ...

真的很容易
var permalinkInput = $('#permalink');

$('#title').change(function() {
    permalinkInput.prop('disabled', !$(this).val());
}).change().blur(function() {
    $(this).val(function(i, value) {
        return value.replace(/\s+/g, '-').toLowerCase();
    });
});​

jsFiddle

如果你没有jQuery但只需要支持符合标准的现代浏览器,那就是......

var permalinkInput = document.querySelector('#permalink'),
    titleInput = document.querySelector('#title');

permalinkInput.disabled = true;

titleInput.addEventListener('change', function() {
    permalinkInput.disabled = !titleInput.value;
}, false);

titleInput.addEventListener('blur', function() {
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase();
});​

jsFiddle

如果您没有jQuery并且不得不支持我们的旧IE 朋友,那么它看起来就像......

var permalinkInput = document.getElementById('permalink'),
    titleInput = document.getElementById('title');

var addEvent = function(element, type, callback) {
    if (element.addEventListener) {
        element.addEventListener(type, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + type, callback);
    } else {
        element['on' + type] = callback;
    }
}

permalinkInput.disabled = true;

addEvent(titleInput, 'change', function() {
    permalinkInput.disabled = !titleInput.value;
});

addEvent(titleInput, 'blur', function() {
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase();
});​

jsFiddle

请注意,事件注册的旧回退是分配on*属性。这将覆盖在那里分配的任何先前属性。

如果您真的想为这些古老的浏览器注册多个事件,您可以修改属性分配以使用自定义处理程序,该处理程序在需要时注册并触发多个事件。