2011-03-03 154 views
2

如何將<input type="text"...設置爲只讀,但允許刪除其值?HTML <input type =「text」... as <input type =「file」

換句話說,如何實現像<input type="file"...這樣的行爲,您無法手動輸入文件路徑,但可以刪除「瀏覽」按鈕注入的內容。

+0

也許不可能沒有JavaScript。你可以使用它嗎?你可以使用jQuery嗎? – 2011-03-03 10:12:46

+0

是的,我很開放的任何javascript – eomeroff 2011-03-03 10:17:16

+0

檢查我的答案,你也可以將onclick移動到type =文本字段,如果你想清除onclick – Michael 2011-03-03 10:19:51

回答

1

的jQuery:

<input type="text" id="name1" name="name" readonly="readonly" value="demovalue" /> 
<input type="button" onclick="$('#name1').val('');" value="clear"> 

基本:

<input type="text" id="name1" name="name" readonly="readonly" value="demovalue" /> 
<input type="button" onclick="document.getElementById('name1').value='';" value="clear"> 
0

這樣的事情?

<input type="text" onclick="this.value='',this.disabled='disabled'" value="text"> 

,如果你不想改變背景爲灰色,您可以添加和下面的CSS:

input[disabled] {background:white;border:1px solid #7F9DB9} 

演示:http://jsfiddle.net/utw8y/1

更新

只使用刪除或退格鍵,您可以使用以下jQuery代碼:

$('input').keypress(function(event) { 
    if ((event.which!='0') && (event.which!='8')) { 
    event.preventDefault(); 
    } else { 
    $(this).val("");  
    } 
}); 

演示:http://jsfiddle.net/utw8y/2/

+0

不完全一樣,我可以用鍵盤上的刪除按鈕和退格鍵刪除谷歌嗎? – eomeroff 2011-03-03 10:27:42

1

考慮到這個HTML:

<input type="text" class="onlydelete" value="Nyedva Nyedva" /> 

以下jQuery的功能將只允許Backspace鍵在輸入字段中使用onlydelete類。

$('.onlydelete').keypress(function (e) { 
    return (e.which===8); 
}); 

UPDATE:

我發現,你還需要刪除鍵。我想你也想讓箭頭鍵讓用戶移動插入符號。對於這些特殊鍵,您可以使用keydown。以下片段僅允許刪除(46),退格鍵(8)和箭頭鍵(37-40)。

$('.onlydelete').keydown(function (e) { 
    return (e.which===46 || e.which===8 || (e.which>=37 && e.which<=40)); 
}); 

更新2:

有關添加類的其他好處是,你可以很容易地風格的CSS這些特殊的輸入。例如:

.onlydelete { background-color: #aaaaaa; } 
0

試試這個:

var inputBox = document.getElementById("inputBox"); 
 

 
inputBox.onkeypress = checkInput; 
 

 
function checkInput(e) { 
 
    // checking if the pressed key is delete or backspace 
 
    // if not, we prevent character input 
 
    if (e.keyCode != 8 || e.keyCode != 46) { 
 
    e.preventDefault(); 
 
    } 
 
} 
 

 
// also a button to clear the input value 
 
document.getElementById("delete").onclick = function() { 
 
    inputBox.value = ""; 
 
}
<input type="text" id="inputBox" value="this is a test" /> 
 
<input type="button" id="delete" value="delete" />