I am having the below code to show input field with phone number in certain format. i.e., If phone number starts with 33,55 or 81 I will show it as (33) 1234-5678. If phone number starts with any other numbers, the format will be (123) 456-7890.
Now, the problem is when I submit the form, it is submitted as (33) 1234-5678. But I should submit 3312345678 and display (33) 1234-5678.
Could someone help me, how could i overcome this issue. I didnt use any jquery plugins;
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
You can change the value when the form is submitted, just before it is sent to the server:
$("form").on("submit", function(){
var originalVal = $("#criterion").val();
var newVal = originalVal.replace(/[^\d]/g, '');
$("#criterion").val(newVal);
});
You could have a hidden input that you store the original value of the input before modifying it.
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input type="hidden" id="org" name="org" />
-
$(document).ready(function() {
$("#criterion").change(function () {
var searchBy = $('#smartWirelessSearch').val();
$('#org').val($(this).val());
if(searchBy == 'Mobile'){
$(this).attr("criterion", $(this).val());
var twoDigit = $('#criterion').val().substr(0, 2);
var threeDigit = $('#criterion').val().substr(0, 3);
var remainingDigits = $('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
$('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
$('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
If you need to have the original cleaned value all the time, there are many ways to do that too. One simple solution is to have clean it by your self everytime input changes.
If so, replace $('#org').val($(this).val()); by $('#org').val($(this).val().replace(/[^\d]/g, ''));
This basically replaces everything that is not a digit with an empty string.
There are two possibilities to solve this, the first is to have a second (extra) hidden input like:
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input id="criterion_hidden" name= "criterion_real" type="hidden" size="15" maxlength="60" value="" placeholder="" onkeypress = "submitOnReturn(event);">
And populate it in your jquery:
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
$("#criterion_hidden").val(twoDigit + remainingDigits); //update it here.
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
The other solution is to change the value on the server side (PHP?) by using a replace with a regular expression such as /[^\d]/g.
On submit of the form replace input value of ( ) - with empty string "".
I would suggest two solutions:
1. Toggle Format
With this solution, you either show the formatted value in the input, or the clean digit-only value. So you would take care to show the digit-only value when the form is submitted, but also when the user edits the value (as suggested by #Rune FS):
jQuery(function($) {
function cleanMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Strip all non-digit characters
$("#criterion").val($("#criterion").val().replace(/[^\d]/g, ''));
}
}
function formatMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Apply format after first stripping all non-digit characters
$("#criterion").val($("#criterion").val()
.replace(/[^\d]/g, '')
.replace(/(33|55|81|...)(.*?)(....)$/, '($1) $2-$3'));
}
}
$("#myform").submit(cleanMobile);
$("#criterion").blur(formatMobile).focus(cleanMobile).keypress(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
// Set initial format correctly on page load
formatMobile();
}, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<select id="smartWirelessSearch">
<option value="Mobile">Mobile</option>
</select>
<input id="criterion" name="criterion" type="tel" class="inputboxBg"
size="15" maxlength="60" style="width:85%;" value="" placeholder="">
<input type="submit" value="submit">
</form>
Run the snippet to see how it responds to focus and submit.
Note that the code above also:
Uses a regular expression to format the number;
attaches the keypress handler via code instead of the element's onkeypress attribute;
defines functions for the format manipulations so these can be referenced in blur, focus and submit events;
defines a dummy smartWirelessSearch element so the code is compatible with your form;
gave the form an id myform, which you should replace with yours.
2. Use Hidden Input
If you do not want the input value to visibly change at form submission, you could add a hidden input and give that the digit-only value, like this:
<input id="criterionClean" name="criterionClean" type="hidden">
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15"
maxlength="60" style="width:85%;" value="" placeholder=""
onkeypress="submitOnReturn(event);">
In your Javascript add one line:
if(searchBy == 'Mobile'){
// ... your code ...
// Then pass the digits only in the hidden input
$('#criterionClean').val($(this).val().replace(/[^\d]/g, ''));
}
Now you'll submit both the formatted and the cleaned value. Your server code could then use the clean digit-only value.
If you prefer the clean value to be called #criterion, then swap the names of the two inputs in html and in your code.
Related
I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
I am looking for a javascript function that when using onblur it validates that the text input is a number only with no decimal points or special characters. I have been able to find a few things, but none of them have worked thus far.
Here's what I have for the input fields:
<tr>
<td width="312"><strong>Cash on Hand</strong></td>
<td width="188">$
<input type="text" onchange="updateassets()" value="0" maxlength="11" name="CashOnHand" /></td>
Any help would be greatly appreciated.
Use below method onKeyUp event, this will not allow any characters on input field
function numericOnly(e)
{
var val = e.value.replace(/[^\d]/g, "");
if(val != e.value)
e.value = val;
}
Input field code
<input type="text" onchange="updateassets()" onKeyUp="numericOnly(this)" value="0" maxlength="11" name="CashOnHand" />
I like to separate the structure (HTML) from the function (JS). That's why there's no "onchange" attribute in the input element.
HTML
<input type="number" name="cashOnHand" value="0" maxlength="11" />
JS
function checkInputInteger() {
// Check if the input value is an integer
if (this.value == parseInt(this.value)) {
// The value is an integer
console.log('Input ' + this.name + ' is an integer');
}
else {
// The value is not an integer
console.log('Input ' + this.name + ' is not an integer');
}
}
// Get the input from DOM (getElementsByName returns a list)
input = document.getElementsByName('cashOnHand')[0];
// Bind the blur event to checkInputInteger
input.addEventListener('blur', checkInputInteger, false);
HTML
<form>
<input type="text" id="txt" />
</form>
JS
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
Hope it helps you
Given:
<input onchange="updateassets()" value="0" ...>
you can make life easier by passing a reference to the element to the function using this:
<input onchange="updateassets(this)" value="0" ...>
and the validation function can be:
function validateIsInteger(element) {
if (/\D/.test(element.value)) {
// the element value contains non–digit values
} else {
// the element value is only digits
}
}
Using the change event is a good idea, as if the value hasn't changed, you don't need to check it.
There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}
I have an input text:
<input name="Email" type="text" id="Email" value="email#abc.example" />
I want to put a default value like "What's your programming question? be specific." in Stack Overflow, and when the user click on it the default value disapear.
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email#abc.example" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see JQuery HTML5 placeholder fix « Kamikazemusic.com for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a JavaScript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the jQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email#abc.example" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email#abc.example';}"
onfocus="if (this.value == 'email#abc.example') {this.value = '';}" />
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
Using jQuery, you can do:
$("input:text").each(function ()
{
// store default value
var v = this.value;
$(this).blur(function ()
{
// if input is empty, reset value to default
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
// when input is focused, clear its contents
this.value = "";
});
});
And you could stuff all this into a custom plug-in, like so:
jQuery.fn.hideObtrusiveText = function ()
{
return this.each(function ()
{
var v = this.value;
$(this).blur(function ()
{
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
this.value = "";
});
});
};
Here's how you would use the plug-in:
$("input:text").hideObtrusiveText();
Advantages to using this code is:
Its unobtrusive and doesn't pollute the DOM
Code re-use: it works on multiple fields
It figures out the default value of inputs by itself
Non-jQuery approach:
function hideObtrusiveText(id)
{
var e = document.getElementById(id);
var v = e.value;
e.onfocus = function ()
{
e.value = "";
};
e.onblur = function ()
{
if (e.value.length == 0) e.value = v;
};
}
Enter the following
inside the tag, just add onFocus="value=''" so that your final code looks like this:
<input type="email" id="Email" onFocus="value=''">
This makes use of the javascript onFocus() event holder.
Just use a placeholder tag in your input instead of value
we can do it without using js in the following way using the "placeholder" attribute of HTML5
( the default text disappears when the user starts to type in, but not on just clicking )
<input type="email" id="email" placeholder="xyz#abc.example">
see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder
<input name="Email" type="text" id="Email" placeholder="enter your question" />
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
I think this will help.
Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email#abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
I didn't see any really simple answers like this one, so maybe it will help someone out.
var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }
Here is an easy way.
#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>