I want to get the innerText of "lid" but when I write "lid.innerText I get null values is there any other way.
function zoom() {
var input = document.getElementById("myInput").value; //value from searchbox
// console.log(input);
d3.json("intervals.json", function(alldata) // entering json file to look for oid
{
var i;
for (i = 0; i < alldata.records.length; i++) //for loop for getting the oid alldata.records.length;
{
conceptid = alldata.records[i].oid; //saving all the oid in conceptid
lid = ("l" + conceptid.toString()); //concatenate with "l"
console.log(lid);
if (document.getElementById(lid).innerText === input) // if lid.innertext = input
{
document.getElementById(lid).click(); //then zoom
}
}
});
}
Your element is <text> which is a special tag inside <svg> so innerText does not apply. Use textContent instead:
if (document.getElementById(lid).textContent === input)
Related
I'm trying to save some strings in the local storage, I'm trying to do this but I get undefined in the local storage.
I'm asking the user for the players names, and then I want to store them in the local storage in order to use them again.
Here's what I'm trying :
const x = localStorage.getItem('playersNum');
const parentDiv = document.getElementById('player-list');
for (let i = 0; i < x; i++) {
const newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", `player${i}`);
newInput.setAttribute("placeholder", "Player's Name");
parentDiv.appendChild(newInput);
}
//get all input elements of type text and starting id with player
const input = document.querySelectorAll("[type='text'][id^='player']");
const btn = document.getElementById('startGame');
btn.addEventListener('click', function() {
//reset border style of all input elements
[...input].forEach(el => el.style.border = '');
//get all empty input elements
let empty = [...input].filter(el => el.value.trim() == "");
//check length
if (empty.length) {
//show alert
// alert('Please fill in the players names');
//set border style to empty input elements
empty.forEach(el => el.style.border = '1px solid red');
}
else {
window.location.assign('game.html');
localStorage.setItem('playersNames', String(input.value));
}
});
You're declaring input with querySelectorAll, so you need to read input as an array.
localStorage.setItem('playersNames', String(input[0].value));
Then, if you want all player's names you will need to iterate through the array. Also, you need to get the previous value of localStorage and append to it, since it gets overwritten every time you set it.
const input = document.querySelectorAll("[type='text'][id^='player']");
for (i=0; i < input.length; i++) {
var checkForStorage = localStorage.getItem('playersNames');
if (checkForStorage !== null) {
localStorage.setItem('playersNames', checkForStorage + ',' + String(input[i].value))
} else {
localStorage.setItem('playersNames', String(input[i].value));
}
};
I basicly add my input values to vals array.
Then save the array to localStorage: localStorage.setItem('mylist', JSON.stringify(vals));
After that, i show values from vals array.
It saves the values to localStorage but when i refresh, values doesn't show up on screen with my dynamicly created li elements.
Why?
Note: I want to use localstorage with JSON.
JSFIDDLE
var input = document.getElementById("input");
var box = document.querySelector(".box");
var vals = [];
var li;
var list;
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
// Loop input values
list = vals.map(function(item, index) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
}, false);
box.innerHTML = list;
After a page refresh the list array is empty. this will fix it:
var vals = JSON.parse(localStorage.getItem('mylist') || "[]");
vals.forEach(function(entry) {
li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = entry;
})
The || "[]" is a fallback in case localStorage returns null (the user never set a list)
You should also remove the last line of your script ( box.innerHTML = list; )
Youd don't read anything from localStorage after page load. You read data from storage only in your keyup handler but you do it right after overriding it with new value. You have to get data from storage when page is loaded:
use this:
var list = JSON.parse(localStorage.getItem('mylist'))
It is saving in localStorage but in your code, after you refresh, you never populate the values in your HTML.
var input = document.getElementById("input");
var box = document.querySelector(".box");
var storageVals = localStorage.getItem('mylist');
var vals = storageVals ? JSON.parse(storageVals) : [];
input.addEventListener("keyup", function(e) {
var val = e.target.value;
if (e.which == 13) {
box.innerHTML = "";
input.value = " ";
// Push input value array
vals.push(val);
localStorage.setItem('mylist', JSON.stringify(vals));
renderList();
}
}, false);
function renderList() {
// Loop input values
vals.forEach(function(item, index) {
var li = document.createElement("LI");
box.appendChild(li);
li.innerHTML = JSON.parse(localStorage.getItem('mylist'))[index];
});
}
renderList();
How can I extract the string from a certain data attribute via regexp.
<button data-loading-text="Some text on loading" data-toggle="button">Button</button>
<button data-finished-text="Some text on finished" data-toggle="button">Button</button>
And my javascript is
var Buttons = document.querySelectorAll([data-toggle="button"]);
[].forEach.call(Buttons, function (item) {
var data = item.getAttribute('data-'+INEEDTHIS+'-text')
var option = INEEDTHIS
return new Button(item,option);
})
You can use the Element.attributes property:
var attrs = item.attributes;
for(var i = attrs.length - 1; i >= 0; i--) {
var m = attrs[i].name.match(/^data-(.*)-text$/);
if (m) {
var option = m[1];
// do something
}
}
You can use the .attr() method of jQuery
I have this JavaScript Code that currently adds new textareas, inputs etc. inside a table and adds a unique number on each id/name
var i=1;
function addRow() {
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var descriptionCell = row.insertCell(0);
var elDescription = document.createElement('textarea');
elDescription.type = 'textarea';
elDescription.name = 'description' + i;
elDescription.id = 'description' + i;
elDescription.cols = 70;
elDescription.rows = 2;
descriptionCell.appendChild(elDescription);
var unitpriceCell = row.insertCell(1);
var elUnitPrice = document.createElement('input');
elUnitPrice.type = 'text';
elUnitPrice.name = 'unitprice' + i;
elUnitPrice.id = 'unitprice' + i;
elUnitPrice.size = 20;
unitpriceCell.appendChild(elUnitPrice);
i++;
form1.number.value=i;
//alert(i);
document.getElementById("line").innerHTML = "whatever";
}
I have removed the table and now this is not working. How can I make the same thing work with text inputs and text areas without the table?
A relatively simple approach to the problem:
function createFieldset(opts){
// default settings:
var s = {
// finds the first form, could use "document.forms[0]" instead
'appendTo' : document.querySelector('form'),
// an array of elements you want to create:
'create' : ['input', 'textarea'],
// the element you want to wrap those elements with:
'wrapper' : 'fieldset',
// the className to apply to the wrapping-element:
'wrapperClassName' : 'group',
// the prefix of the 'legend' tag (if you want to use one):
'legendPrefix' : 'Group '
},
// finding out where the count should start (by finding
// the number of current wrapping elements), could use
// 'document.getElementsByTagName(s.wrapper).length' or
// 'document.getElementsByClassName(s.wrapperClassName).length':
count = document.querySelectorAll(s.wrapper).length,
// creating the wrapper element:
container = document.createElement(s.wrapper),
// finding out whether to use textContent or innerText:
textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
// caching temporary variables for later:
created,
tmp;
// iterating through any user-set properties to update the
// default settings:
for (var prop in opts) {
if (opts.hasOwnProperty(prop)) {
s[prop] = opts[prop];
}
}
// if we have a prefix of length > 0 once leading/trailing white-space
// is removed, then:
if (s.legendPrefix.trim().length > 0) {
// create a 'legend' element:
var legend = document.createElement('legend');
// set the text of that legend element to 's.legendPrefix n'
legend[textProp] = s.legendPrefix + count;
// append that legend element to the container element:
container.appendChild(legend);
}
// iterating over the array of elements to be created:
for (var i = 0, len = s.create.length; i < len; i++){
// caching the string of the element at position i in the array:
tmp = s.create[i];
// creating the element at that position:
created = document.createElement(tmp);
// setting the id, and name, to element-type + n:
created.id = tmp + (count);
created.name = tmp + (count);
// appending the element to the wrapping element:
container.appendChild(created);
}
// setting the className of the wrapping element:
container.className = s.wrapperClassName;
// inserting the element to the appendTo node, before its lastElementChild:
s.appendTo.insertBefore(container, s.appendTo.lastElementChild);
}
createFieldset({
'wrapperClassName' : 'first'
});
var button = document.querySelector('#addMore');
button.addEventListener('click', function (event) {
event.preventDefault();
createFieldset();
}, false);
JS Fiddle demo.
References:
document.createElement().
document.getElementsByClassName().
document.getElementsByTagName().
document.querySelector().
document.querySelectorAll().
EventTarget.addEventListener().
Node.appendChild().
Node.insertBefore().
Object.hasOwnProperty().
String.prototype.trim().
I have this code:
function addFormControls() {
var e = document.getElementById("ProductsList");
var prodid = e.options[e.selectedIndex].value;
var prodvalue = e.options[e.selectedIndex].text;
if (num == 0) {
document.getElementById("ProductsPanel").innerHTML = '<h3>Products added to Variant</h3>';
}
if (num < 10) {
var boolCheck = checkArrayData(prodid);
if (boolCheck == false) {
document.getElementById("ProductsPanel").innerHTML = document.getElementById("ProductsPanel").innerHTML + prodvalue + '<input type="text" id="' + prodid + 'product" value="0" width="50px" maxlenght="2" /><input type="button" onclick="updateArrayData(\'' + prodid + '\', document.getElementById(\'' + prodid + 'product\').value);" value="Update Number" /><br />';
num++;
prodIdArray.push({
'key': prodid,
'value': prodvalue,
'num': 0
});
document.getElementById("productsArray").value = prodIdArray;
} else {
alert("Sorry product has already been added!");
}
}
}
which happily updates a div tag with new info, however if you look at the section where it prints a text box to the screen, line 13, these textbox's will be updated by the user.
So in short, textboxs are added, and value update.
however if there is a textbox with value 5, then this function called again to add another textbox, the previous textbox' values will be wiped clean!
So, how do i prevent this, will i have to do some, for loop over div controls taking the values, then put them back after this function is called?!?
I create some javascript to save all the values in a particular input's value field before adding the control, then return all the saved values back to their respected inputs.
function saveValuesOfProducts()
{
// initialise the array
numOfProds = new Array();
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of inputs left saving their value
for (i=0; i<x.length; i++)
{
numOfProds.push(x[i].value);
}
}
function returnValuesOfProducts()
{
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of saved values and return them to the input
for (i=0; i<numOfProds.length; i++)
{
x[i].value = numOfProds[i];
}
}
function leaveTextInputs(value)
{
// create a new blank array
var newArr = new Array();
// loop through all the elements in passed array
for (i=0; i<value.length; i++)
{
// cache the element
var thevalue = value[i];
// check if the element is a text input
if (thevalue.type == "text")
{
// check the id consists of product in it!
var regexteststring = thevalue.id;
// create the pattern to match
var patt1 = /product/i;
if (regexteststring.match(patt1) == "product")
{
// as additional check, if it has a size quantity of 2 then its defo out stuff
if (thevalue.size == 2)
{
newArr.push(thevalue);
}
}
}
}
// now return the new array
return newArr;
}