Reputation: 145
I would like a variation on a watermark for a textbox. But I don't want the watermark to go away. I want it to act like a prefix that can't be typed over or removed. I don't want to use an HTML/CSS solution such as:
<div style="border: solid 1px black; width:250px;">
<label style="border:none;">prefix_</label>
<input type="text" style="border:none;"/>
</div>
I even want the prefix submitted as part of the textbox value. I would like a jquery solution. But I must not be using the right keywords to search because I can't find one. Anyone have an idea?
Upvotes: 1
Views: 11633
Reputation: 2982
Try this: (Nicola Peluchetti's answer with some slight modifications)
Makes no effort to retain user's input if they mess with the prefix:
Attempts to retain user's input:
Upvotes: 1
Reputation: 11341
This would handle keeping the prefix permanent:
$('#field').keyup(function() {
var prefix = 'string'
if (this.value.substring(0, prefix.length) != prefix){
$(this).val(prefix)
}
});
Upvotes: 3
Reputation: 35360
Here's my attempt in jQuery: http://jsfiddle.net/5n6WF/
$(function() {
$('#field').val($('#field').data('prefix'));
original_value = $('#field').val();
$('#field').keyup(function() {
var f = $(this),
prefix = f.data('prefix'),
rx = new RegExp('^' + escape(prefix));
new_value = prefix + unescape(escape(f.val()).replace(rx, ''));
if (original_value != new_value) {
original_value = new_value;
f.val(new_value);
}
});
});
Upvotes: 0
Reputation: 555
You could prepend the prefix upon submitting the textbox. Like this you will not have to handle users trying to remove the prefix.
$('#submitbutton').click(function{
var valueiwant = "myprefix "+$('#textfield').val();
});
Hope this helps
Upvotes: 1
Reputation: 1422
Not sure how you'd add it to the text box (so it's not removable) but you could just add the prefix when calling the value of the text box. For example:
<input type = 'text' id = 'inputID' />
<script type = 'text/javascript'>
var MyVar = document.getElementById('inputID').value;
var finalVar = "prefix_" + MyVar;
MyVar.value = finalVar;
</script>
attach it to an "onclick function" or "onKeydown" function
Upvotes: 0