I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.
I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);
<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);
I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>
In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()
can anyone give me the javascipt code to extract following instances of sf_number from my HTML?
<ul class="multi_value_field" style="width: 99.5%;">
<li class="choice" choice_id="sf_number">sf_number<a class="close">×</a><input type="hidden" name="ticket[set_tags][]" value="sf_number" style="display: none;"></li>
<li class="search_field_item"><input type="text" autocomplete="off" tabindex="20"></li>
</ul>
Basically I want to replace all three instances of sf_number with a different
value from another field. This is the code I have made to try and extract sf_number but doesn't work so far:
var n2 = document.getElementsByClassName("multi_value_field").getElementsByClassName("choice");
Thanks in advance
UPDATE
How can I change my existing code by using your suggestions below?
<html>
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
n2.value = n1.value;
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>
Update
This doesn't seem to work, is it correct?
<html>
<script type="text/javascript">
copy = function()
{
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
fields[i].setAttribute("choice_id", "document.getElementById("ticket_fields_20323656").value");
fields[i].getElementsByTagName("input")[0].value = "document.getElementById("ticket_fields_20323656").value";
fields[i].firstChild.nodeValue = "document.getElementById("ticket_fields_20323656").value";
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>
Try this code. Do you also want to replace the text?
<script>
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
{
fields[i].setAttribute("choice_id", "something else");
fields[i].getElementsByTagName("input")[0].value = "something else";
fields[i].firstChild.nodeValue = "something else";
}
</script>
var n2 = document.getElementsByClassName("multi_value_field") returns a node List
So you need to use a for loop to iterate the list..
var n2 = document.getElementsByClassName("multi_value_field");
for(var i =0;i< n2.length;i++){
var $li = n2[i].getElementsByClassName("choice"); This is again a Node list.
for(var j = 0;j< $li.length ; j++){
$li[j] // This the li in question
}
}
UPDATE
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number");
// The above line again return's node List ....
n2.value = n1.value;
Replace that by this line with this if you feel it has a single class
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
But the thing is I don't see the element with id="choice" in the HTML.
I'm not sure I understand your question.
There is no HTML attribute named "choice_id", and using non–standard attributes is not a good idea. If you want to identify a number of elements using the value 'sf_number', you should use a class instead, e.g.
<li class="choice sf_number">sf_number<a class="close">×</a>...</li>
Now you can get all elements with class of "sf_number" using getElementsByClassName, or querySelectorAll. You can add a shim for one or both of those to make life easier, then use:
var sfNumbers = document.querySelectorAll('.sf_number');
Then you can iterate over the collection per other answers.
An element can have multiple classes, the above will select only those with a class of 'sf_number'. If you want to select the text sf_number, you are much better off putting it in a span or similar element so you can reference it more directly. Relying on different browsers to insert text nodes consistently is not a good idea.