2011-03-03 136 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" />

相关问题