2012-04-14 105 views
2

我有兩個輸入文本字段。一個是輸入文章的標題,另一個是文章的固定鏈接。我想要做的是永久性字段禁用,直到文本插入到標題字段中,並且當用戶將焦點從標題字段中移出時,它會運行自定義正則表達式以用連字符替換空格,並將任何大寫字母減小。使用模糊與文本字段

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

你自己到底想到了什麼? – sg3s 2012-04-14 13:14:30

+0

嗯,我正在尋找jQuery模糊函數的文檔,我想知道如果這就是我應該使用的,除此之外,我期待看看是否有其他人使用它遠程接近這一點,並沒有看到任何東西線上。 – 2012-04-14 13:17:43

回答

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*屬性。這將覆蓋此處分配的任何以前的屬性。

如果您確實想爲這些古老的瀏覽器註冊多個事件,您可以修改屬性分配以使用自定義處理程序,該處理程序會在需要時註冊並觸發多個事件。

+1

+1代碼的效率,雖然因爲永久鏈接只有一次使用它不需要是一個變量。 – sg3s 2012-04-14 13:22:23

+1

@ sg3s然而,它會被*選中*在每個'change'事件上不必要的。 – alex 2012-04-14 13:23:00

+0

正確。沒有注意我猜:) – sg3s 2012-04-14 13:25:38