Reputation: 1270
I have input text field and I have a placeholder inside. When I click on input, placeholder disappears. I am using jQuery Watermark plugin for this placeholders. I want to change this behavior. I need that placeholder to stay in input when user types in this field.
Nice example would be field for e-mail. In one step, user gives me domain name, for example 'foo.com'. Placeholder for e-mail will look like '@foo.com'. When user clicks on this field, I want this placeholder to act like value of that input, but unchangeable. Default value of my e-mail input field is '@foo.com', when user types in 'bar' its '[email protected]'.
I hope you understand what I am trying to do :) How can I achieve this behavior?
Upvotes: 3
Views: 590
Reputation: 23
You can use this function. I have used it once in my code (with help from stackoverflow) :
html:
<input type="text" id="t1" placeholder="@foo.com">
javascript:
function setRange(input, textStart, textEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(textStart, textEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', textEnd);
range.moveStart('character', textStart);
range.select();
}
}
function setCursorPos (input, pos) {
setRange(input, pos, pos);
}
$("#t1").click(function() {
$(this).val("@foo.com");
setCursorPos(document.getElementById("email"), 0);
});
Upvotes: 1
Reputation: 356
You can just have a absolutely positioned label for this. Also, you could handle onclick and onblur events on the input in case you want to hide the label. Try this:
<html>
<body>
<form>
<div style=" position:relative;z-index:1;">
<label style="position:absolute; line-height:28px;text-align:left;left:150px;top:4px;overflow:hidden; height:28px;width:200px; z-index:2;color:#cacaca" for="email">@foo.com</label>
<input type="text" value="" name="email" style="border:1px solid #939393; line-height:28px;text-align:left;font-size:14px;padding-left:5px;color:#000;z-index:1;width:300px;height:30px" />
</div>
</form>
</body>
</html>
Upvotes: 2