Using Javascript to dynamically create buttons onload - javascript

So I'm having troubles understanding what I'm doing wrong here.
The big picture I'm trying to implement is a page with an iframe that is controlled with buttons that change the source of the iframe when pressed. The buttons would be dynamically created from a data structure that I wouldn't know the size of, which means that I needed to implement it as a loop.
So far I just added a pre-populated object and tried to implement the dynamic creation of the buttons to the HTML page, but I'm unable to create the buttons.
The code I'm trying to run is
<HEAD>
<TITLE>Testing stuff</TITLE>
</HEAD>
<BODY onload="script();">
<FORM>
<H2>Dynamically add button to form.</H2>
<span id="fooBar"> </span>
</FORM>
</BODY>
<script>
var URLobj = {
url1 : "https://www.lipsum.com/",
url2 : "https://www.cnet.com/news/",
url3 : "https://stackoverflow.com/"
};
function add(name, URL) {
//Create an input type dynamically.
var element = document.createElement("BUTTON");
//Assign different attributes to the element.
element.setAttribute("type", "button");
element.setAttribute("value", URL);
element.setAttribute("name", name);
alert(name);
var foo = document.getElementById("foobar");
//Append the element in page (in span).
alert('i can reach here');
foo.appendChild(element);
alert('i can not reach here');
}
window.onload = function iterator()
{
for (var key in URLobj) {
if (URLobj.hasOwnProperty(key)) {
add(key, URLobj[key])
}
}
}
</script>
Also, does this seem like any good of an approach for this kind of a problem? (Trying to add buttons dynamically) or will my next step prove to be tricky with my current approach (making the buttons control an iframe in the page)?

The main issue here is this line:
var foo = document.getElementById("foobar");
As JS is case sensitive, it should be:
var foo = document.getElementById("fooBar");
Pay close attention to the console when debugging stuff like this. This is the error you should see with your original code:
Uncaught TypeError: Cannot read property 'appendChild' of null
Also, the element type should be input based on your usage, not button. See below.
var URLobj = {
url1: "https://www.lipsum.com/",
url2: "https://www.cnet.com/news/",
url3: "https://stackoverflow.com/"
};
function add(name, URL) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "button");
element.setAttribute("value", URL);
element.setAttribute("name", name);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
window.onload = function iterator() {
for (var key in URLobj) {
if (URLobj.hasOwnProperty(key)) {
add(key, URLobj[key])
}
}
}
<HEAD>
<TITLE>Testing stuff</TITLE>
</HEAD>
<BODY onload="script();">
<FORM>
<H2>Dynamically add button to form.</H2>
<span id="fooBar"> </span>
</FORM>
</BODY>

Please check
var foo = document.getElementById("foobar");
To
var foo = document.getElementById("fooBar");

Related

How to change href value using javascript?

I have a wordpress site and theme that is providing me an ability to change elements in menu widget on all pages it appears only.
So, what I want to do is to change links and names of menu elements locally on one page. I have an id's for menu li elements, 'menu-item-7062' for example and a href tag inside it with already defined link and text values.
I have already tried and injected this code snippets in after all post content:
<script type='text/javascript'> document.getElementById('menu-item-7062').href = 'new link'; </script>
I have also created a function that is triggers after onclick event:
<script type="text/javascript">
document.getElementById("menu-item-7062").onclick = function() {
document.getElementById("menu-item-7062").href="my new link";
};
</script>
Unfortunately, they didn't affect my old link. Returning to my question, what are other solutions I could try in order to change both a href link and text value? What possible mistakes I have made?
UPDATED:
Here is my anchor tag
Автоматизация технологических процессов
A tag located under the <li id="menu-item-7062">, there is my mistake.
Did you try setAttribute function
document.getElementById("menu-item-7062").setAttribute("href", "my new link");
I have successfully affected a tag by query selector:
<script type="text/javascript">
var tag = document.querySelector('a[href="https://test.etm.io/ru/services/automation/"]');
if(tag){
tag.innerHTML = "new";
}
</script>
you should try this..
var a = document.getElementsByTagName("a");
a[0].href = "www.abc.com/";
if you doesn't know index of a then you should get id of a and then set link.
This will help you to check and set href for tag "a" without "id":
const parent = document.getElementById("menu-item-7062");
if(parent.firstElementChild.localName === 'a') {
const child = parent.firstElementChild;
child.href = 'my new link';
}
OR
const parent = document.getElementById("menu-item-7062");
parent.firstElementChild?.href = 'my new link';

jscript to run at window.onload AND item.onchange

I'm using jscript to load a string in to several elements of an array, then display the useful element in html.
There's a pulldown menu that causes the string to change. So, I need the function to be re-run when that happens.
I have been able to successfully display the element using window.onload
and, I have been able to successfully display the element AFTER the pulldown menu has been changed.
But, I can't seem to display the element with window.onload and subsequently after item.onchage
If anyone has any suggestions, I'd be grateful.
Here is the code that works for window.onload
window.onload = function() {
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
//loads the string in to an array and returns the 2nd element
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
}
Here is the code that works for pulldown.onchange
jQuery(function(){
jQuery('.dropdownimage-format select').on('change', function(){
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
});
In both cases, the element is displayed in html by
<a id="MASNUM">

assigning variable to document.getElementById().Innerhtml not working

See the code below:
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
var MessageElement= document.getElementById("happy").innerHTML
var Message=text[messageIndex];
MessageElement=Message;
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
It doesn't work.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Why is it so?
Sorry, I am a newbie learning JavaScript.
Because that's how variables and values work in JavaScript. Imagine variables to be like containers. With
var MessageElement = document.getElementById("happy").innerHTML
the container MessageElement will contain a string. Later on, with
MessageElement = Message;
you simply put a new value in the container, overwriting the previous value/content the container had. But it doesn't have any effect on the location where the previous value was coming from.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Now the variable contains a reference to the DOM element and
MessageElement.innerHtml = Message
doesn't assign a new value to the variable (doesn't put a new value in the container), it uses the value of the variable (container).
innerHTML return a string not e pointer to the document.getElementById("happy")'s text node.
try this
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
document.getElementById("happy").innerHTML = text[messageIndex];
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
#Felix King is correct.
To test how it is actually behaving I myself tried the below snippet on W3Schools.
And I found:
var MessageElement = document.getElementById("happy") - assigns the element (in my example - http://www.microsoft.com/)
alert(m) thus displays - http://www.microsoft.com/
m.innerHTML = "Atul" - assigns Atul to the element.
However, value of m was still http://www.microsoft.com/ as Felix rightly said - 'MessageElement.innerHtml = Message, doesn't assign a new value to the variable'.
<html>
<head>
<script>
function changeLink()
{
var m = document.getElementById("myAnchor"); //assigns http://www.microsoft.com/
alert(m); //
m.innerHTML = "Atul"
alert(document.getElementById("myAnchor").innerHTML + " new");
document.getElementById('myAnchor').innerHTML=m;
}
</script>
</head>
<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
</body>
</html>
Thanks Felix :)

Passing a variable into a DOM function in Javascript

I took this example from w3schools and modify it to this. The code below is not working.
What I intend to do is hide the div with id "demo1". It is not working. What is the problem?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(div_id)
{
//here the div_id variable seems to unparsable by the DOM event
document.getElementById(div_id).innerHTML = hello;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('demo1')">Click me</button>
<div id="demo1"></div>
<div id="demo2"></div>
</body>
</html>
The variable hello is not defined. You were probably looking to set the innerHTML as a String:
function myFunction(div_id) {
document.getElementById(div_id).innerHTML = "hello";
// -----------------------------------------^-----^
}
DEMO: http://jsfiddle.net/uzuKp/1/
Even though you took an example from W3Schools and modified it, I'd suggest binding events separate from the HTML and storing associated data in data-* attributes. In your example, it can be as something like this:
<p>Click the button to trigger a function.</p>
<button data-div-id="demo1">Click me</button>
<button data-div-id="demo2">Click me</button>
<button data-div-id="demo1">Click me</button>
<div id="demo1">demo1</div>
<div id="demo2">demo2</div>
And the JS:
function clickHandler() {
var targetDivId, targetDiv;
targetDivId = this.getAttribute("data-div-id");
targetDiv = document.getElementById(targetDivId);
targetDiv.innerHTML = "Hello" + new Date().getTime();
}
function loadHandler() {
var buttons, i, j, cur;
buttons = document.getElementsByTagName("button");
for (i = 0, j = buttons.length; i < j; i++) {
cur = buttons[i];
cur.onclick = clickHandler;
}
}
window.onload = loadHandler;
DEMO: http://jsfiddle.net/3K4RD/
Although I would also suggest looking at the following article to see different ways to bind events: addEventListener vs onclick
One final suggestion I have is to not set the innerHTML property. You may have a simple example here, but it's usually a better idea to use DOM methods like appendChild (to add a node) and document.createTextNode (to create text that can be appended). Of course, that would require the contents to be cleared out first, something like:
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
targetDiv.appendChild(document.createTextNode("Hello"));
DEMO: http://jsfiddle.net/52Kwe/
You could also store the specific string that needs to be set as the innerHTML as a data-* attribute (especially if it differs between buttons).
UPDATE:
Per your recent edit, the style property is a special property, which is actually a special object with style properties that you need to set. So for your example, you have to set the .style.display value, like:
document.getElementById(div_id).style.display = "none";
document.getElementById(div_id).style.display = 'none';
document.getElementById(div_id).style.visibility= 'hidden';

Element onclick event does not show data

I have the following script to create some hyperlinks which are numbers stored in an array. I want to be able to click those numbers and get the particular number to be shown in the alert box. I am able to see the links but when I click them I don't see any data.
<html>
<body>
<script type="text/javascript">
var str="732176086,732176085,735219154,735219155,23948614,23948629,23948628,764488973,764488974,764488975,23948631,732164301,732164304,732164305,732164303,732164302,732168040,832567989,832567988,807573121,807573120,765867299,831150154,831150153,23951065,23952295";
var str_array=str.split(',');
for(var i=0;i<str_array.length;i++)
{
controlRef = document.createElement('a');
var newLine=document.createElement('br');
document.body.appendChild(newLine);
controlRef.href = '#';
controlRef.innerHTML = str_array[i];
document.body.appendChild(controlRef);
}
controlRef.onclick = function () { alert(controlRef.innerHTML); };
</script>
</body>
</html>
Place the click handler inside of the for loop.
You also need to break the closure to controlRef. Otherwise the controlRef will point to the last element.
controlRef.onclick = (function(element) {
return function() {
alert(element.innerHTML);
};
})(controlRef);
jsFiddle.

Categories

Resources