I have the code below that returns the rowIndex of the clicked row.
The table uses the info from the WebViewString element, it has an csv formatted data and always have at least one column.
I need to get the value of the first column of that row. How to???
I know nothing about JS... just need this little modification but couldn't find anything by myself.
<!doctype html>
<head>
<meta name="author" content="puravidaapps.com">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="materialize.min.css" media="screen,projection"/>
<title>Table Layout</title>
</head>
<body>
<div id="myTable"></div>
<script>
// if you have commas inside your text, feel free to use another delimiter, for example |
var delimiter = ",";
// get the table to display from the window.AppInventor object and split at new line
var urlArray = window.AppInventor.getWebViewString().split("\n");
//var urlArray = location.search.slice(1).split("/n");
var doc = document;
var fragment = doc.createDocumentFragment();
var thead = doc.createElement("thead");
var tr = doc.createElement("tr");
// split at delimiter
var rowArray = urlArray[0].split(delimiter);
addRow(thead, "th");
fragment.appendChild(thead);
var tbody = doc.createElement("tbody");
for(i=1;i<urlArray.length;i++){
var tr = doc.createElement("tr");
// split at delimiter
var rowArray = urlArray[i].split(delimiter);
tr.addEventListener ("click", function () {
// return index (add 1 because first row is the header row)
// window.document.title = this.rowIndex + 1;
window.AppInventor.setWebViewString(this.rowIndex + 1);
});
addRow(tbody, "td");
}
fragment.appendChild(tbody);
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("myTable").appendChild(table);
// http://stackoverflow.com/a/9236195/1545993
doc.getElementById("myTable").getElementsByTagName('table')[0].className = "striped";
function addRow(dom, tag) {
for(j=0;j<rowArray.length;j++){
var el = doc.createElement(tag);
el.innerHTML = rowArray[j];
tr.appendChild(el);
dom.appendChild(tr);
}
}
</script>
</body>
</html>
Related
I am trying to use javascript to extract data from the URL parameter 'utm_source' and add it to a field on a form so that it is stored in my contact database for tracking purposes.
I had previously accomplished this on another site, but when trying to reuse the code it is not working for me.
The page is here (with the included URL parameter to be extracted):
https://members.travisraab.com/country-guitar-clinic-optin-1-1?utm_source=youtube&utm_medium=description
The desired result if for the 'traffic_source' field on my form to be populated with the value from the 'utm_source' URL parameter, in this case 'youtube'.
Here is the code I am using:
<script type="text/javascript">
function addSource() {
var fieldToChange = document.getElementsByName("form_submission[custom_4]");
var source = trafficSource();
fieldToChange.value = source;
}
var trafficSource = function() {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == "utm_source"){
return pair[1];
} else if (pair[0] == "gclid") {
return 'google';
}
}
return 'unknown';
}
document.onload = addSource();
</script>
fieldToChange is a NodeList so if you want to change the value property you need to specify the index number
So this should fix your code
fieldToChange[0].value = source;
You can take all the query params using new URLSearchParams(window.location.search) and get the particular query param using searchParams.get('utm_source') and then, store the value of utm_source in form field using document.getElementById("utmsource").value = param;.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="utmsource" />
<script>
let searchParams = new URLSearchParams(window.location.search)
let param = searchParams.get('utm_source')
document.getElementById("utmsource").value = param;
</script>
</body>
</html>
Here is my HTML and JS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script src="functions.js"></script>
</body>
</html>
Here is my Javascript code
'use strict'
const buttonclick = document.getElementById('button')
const list = document.getElementById('lists')
const a = "<span><button class = 'rbutton'>X</button></span>" //list-item button
const clickhandler = () => {
const text = document.getElementById('text')
//creating a list element
if(text.value != ''){
let Newdiv = document.createElement('div')
// appending elements
Newdiv.innerHTML = text.value + a
list.appendChild(Newdiv)
let b = document.getElementsByClassName('rbutton')
if(b !=[]){
for(let i = 0; i < b.length; i++){
b[i].addEventListener('click', function(){
b[i].parentElement.parentElement.remove();
console.log(b)
})
}
}
//reseting the textarea value
text.value = ''
}
}
buttonclick.addEventListener('click', clickhandler)
An error in shown on delete a item: Cannot read property 'parentElement' of undefined at HTMLButtonElement. .
Can someone please explain what is wrong in my code and what does the error mean.
thankyou
On every click of the button you are attaching event handlers to the whole group again.
On the first iteration, 1st button has one delete handler.
On second iteration, 1st button has 2 event handler(one for buttons[0] and one for buttons[1]), and 2nd has one.
So on.
Use this. It will always point to the element to the event on which the event handler is attached:
this.parentElement.parentElement.remove();
Another way is to simply use this.parentElement.parentElement.remove()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
<script>
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
this.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
</script>
</body>
</html>
You should use window.event.target.parentElement... to get the button instead of b[i].parentElement....
"use strict";
const buttonclick = document.getElementById('button');
const list = document.getElementById('lists');
const a = "<span><button class = 'rbutton'>X</button></span>"; //list-item button
const clickhandler = () => {
const text = document.getElementById('text');
//creating a list element
if(text.value != '') {
let Newdiv = document.createElement('div');
// appending elements
Newdiv.innerHTML = text.value + a;
list.appendChild(Newdiv);
let b = document.getElementsByClassName('rbutton');
for(let i = 0; i < b.length; i++) {
b[i].addEventListener('click', function() {
window.event.target.parentElement.parentElement.remove();
});
}
//reseting the textarea value
text.value = '';
}
}
buttonclick.addEventListener('click', clickhandler);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2-d0</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>2-D0</h2>
<div id="heading">
<textarea id="text"></textarea>
<button id="button">Add</button>
</div>
<div id="lists">
</div>
</body>
</html>
I'm currently creating a dashboard and I want to create a "Bootstrap List Group" which should show a list of friends of the current dashboard.
I have given to arrays like this:
friendsID[id1, id2, id3]
friendsName[name1, name2, name3]
I want to create a method in javascript so that the result looks like this.
<div class="list-group">
name1
name2
name3
</div>
Would love to here how you would manage this because I am a little bit desperate and have no clue how to do this.
Here You can use document.write() to solve the problem it is used when the path for the html is not needed
var friendsID = ['id1','id2','id3'];
var i=0;
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
document.write("<a href='/dashboard/"+friendsID[i]+"' class='list-group-item list-group-item-action'>"+friendName[i]+"</a><br>")
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./java.js"></script>
</body>
</html>
Or You can Use Innerhtml in this the path inside which div the html must be kept is determined by the programmer.
var friendsID = ['id1','id2','id3'];
var i=0;
var statement =[0,0,0];
var friendName = ['name1','name2','name3'];
console.log(friendName[2]);
idplace();
function idplace(){
for(i=0;i<friendsID.length;i++)
{
statement[i]="<a href='google.com/"+friendsID[i]+"'>"+friendName[i]+"</a><br>";
console.log(statement[i]);
document.getElementById("hello").innerHTML+=statement[i];
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="hello"></div>
<script src="./java.js"></script>
</body>
</html>
You can do something like this
const friendsID = ["id1", "id2", "id3"]
const friendsName = ["name1", "name2", "name3"]
let i = 0;
for (i = 0; i < friendsID.length; i++) {
let list = '' + friendsName[i] + ""
$(".list-group").append(list)
}
<div class="list-group">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
check this out
https://jsfiddle.net/cloud_zero/hacLpe3g/4/
var arry1 = ["name1", "name2", "name3"];
var arry2 = ["id1", "id2", "id3"];
// merging two array
var result = arry1.reduce(function(acc, cur, index) {
return Object.assign(acc, { [arry2[index]]: cur })
}, {})
// generating links
var text = Object.keys(result).map(function(key) {
return `${ result[key] }`;
});
// finally adding to dom
document.querySelector('.list-group').innerHTML = text.join('');
first i merged two array to object (result)
then i generate links from the result
lastly linked added to DOM
First of all thank you for your great solutions!
I also tried my best and came up with this here.
var friendsIDs = ["id1", "id2", "id3"];
var friendsNames = ["name1", "name2", "name3"];
var friendLinks = [];
for (i=0; i < friendsIDs.length; i++){
friendLinks.push("<a href=/dashboard/" + friendsIDs[i] + " class=\'list-group item list-group-item-action\' >" + friendsNames[i] + "</a>")
}
//Create HTML Element for the Company Relations
var linkTarget = document.getElementById('linkTarget');
for(i=0; i < friendLinks.length; i++){
linkTarget.innerHTML += friendLinks[i];
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="list-group" id="linkTarget"></div>
I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?
<!DOCTYPE HTML>
<html>
<head>
<title>jsLoopDemo</title>
<!--
Honor Code: I acknowledge that this code represents my own work: CC
Date: July 6, 2017
-->
<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />
<script type="text/javascript">
do{
var numChose = prompt("Please enter an interger greater than zero.");
}while (isNaN(numChose) || numChose % 1 !== 0 || numChose < 1 );
function genTable(numChose)
{
var table = document.createElement("TABLE");
var tableBody = document.createElement("TBODY");
table.appendChild(tableBody);
var myTableDiv = document.getElementById("mytable");
for (var r = 0; r <= numChose; r++)
{
var tr = document.createElement("TR");
tableBody.appendChild(tr);
var td = document.createElement("TD");
tr.appendChild(td);
td.appendChild(document.createTextNode("Row " + r));
}
myTableDiv.appendChild(table);
}
</script>
</head>
<body>
<div id="mytable">
</div>
</body>
</html>
Two things:
You need to actually call the function after the prompt, so you need to add a line after your do while:
genTable(numChose);
That still won't work, since the DOM will not be ready (myTableDiv will be undefined), so you need to wrap your entire code in an event listener:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
Move the <script> code after the
<div id="mytable">
</div>
in <body> so that the element is rendered on DOM while table is being generated and call the function
genTable(numChose);
after you get the number from user.