Show placeholder instead of the default value in html form - javascript

A text field in html form have a default value,
but I would like to show the placeholder instead of the default value.
any ideas?

From what you said here it sounds like you actually want to listen for the focus and blur events and just clear the contents of the <input> with some kind of cache to restore it if nothing gets typed.
<input id="foo" type="text" value="" data-value="" />
Then in script
var foo = document.getElementById('foo');
foo.addEventListener('focus', function () {
this.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
DEMO

Provided you are only concerned with browsers that support HTML5, the following is an option:
<input type="text" name="myText" placeholder="My Placeholder">

<input type="text" name="foo" placeholder="Foo Name"/>
<input type="hidden" name="foo" value="foo"/>

On one hand, it is doable; on the other hand, I'm not sure why you should.
$('input[type="text"]').each(function (i, o) {
var inputBox = $(o),
swapInValue = function () {
inputBox.val(inputBox.data('val'));
},
swapOutValue = function () {
inputBox.data('val', inputBox.val()).val('');
};
inputBox.blur(swapOutValue).focus(swapInValue);
});

Related

Automatically inserting window.location.hash into html input value?

Here's what I'm essentially trying to do:
<input type="text" class="form-control" value="window.location.hash">
What's the proper way to insert the window.location.hash into the input's value?
Note: I've found several ways to do this when people are required to click a button, but nothing that explains how to do it automatically when the page loads.
You'll need to assign this after the page loads, or at least the element
<input type="text" class="form-control" id="hash" value="">
<script>
window.onload=function() {
document.querySelector("#hash").value = window.location.hash
}
</script>
Just get the element and change its value using JavaScript. In this Snippet, I'm redirecting to a different hash, just for example purposes.
const input = document.querySelector("input.form-control");
// Redirect to different hash for example
window.location.hash = "abcdef";
input.value = window.location.hash;
<input type="text" class="form-control" />
You need JS script for that:
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('location');
input.value = window.location.host; // change .host to .hash
})
<input id="location">

Show alert on textbox on invalid input

I know that I can restrict textbox to pass only numeric with this:
<input type="number" id="box_1">
But alert is showing only after clicking submit button. How can I show it in on-key event with JavaScript?
Go with Jquery. something like this:
<input type="text" class="numbersOnly" value="" />
And:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
I think you should use this : it detects if the user has entered letters
<script type="text/javascript">
$(document).ready(function () {
var txtbox_1 = $('#box_1');
// Setup the event
txtbox_1.focusout(function () {
var last = $.data(txtbox_1, "last");
if ($(this).val().match(/[a-z]/i))
alert("Letters");
});
});
</script>
<input id="box_1" name="box_1" type="number">
Hey I think You want something like this.
Check it jsfiddle

Restore textfield's default value when user clicks the reset button JavaScript

I'm trying to get the textfields to return to their default value when the user clicks the Reset button.
All it does now when the user clicks the Reset button is replacing the user's text with ''.
How can I do it by using pure JavaScript (no jQuery)?
HTML:
<p>Type the first number</p>
<input id="first" type="text" placeholder="First Number" />
<p>Type the second number</p>
<input id="second" type="text" placeholder="Second Number" />
<button id="aButton">Apply</button>
<button id="rButton">Reset</button>
<div id="add"></div>
JAVASCRIPT:
app.onactivated = function (args) {
var aButton = document.getElementById("aButton");
aButton.addEventListener("click", buttonClickHandler, false);
var rButton = document.getElementById("rButton");
rButton.addEventListener("click", buttonResetHandler, false);
};
...
function buttonResetHandler(evetInfo) {
document.getElementById("first").innerText = '';
document.getElementById("second").innerText = '';
}
innerText is an invalid property that is implemented in IE browsers and is used for setting/getting text content of non-form elements, if the values should be set as default, you can use defaultValue property:
var a = document.getElementById("first"),
b = document.getElementById("second");
a.value = a.defaultValue;
b.value = b.defaultValue;
If you want to reset all the form elements, you can use .reset() method of DOM HTMLFormElement object:
document.forms["myForm"].reset();
location.reload(); // reloads the page
history.go(0); // deletes the history
But if you need to preserve some values inside of the page then reassign the values in the function again. To reassign, write the variable (declare in let to change later) again in the function and change the textContent again.
Replace,
document.getElementById("first").innerText
With,
document.getElementById("first").value
Example:
<input id="txtBox" type="text" value="lama">
<input type="button" value="reset lama" onclick='document.getElementById("txtBox").value="lama2";'>
create an init function that sets the default values for each input, then you can call that:
function initializeInputs() {
document.getElementById("first").value = '';
document.getElementById("second").value= '';
}
function buttonResetHandler(e) {
initializeInputs();
}

Passing jQuery objects to a function

Here is the working demo of what I want to achieve. Just enter some value in input and you might get what I want to achieve. (Yes, I got it working but stay on..)
But it fails when multiple keys are pressed together.
What I am trying :
I have screen which contains few enabled and few disabled input elements. Whenever user updates any value in editable input element, I want to update disabled input which had same value with user updated value.
HTML :
<input value="foo" /> // When User updates this
<br/>
<input value="bar">
<br/>
<input value="Hello">
<br/>
<input value="World">
<br/>
<input value="foo" disabled> // this should be updated
<br/>
<input value="bar" disabled>
<br/>
<input value="foo" disabled> // and this also
<br/>
<input value="bar" disabled>
<br/>
<input value="Happy Ending!">
<br/>
I tried this which I think will save me from multiple_clicks_at_a_time
JS:
$(":input:not(:disabled)").keyup(function () {
// Get user entered value
var val = this.value;
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings");
$(siblings).each(function () {
// Update each input with new value
this.value = val;
});
});
$(function () {
$(":input:not(:disabled)").each(function () {
// Find inputs which should be updated with this change in this input
siblings = $(":input:disabled[value=" + this.value + "]");
// add them to data attribute
$(this).data("siblings", siblings);
});
});
But I am not able to pass the selectors to keyup function and invoke .each on it.
PS:
My previous completely different try, working with single_click_at_a_time but I felt that I am unnecessarily traversing the DOM again and again so dropped this
$(":input").keypress(function () {
$(this).data("oldVal", this.value);
});
$(":input").keyup(function () {
var oldVal = $(this).data("oldVal");
$(this).data("newVal", this.value);
var newVal = $(this).data("newVal");
$("input:disabled").each(function () {
if (this.value == oldVal) this.value = newVal;
});
});
I would group those inputs first and bind a handler for enabled elements to apply to the group. See below,
var grpInp = {};
$(":input").each(function () {
if (grpInp.hasOwnProperty(this.value)) {
grpInp[this.value] = grpInp[this.value].add($(this));
} else {
grpInp[this.value] = $(this);
}
});
$.each(grpInp, function (i, el) {
el.filter(':enabled').keyup(function () {
el.val(this.value);
});
});
DEMO: http://jsfiddle.net/fjtFA/9/
The above approach basically groups input element with same value, then filters them based on :enabled and bind a handler to apply it to the group.
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings", siblings);
No. The .data method called with two arguments does not get, but set the data (and returns the current selection). Also, you should make your variables local:
var siblings = $(this).data("siblings");
Working demo

Cursor appear on search box click

Just want some direction really.
Want my search box to have text inside, but when it is clicked, it clears it and allows the user to start typing.
How is this achieved?
jQuery?
Anyone got any useful links or tips to do this?
Thanks :)
Update for 'jQuery'
<form action="process.php" method="POST">
<input type="text" name="keyword" value="Keyword or code" id="textBox"/>
<?php echo $form->error("keyword"); ?>
<input type="submit" value="Search" name="search" />
</form>
<script type="text/javascript">
$('#textBox').focus(function() {
if ($(this).val()==='Keyword or code') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('Keyword or code');
}
});
</script>
A more generic approach (we do not need to have the watermark text in the JS):
Given the HTML element <input class="watermark" type="text" value="Text Here" />
And the following Javascript:
<script type="text/javascript">
$(document).ready( function () {
$('input.watermark').focus( function () {
var $this = $(this);
if( !$this.data('watermark_value') || $this.data('watermark_value') === $this.val() ) {
$this.data( 'watermark_value', $this.val() ).val( '' );
}
});
$('input.watermark').blur( function () {
var $this = $(this);
if( $this.val() === '' ) {
$this.val( $this.data('watermark_value') );
}
});
});
</script>
Then you can give any input the class watermark to get the effect.
This will store the original value of the input and make the input blank when first entered, if the field is left blank when focus is removed it'll put the original value back, if the user enters a value into the input then nothing will happen when they leave. If they later revisit the input and make it blank, then again the original value will be inserted.
jQuery isn't necessary - here's a simple plain Javascript solution.
You need to bind to the inputs onfocus event and restore your default with the onblur if it was left empty:
function initSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Clear out the input if it holds your default text
if (theInput.value = "Your default text") {
theInput.value = "";
}
}
function blurSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Restore default text if it's empty
if (theInput.value == "") {
theInput.value = "Your default text";
}
}
<input type='text' value="Your default text" onfocus="initSearchBox();" onblur="blurSearchBox();" />
Actually by this method, it's not really even necessary to getElementById(). You can probably just use this.
try this:
HTML:
<input id="searchBox" value=""/>
JQUERY:
var pre = $('#searchBox').val();
$('#searchBox').focus(function() {
if($(this).val() != pre)
$(this).val($(this).val());
else
$(this).val('');
}).blur(function() {
if ($(this).val() != null && $(this).val() != '')
$(this).val($(this).val());
else
$(this).val(pre);
}).keyup(function() {
if ($(this).val() == null || $(this).val() == '' || $(this).val() == undefined)
$(this).val(pre).blur(); // here the input box will lost cursor blink until you click again due to `blur()` function
});
This can be done with jQuery using the following method;
HTML;
<input id="textBox" name="" type="text" value="text here" />
The jQuery;
$('#textBox').focus(function() {
if ($(this).val()==='text here') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('text here');
}
});
This will remove the value of the text box if it is current "text here", then if the user clicks off the box and leaves it empty, it'll add the placeholder text back in.
You could change the .focus to simply be a click function to remove any content, regardless of what's in there.
$('#textBox').click(function() {
$(this).val('');
});
Or you can just use some Javascript in the Input field in HTML like so;
<input type="text" value="Text here" onfocus="if(this.value=='Text here')this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Again, this will only remove text on click if the value is "text here" and it'll add "Text here" back in if the user leaves the box empty.
But you could adjust the onfocus to remove any content with;
<input type="text" value="Text here" onfocus="this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Ensure you've got jQuery included, add this in the ....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
You can do this in html5 like this:
<imput type="search" value="" placeholder="search here">
But support in IE is limited.
Or, you can do it with jquery very easily:
$(function() {
$("#search").click(function() {
$(this).val("");
});
});
You can just add placeholder="" into your input tag
<input type="text" placeholder="Keyword or code">
This will generate a watermark which goes away when you focus on it

Categories