I have an input field like this:
<input class="" type="text" id="Name_11_1" name="Name" value="Your name:">
And want to change it into this:
<input class="" type="text" id="Name_11_1" name="Name" value="Your name:" onblur="this.value = this.value || this.defaultValue;" onfocus="this.value == this.defaultValue && (this.value = '');"Your name:">
The problem is that I CAN'T edit the input field directly and have to use an external JavaScript code.
With jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function() {
$('#Name_11_1').blur(function() {
$(this).val(YOUR_EXPR);
});
$('#Name_11_1').focus(function() {
$(this).val(YOUR_EXPR);
});
});
</script>
First remove the existing event handlers and then attach your own:
var obj = document.getElementById('Name_11_1');
obj.removeAttribute('onfocus');
obj.removeAttribute('onblur');
obj.addEventListener('blur', function() {
// your js code for blur event
});
obj.addEventListener('focus', function() {
// your js code for focus event
});
If the browser understands the placeholder attribute on input tags, you can use that:
<input id="foo" name="foo" placeholder="Your name">
You can then add JavaScript to provide a fallback for other browsers:
if (!'placeholder' in document.createElement('input')) {
$('#foo').on('focus', function() {
// your code
}).on('blur', function() {
// your code
});
}
UPDATE: forgot that the OP can't edit the input tag directly. In that case, the code snippet can be modified to something like this:
var elem = $('#Name_11_1'),
defaultValue = 'Your name';
if ('placeholder' in document.createElement('input')) {
elem.attr('placeholder', defaultValue);
} else {
elem.on('focus', function() {
// your code
}).on('blur', function() {
// your code
});
}
Related
Can anyone tell me why this code wouldn't work? I have an input and I'm trying to check weather or not the input is "start". So I do... how ever nothing is working - not even the .ready but I'm new so I have no idea what the problem is.
HTML
<form id="inputForm" onsubmit="return false;">
<input id="input" type="text" size="30" autofocus="autofocus" maxlength="100" autocomplete="off"/>
</form>
JS:
var input = "";
$(document).ready(function() {
$("#inputForm").submit(function() {
input = $("#input").val().toUpperCase();
if (input === "START") {
alert("worked");
}
$("#command_input").val("");
})
});
I suspect that you haven't included jQuery in your webpage. You can import it by adding
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Before the script tag for your code. (https://code.jquery.com/jquery has more jQuery CDNs too)
You really don't need jQuery to do this though. Here's the plain JS equivalent code working here:
var input = "";
document.body.onload = function() {
document.getElementById("inputForm").addEventListener("submit", function() {
input = document.getElementById("input").value.toUpperCase();
if (input === "START") {
alert("worked");
}
document.getElementById("command_input").value = "";
});
};
After looking at the code here: https://jsfiddle.net/cu7tn64o/1/
It seems to work fine! As the other commenters have mentioned, this is likely because you have not included jQuery in your html file like so:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
https://code.jquery.com/
First include the jquery file using script tag in your html file.
Submit the form using jquery or in the below case I have submitted using a button. Onsubmit the value is taken from the input field and compared.
var input = "";
$(document).ready(function() {
$("#inputForm").submit(function() {
input = $("#input-value").val().toUpperCase();
if (input === "START") {
alert("worked");
}
else
{
alert("sorry");
}
$("#command_input").val("");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inputForm" onsubmit="return false;">
<input id="input-value" type="text" size="30" autofocus="autofocus" maxlength="100" autocomplete="off"/>
<input type="submit" name="submit" value="submit" />
</form>
If you return false from the event handler, things ought to work.
var input = "";
$(document).ready(function() {
$("#inputForm").submit(function() {
input = $("#input-value").val().toUpperCase();
if (input === "START") {
alert("worked");
} else {
alert("sorry");
}
$("#command_input").val("");
// You have to return false HERE to prevent the default action of a
// form -- send a request to a server, that is
return false;
});
});
I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>
I have a textbox that has variable maxlenght based on some condition. There are keyup and keydown events associated with the textbox. On paste my maxlenght validation fails.If "Location" is selected the type of textbox is number with maxlenght 6, for other the type is text with maxlen 11 and 15 respectively "
$(document).on("pageinit", function (event) {
$('input[type="text"]').on('keyup keydown', function (event) { /*Some validation*/} });
$('input[type="number"]').on('keyup keydown', function (event) { /*Some validation*/} });
JQuery
$(document).ready(function() {
var characters ;
$("#text").keyup(function(){
if($('#vehicle').prop('checked')){
characters=5;
}
else{
characters=10;
}
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
});
});
HTML
<input type="checkbox" id="vehicle" value="Bike">I have a bike<br>
<input type="text" id="text"/>
SEE DEMO HERE
I used paste event to trigger keyup event because only using paste event I can somehow get the input but I couldn't manipulate the input given. Here's how I found a way -
$(".AlphaValidateOnPaste").on('paste', function(e) {
$(e.target).keyup();
});
$('.AlphaValidateOnPaste').on('keyup',function(e){
var value = $(this).val();
var i = value.length;
while (i--) {
var result = value.charAt(i).match(/^[a-zA-Z ]*$/);
if(result == null){
$(this).val('');
alert('Only Alphabates and Spaces');
break;
}
}
});
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="employee_name" class="form-control AlphaValidateOnPaste" id="employee_name" required>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Please do not give a negative vote if I am wrong with asking this question. I have a TextBox like this:
<input class="login-inpt" runat="server" name="loginName" type="text" value="User Name" />
It currently holds a default value. I want the default value to be cleared and replaced with a cursor when I click on the TextBox.
For newer browsers (IE>9):
<input type="text" id="userName" placeholder="User Name" />
For older:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Placeholder support</title>
</head>
<body>
<input type="text" id="userName" placeholder="User Name" />
<script src="../js/vendor/jquery-1.10.2.min.js"></script>
<script src="../js/vendor/jquery-migrate-1.2.1.js"></script>
<script src="../js/vendor/modernizr-latest.js"></script>
<script src="../js/placeholder.js"></script>
</body>
</html>
placeholder.js (jQuery, Modernizr)
var Placeholder = (function ($, document) {
/* Static Content */
var _$document = $(document);
/* Events */
var _initPlaceholders = function () {
_$document.find('input:text').each(function () {
var $this = $(this);
$this.css({ color: '#888' }).val($this.attr('placeholder'));
});
};
var _placeholderEvent = function () {
var $input = $(this), placeholderValue = $input.attr('placeholder');
if ($input.val() === placeholderValue) {
$input.css({ color: '#000' }).val('');
return;
}
if ($input.val() === '') {
$input.css({ color: '#888' }).val(placeholderValue);
}
};
var _bindEvents = function () {
if (!Modernizr.input.placeholder) {
_initPlaceholders();
_$document.on('focus blur', 'input:text', _placeholderEvent);
}
};
var init = function () {
_bindEvents();
};
return {
init: init
};
})(jQuery, document);
Placeholder.init();
You can try this
<input type="text" value="user name" onfocus="if(this.value=='user name') this.value='';">
HTML:
<input type="text" value="user name" id="userName" />
With jQuery:
$(function() {
$('#userName').click(function() {
$(this).val('').unbind('click');
});
});
EDIT: Here's a demo
add the following as an attribute to your input tag:
onfocus="if(this.value=='A new value') this.value='';"
From: How to clear a textbox using javascript
I got the solution Thanks.
input type="text" id="userName" onfocus="inputFocus(this)" onblur="inputBlur(this)"
function inputFocus(i) { if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; } } function inputBlur(i) { if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; } }
You already got good answers but if you are newbie it might interest you how it could work without libraries.
Here is HTML:
<input id="textBox" class="textBox phrase" type="text" value="Enter Your Text..">
you don't need to set class and id you could pick one of them
Here is JavaScript:
var textBox = document.getElementById('textBox'), //probably the fastest method
/**************************additionally possible****************************
var textBox = document.getElementsByTagName('input')[0], //returns HTMLInputElement list (since we've got only one we chose the first one)
or
var textBox = document.querySelectorAll('textBox'), //works almost the same way as jquery does except you don't get all jquerys functionality
or
var textBox = document.getElementsByClassName('textBox')[0], //i guess its a least supported method from the list
***************************************************************************/
//text you want to choose for you input
phrase = "Enter Your Text..";
function addEvent(el, ev, fn) {
//checking method support
//almost every browser except for ie
if(window.addEventListener) {
el.addEventListener(ev, fn, false);
}
//ie
else if(window.attachEvent) {
el.attachEvent('on' + ev, fn);
el.dettachEvent('on' + ev, fn);
}
}
addEvent(textBox, 'focus', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if the text in your text box is your phrase then clean it else leave it untouched
target.value = target.value === phrase ? "" : target.value;
});
addEvent(textBox, 'blur', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if your text box is not empty then leave it else put your phrase in
target.value = target.value ? target.value : phrase;
});
$('.login-inpt').focus(function() {
$(this).val('');
});
$('.login-inpt').focusout(function() {
$(this).val('User Name');
});
check out here http://jsfiddle.net/TDUKN/
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>