HTML <input type="text"... as <input type="file"
How to set <input type="text"...
to be read-only but to allow deletion of its value?
In other words how to achieve behavior like <input type="file"...
, where you cannot manually enter path to file but you can dele开发者_Python百科te what has been injected by "Browse" button.
jquery:
<input type="text" id="name1" name="name" readonly="readonly" value="demovalue" />
<input type="button" onclick="$('#name1').val('');" value="clear">
basic:
<input type="text" id="name1" name="name" readonly="readonly" value="demovalue" />
<input type="button" onclick="document.getElementById('name1').value='';" value="clear">
Considering this HTML:
<input type="text" class="onlydelete" value="Nyedva Nyedva" />
The following jQuery function will only allow the Backspace key to be used in the input fields with class onlydelete
.
$('.onlydelete').keypress(function (e) {
return (e.which===8);
});
UPDATE:
I've found that you also need the Delete key. And I guess you would also like to allow the arrow keys to let the user move the caret. For these special keys, you can use keydown. The following snippet only allows Delete (46), Backspace (8), and arrow keys (37-40).
$('.onlydelete').keydown(function (e) {
return (e.which===46 || e.which===8 || (e.which>=37 && e.which<=40));
});
UPDATE 2:
The other good thing about adding a class is that you can easily style these special inputs with css. For example:
.onlydelete { background-color: #aaaaaa; }
something like this?
<input type="text" onclick="this.value='',this.disabled='disabled'" value="text">
if you don't want to change the background to grey, you can add and the following css:
input[disabled] {background:white;border:1px solid #7F9DB9}
Demo: http://jsfiddle.net/utw8y/1
Update
Using only delete or backspace keys you can use the following jQuery code:
$('input').keypress(function(event) {
if ((event.which!='0') && (event.which!='8')) {
event.preventDefault();
} else {
$(this).val("");
}
});
Demo: http://jsfiddle.net/utw8y/2/
Try this:
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" />
精彩评论