set text of input value with javascript - javascript

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';

Related

How to remove/change an input value using javascript

How do I remove the value 'Anonymous' in this input that I have and replace it with a placeholder text 'Your name' using javascript/jquery? I don't have access to the HTML code.
This is what I have so far, but don't really know where to go from there.
document.getElementById('txtYourName').placeholder =' Your Name ';
HTML
<input id="txtYourName" type="text" value="Anonymous" name="txtYourName"></input>
Add this second line here...
A placeholder is only seen when the value happens to be blank. With the code below, you can set the placeholder, as well as erase the default value in your field.
document.getElementById('txtYourName').placeholder =' Your Name ';
document.getElementById('txtYourName').value = "";
Demo: http://jsfiddle.net/723vL/
You can use .val():
$('#txtYourName').val('');
or pure javascript using:
document.getElementById('txtYourName').value = ""
If you want to set new value then just put your value inside "", like:
$('#txtYourName').val('new value');
With jQuery, your final code should look like:
$('#txtYourName').attr('placeholder','Your name');
$('#txtYourName').val('');
Fiddle Demo
With pure JS, you final code should look like:
document.getElementById('txtYourName').placeholder ='Your name';
document.getElementById('txtYourName').value = "";
Fiddle Demo
That should do it, so long as you are running that script either on an onload event, jquery's ready event or at the very bottom of the page, once the DOM has been rendered.
Are you getting an error in your console?
try this
returns value:
$('#txtYourName').attr("value");
sets value
$('#txtYourName').attr("value", "");
use
document.getElementById('txtYourName').value ='some vaue';
if you are using jQuery then you can use
$("#txtYourName").val('some value');

jQuery - cannot extract .data() attribute with calculated key

I'm working with this jQuery code:
$('#selection').bind("change", function(){
var selected = $(this).find('option:selected');
var datavar = selected.text().toLowerCase();
//alert(datavar);
//alert('looking for '+datavar+$('#test').data(datavar));
//alert($('#test').data('var1'))
});
http://jsfiddle.net/Zwe6h/
The purpose is to choose what data variable you wish to extract from the #test element by using the #selection element. it should alert you as to what the value of that data variable is.
The datavar variable is set correctly as alert(datavar); prints out the correct value.
However, the second test alert (which is the purpose of this test) displays it as undefined. The third test alert simply tests to make sure you can explicitly call the data variables by hard-coding the variable.
I am not understanding why it is coming back with undefined. I tested the type of datavar, and it is indeed a string, so I would expect it to behave just as it would if it were hardcoded. Can someone shed some light on this?
Try this:
alert('looking for '+datavar + $('#test').data($.trim(datavar)));
Issue is with some newline chars (casued by html formatting) in the text selected as they are not included between the option start and end tag. So you just need to trim it.
Fiddle
Or fix your options to include the text in between closing and ending tags.
<select name='selection' id='selection'>
<option value='1'>var1</option>
<option value='2'>var2</option>
</select>
Fiddle2

Setting input value to attribute value in JQuery

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.

Can I use a variable in JS for my html?

I have a JS file CharacterSelection where a user can select an avatar and type their name into a textarea.
Now I want to set a text div in an html file to the contents of the textarea. I will use it to display the player's name at a specific location on the screen.
I know that I can set a div to a text, such as: <div id ="statSheetExitButton">Exit</div> will show "Exit" (style and location depending on css)
I'm wondering if there is any way to put a String variable in there, since I will not know what name the player enters.
I grab the textarea's contents using var name = $("#nameTextBox").val();
I'm thinking that saying <div id ="playerName">name</div> will display the text "name".
Is there a way to accomplish my goal?
$("#nameTextBox").change(function(){
$("#playerName").html($(this).val());
});
This will attach an event handler to the textbox so everytime the name changes the div is updated.
Here is a working example. http://jsfiddle.net/2NkTb/
Please note that for the onchange event you must tab out of textbox or the textbox must lose focus
var name = $("#nameTextBox").val();
$("#playerName").html(name);
Do this:
var name = $("#nameTextBox").val();
$('#playerName').text(name);
You could do something like this which will replace the html of the tag with your JavaScript string:
$('#playerName').html(myNameVar);
Other than that, I don't think you can directly inject JavaScript variables like you would in a template language.
Try:
$('#playerName').html($("#textbo").val());
var playerName = 'John Dow'
document.getElementById('playerName').innerHTML=playerName
You need to set the property innerHTML of you div element.
$("playerName").innerHTML = name;

Javascript for mobile HTML form

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
}

Categories

Resources