I have a number of <input /> boxes which I want to start off having a value of something like "Enter your name...".
When you focus them, the value becomes empty and you can type away. When you blur them, if nothing has been entered, then it goes back to "Enter your name...".
I thought of having something like this:
<input id="name" _startValue="Enter your name..." />
Then, something like this:
$(document).ready($("input").val($(this).attr(_startValue)));
This initially should set the value to _startValue but it does nothing. Replacing the line with:
$(document).ready($("input").val("hello"));
does work, however, so the problem must be with the $(this) or the attr().
First of all, how do I get this to work. Secondly, if I am trying to do this in a really retarded way, what is a good way to get this functionality?
I believe its better to use a placeholder like:
<input id="name" placeholder="Enter your name..." />
There are already libraries for this, and if you are already using jquery you should use them.
https://github.com/mathiasbynens/jquery-placeholder
just add the attribute "placeholder" and invoque the function:
<input placeholder="my placeholder">
<script type="text/javascript">
$("document").ready(function(){
$("input").placeholder();
});
</script>
Note that you only need to add the plugin if you need old browser support (in IE specially), otherwise, the attribute is enough.
Also, consider that if you code this, it will take you errors like submitting the default value of the form. What jquery plugins do generally is to make a <span> or whatever and place it on top of the input when the input is empty, and hide it when the input is not empty.
// v---you're not passing a function
$(document).ready($("input").val($(this).attr(_startValue)));
// `this` isn't magic-------^---- It doesn't just mean what you want
Should be more like this:
$(document).ready(function() {
$("input").val(function() {
return $(this).attr("_startValue");
});
});
A common way to mimic placeholders is to put the placeholder text in the element's value, then check the value on focus like:
if (this.value == this.defaultValue) this.value = '';
and then on blur:
if (this.value == '') this.value = this.defaultValue;
Please don't use placeholders instead of labels or onscreen help (e.g. format for dates). If a browser doesn't support the placeholder attribute, it's probably best not to emulate them if using it for the default value is an issue.
After all, placeholders are a "nice to have", they should not be fundamental to using the form correctly.
Related
I know this is probably a piece of cake for all, but im really not any good with javascript.
I would like to set the value of html input with javascript.
I have an input like this:
<input id="input-data" value=""/>
I would like to set the text of the value with javascript, meaning that if id pass value like "CocaCola" to input, it should display "CocaCola" in input
This is how i try
document.getElementById("input-data").value = "CocaCola";
But no data gets displayed in input. When i run debugger and put value as my watch, the "CocaCola" is stored in value.
What on earth am i missing?
Make sure your code is under HTML tag, like this:
<input id="input-data" value=""/>
<script>
document.getElementById("input-data").value = "CocaCola";
</script>
Or you can use:
window.onload = function(){
document.getElementById("input-data").value = "CocaCola";
}
It works any time and anywhere.
Your JavaScript code to set value is right.
You can also try jQuery to set value like this,
$('#input-data').value = 'CocaCola';
Assume you have input element:
<input id="aaa" type="text" value="unchanged" />
Then launch js script:
var e = document.getElementById("aaa");
e.value = "changed";
alert(e.defaultValue + "/" + e.value);
Result will be "unchanged/changed". Unfortunately, when your input element is hidden:
<input id="aaa" type="hidden" value="unchanged" />
...the same js script seem not to be working any more. Result is "changed/changed".
Is this a proper way? If so, why only hidden form elements act different?
The "defaultValue" property is only maintained in a way you apparently expect for "text", "file", and "password" fields.
Here is the relevant portion of the DOM spec.
I suspect the reason for this is that user activity on its own cannot change the value of hidden elements. If you want to preserve the initial values, run something at "load" or "ready" to stash the value somewhere.
For hidden input elements, defaultValue isn't actually implemented. The reason why you get the same result ast .value is because the browser your using is just defaulting.
See here for a discussion of this with Firefox.
Background: I need to append certain data to post; similar to what jQuery's ajaxSetup does that for asynchronous requests except I need it for native form submits.
I need to be able to add a couple of form fields to a form before it is submitted, but I want to make sure I don't add duplicate fields in case they're already there (i.e. original submit failed because of validation or something).
At first I thought something like this would be nice and coherent:
$("form").live("submit", function ()
{
var $this = $(this);
($this.find('#stuff') ||
$this.append('<input type="hidden" id="stuff" name="stuff" />'))
.val('some value');
// carry on with the native submit
// this is actually correct, as opposed to $this.submit()
// which would create a loop
this.submit();
});
Meaning look for #stuff, if it's not found create it, then set its value to "some value". However because the result of the .find() is actually a jQuery wrapper, it would be implicitly converted to a true meaning that even if there are no matching elements found, the .append() code would never be executed.
Is there a nice way to tackle this whole "look for an element and create it if it doesn't already exist" scenario?
change $this.find('#stuff') to $this.find('#stuff').length
edit
if you want to be able to all of it in one statement you can do
(
($this.find('#stuff').length && $this.find('#stuff')) ||
$('<input type="hidden" id="stuff" name="stuff" />').appendTo($this)
).val('some val');
To keep checking logic readable one would expand the conditional:
if ($this.find('#stuff').length) {
$this.find('#stuff').val('some val');
} else {
$this.append('<input type="hidden" id="stuff'" name="stuff" value="some val" />');
}
Alternatively one could just remove and re-add the element... I know, "dom operations are expensive" but if there are several fields to be operated on it's just so much prettier this way:
$this.find('#stuff', '#stuff2', ...).remove()
.append('<input type="hidden" id="stuff" name="stuff" value="some val" />...');
I tried:
$('input').keyup(function() {
$(this).attr('val', '');
});
but it removes the entered text slightly after a letter is entered. Is there anyway to prevent the user from entering text completely without resorting to disabling the text field?
A non-Javascript alternative that can be easily overlooked: can you use the readonly attribute instead of the disabled attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out")
e.g. <input readonly type="text" ...>
if you don't want the field to look "disabled" or smth, just use this:
onkeydown="return false;"
it's basically the same that greengit and Derek said but a little shorter
$('input').keydown(function(e) {
e.preventDefault();
return false;
});
$('input').keypress(function(e) {
e.preventDefault();
});
If you want to prevent the user from adding anything, but provide them with the ability to erase characters:
<input value="CAN'T ADD TO THIS" maxlength="0" />
Setting the maxlength attribute of an input to "0" makes it so that the user is unable to add content, but still erase content as they wish.
But If you want it to be truly constant and unchangeable:
<input value="THIS IS READONLY" onkeydown="return false" />
Setting the onkeydown attribute to return false makes the input ignore user keypresses on it, thus preventing them from changing or affecting the value.
One other method that could be used depending on the need $('input').onfocus(function(){this.blur()}); I think this is how you would write it. I am not proficient in jquery.
For a css-only solution, try setting pointer-events: none on the input.
Markup
<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
TabIndex="1">
Script
function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}
I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:
//.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !
to prevent actions on a HTML input DOM element add readonly to class:
var d = document.getElementById("div1");
d.className += " readonly";
OR in D3:
.classed("readonly", function(){
if(condition){return true}else{return false}
})
AND add to CSS or less:
.readonly {
pointer-events: none;
}
the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).
to remove the element from class:
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\breadonly\b/,'');
or use Jquery:
$( "div" ).removeClass( "readonly" )
or toggle the class:
$( "div" ).toggleClass( "readonly", addOrRemove );
Just to be complete, good luck =^)
just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.
<asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
</asp:TextBox>
One option is to bind a handler to the input event.
The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).
Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.
This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.
const inputEl = document.querySelector('input');
inputEl.addEventListener('input', (event) => {
event.target.value = '';
});
<input type="text" />
Tested in Safari 10, Firefox 49, Chrome 54, IE 11.
The best solution is to unfocus input once user clicks it so it makes it kinda readonly
onFocus={e => e.target.blur()}
I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}