Using jQuery, how can I add a default value of http://
into an input field that can’t be removed, but that still allows you to type a URL after it?
Defa
Check this format util and a prefix implementation for it:
input
event (keyboard, mouse, drag-n-drop, etc.)// Util function
function addFormatter (input, formatFn) {
let oldValue = input.value;
const handleInput = event => {
const result = formatFn(input.value, oldValue, event);
if (typeof result === 'string') {
input.value = result;
}
oldValue = input.value;
}
handleInput();
input.addEventListener("input", handleInput);
}
// Example implementation
// HOF returning regex prefix formatter
function regexPrefix (regex, prefix) {
return (newValue, oldValue) => regex.test(newValue) ? newValue : (newValue ? oldValue : prefix);
}
// Apply formatter
const input = document.getElementById('link');
addFormatter(input, regexPrefix(/^https?:\/\//, 'http://'));
input { padding: 0.5rem; font-size: 1rem; }
<input type="text" id="link" />
Pure CSS based solution we did make div wrapper and span input combination, please do refer follows
.lable {
background-color: #dedede;
width: 50%;
padding: 15px;
border: 1px solid #FF0000;
-moz-border-radius: 5px;
border-radius: 5px;
padding: 5px 5px;
}
.snehainput {
background-color: #dedede;
border-left: 1px solid #000000;
border-right: 0px;
border-top: 0px;
border-bottom: 0px;
padding: 2px 5px;
color: #666666;
outline: none;
}
<div class="lable">
<span class="prefix">971</span>
<input class="snehainput" type="text" value="" />
</div>
$("input").keyup(function(e) {
var oldvalue = $(this).val();
var field = this;
if (field.value.indexOf('http://') === -1 &&
field.value.indexOf('https://') === -1) {
$(field).val('http://');
}
});
<input type="text" value='http://'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
I’ve seen some web forms include this value outside of the field, e.g.
<label for="url">URL:</label> http:// <input id="url" type="text">
But if you’re dead set on enforcing the value via JavaScript (and bear in mind that users can turn JavaScript off), you could write a function that fires every time the user types in the field, and adds http://
to the start of the field if it’s not there. E.g.
<label for="url">URL:</label> <input id="url" type="text" value="http://">
$('#url').keyup(function(){
if( this.value.indexOf('http://') !== 0 ){
// Add lots more code here so that this actually works in practice.
// E.g. if the user deletes only some of the “http://”, if the
// user types something before the “http://”, etc...
this.value = 'http://' + this.value;
}
});