dynamically create div element using javascript - javascript

I am trying to create html elements dynamically using javascript. For example, when creating a paragraph in my "finalXML" file, I use the syntax below:
function paragraph (finalXML, value)
{
var code1 = 'var para = document.createElement("p");
var t = document.createTextNode("This is the paragraph that should be displayed");
para.appendChild(t);
document.body.appendChild(para);'
return String(finalXML).replace(/add_paragraph_here/g,code1);
}
How would I go about creating a div with radio buttons, for example, using the same process? Can anyone help me with that syntax?

see this example: http://jsfiddle.net/kevalbhatt18/owuqm8j8/
var radio_home = document.getElementById("radio_home");
function makeRadioButton(options) {
var div = document.createElement("div");
for (var i = 0; i < options.length; i++) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = options[i].name;
radio.value = options[i].value;
label.appendChild(radio);
label.appendChild(document.createTextNode(options[i].text));
div.appendChild(label);
}
radio_home.appendChild(div);
}
var options = [{
name: "first",
value: "yes",
text: "yes"
}, {
name: "first",
value: "no",
text: "no"
}]
var options2 = [{
name: "second",
value: "ohhh yes",
text: "ohhh yes"
}, {
name: "second",
value: "ohhh no",
text: "ohhh no"
}]
makeRadioButton(options);
makeRadioButton(options2);

Related

OnClick() event is not working in JavaScript for dynamic button in my code

I have added a dynamic buttons inside for loop on webpage using JavaScript and assigned a unique id to each button. I wants to assign onclick() event Listener to each button but this function is not being assigned to any of dynamic buttons. Kindly help me resolving this. Thank You.
myfunction()is working but myfunction1() has some problem. I cannot see onclick event in its dynamically HTML.
There are JS file. data.js contains arrays of objects and other contains function which access the data.
// function.js
function chargerArticles() {
var myShoppingCart = [];
var articles = document.getElementById("content");
for (var i = 0; i < catalogArray.length; i++) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
//Product Name
var articleName = document.createElement("h4");
articleName.setAttribute("class", "aa-product-title");
var articleNameLink= document.createElement('a');
articleNameLink.setAttribute('href',"#");
articleNameLink.innerText = catalogArray[i].name;
articleName.appendChild(articleNameLink);
article.appendChild(articleName);
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
//not working
button.addEventListener("click", myFunction1);
function myFunction1() {
var item = this.getAttribute("id");
var pos = item.substring(0, 1);
document.getElementById("1235").innerHTML = "Hello World";
addToCart(pos);
}
//working
document.getElementById("1234").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("1234").innerHTML = "YOU CLICKED ME!";
}
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
function searchInCart(name) //T-Shirt
{
myShoppingCart = myCartArray;
var name1 = name;
var stop = 0;
for (var i = 0; i < myShoppingCart.length && stop == 0; i++) {
if (myShoppingCart[i].name == name1) {
stop = 1;
// console.log("Hello wooooorld!");
return true;
} else {
return false;
}
}
}
function addToCart(pos) {
if (searchInCart(catalogArray[pos].name)) {
alert("Already Exist!"); // display string message
} else {
var ident = pos + "-qte";
var quatity = document.getElementById("ident").value;
if (quatity > 0) {
var articleCmd = {}; //array of objects
articleCmd.name = catalogArray[pos].name;
articleCmd.price = catalogArray[pos].price;
articleCmd.qte = quatity;
articleCmd.priceTotal = articleCmd.price * articleCmd.qte;
myCartArray.push(articleCmd);
} else {
// alert
}
}
}
//data.js
// data.js
var catalogArray = [{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code: 101,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
},
];
var myCartArray = [{
name: "T Shirt c100",
price: 150,
qte: 2,
TotalPrice: 150,
}
];
This issue occurred because you defined myfunction1 dynamically. In other words, this element wasn't defined during the initial rendering of the page.
You can fix it by using event delegation. Here is how:
Instead of defining the callback on the element, define it for all children of the PARENT element that have the matching css class. For example:
$( ".btnContainer .btn" ).on( "click", function( event ) {
event.preventDefault();
console.log("clicked");
});
where:
<div class='btnContainer'>
</div>
Now when you add buttons with (class name btn) dynamically as children of btnContainer, they will still get access to the click handler, because the event handler isn't bound to the element btn, but to it's parent, hence when the click event is fired, the parent delegates the event to all it's children with the matching class(es)!
Do not add a function in a loop
Delegate
Have a look here. There are MANY issues, I have addressed a few of them
You MAY want to do
button.setAttribute("data-code",item.code);
instead of
button.id = i + "-cmd";
// function.js
const content = document.getElementById("content");
content.addEventListener("click",function(e) {
const tgt = e.target, // the element clicked
id = tgt.id; // the ID of the element
if (id.indexOf("-cmd") !=-1) { // is that element one of our buttons?
// get the name of the article from the button - this could also be a data attibute
var pos = id.split("-")[1];
addToCart(pos);
}
})
function chargerArticles() {
const myShoppingCart = catalogArray.map(function(item, i) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
// here would be a good place to add item.name or something
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
content.appendChild(articles) // ???
})
}
function searchInCart(name) {
return myCartArray.filter(function(x) {
return x.name === name
})[0];
}

Uncaught TypeError: sel.add is not a function

HTML with select tag:
<select id="sel"></select>`
here in JavaScript part, I am trying to add options in select dropdown creating them inside for loop assigning array values to option:
var sel = document.getElementById('sel').value;
var jsonobj = {School_charles: {class_A: [{ idkey: "1", name: "john" },
{ idkey: "2", name: "jill" }]}};
for(var i = 0; i <= jsonobj.School_charles.class_A.length; i++) {
var option = document.createElement('option');
option.text = jsonobj.School_charles.class_A[i].idkey;
option.value = jsonobj.School_charles.class_A[i].name;
sel.add(option);
}
Please tell me where I am wrong, I am learning JavaScript.
You have two mistakes in your code:
var sel = document.getElementById('sel').value; should be just var sel = document.getElementById('sel'); so the the variable sel references the actual select element instead of the select value. That is the reason the add() method was not recognised.
Your for loop condition should be only i < jsonobj.School_charles.class_A.length and not <=
var sel = document.getElementById('sel');
var jsonobj = {
School_charles: {
class_A: [{
idkey: "1",
name: "john"
}, {
idkey: "2",
name: "jill"
}]
}
};
for (var i = 0; i < jsonobj.School_charles.class_A.length; i++) {
var option = document.createElement('option');
option.text = jsonobj.School_charles.class_A[i].idkey;
option.value = jsonobj.School_charles.class_A[i].name;
sel.add(option);
}
<select id="sel"></select>
Two mistakes there
document.getElementById('sel').value should be document.getElementById('sel')
i <= jsonobj.School_charles.class_A.length should be i < jsonobj.School_charles.class_A.length
var sel = document.getElementById('sel');
var jsonobj = {School_charles: {class_A: [{ idkey: "1", name: "john" },
{ idkey: "2", name: "jill" }]}};
for(var i = 0; i < jsonobj.School_charles.class_A.length; i++) {
var option = document.createElement('option');
option.text = jsonobj.School_charles.class_A[i].idkey;
option.value = jsonobj.School_charles.class_A[i].name;
sel.add(option);
}
<select id="sel"></select>

Unable to get dynamically created checkboxes to work

I've been searching the site for a solution however, ive had no luck getting this to work. The desired end result for this piece of code will be to hide and show rows on a table with the checkboxes - the checkboxes are default set to checked as the tables by default are all shown, at the end of the code is my current method of trying to get the checkboxes to activate.
function searchContents(table, noRows) {
document.getElementById('dynamicSearchContents').innerHTML = "";
//locals declarations
var i;
var checkboxes = [];
//labels
var lables = [];
var bikesTableRows = ["Bike ID", "Bike Status", "Bike Cost", "Bike type", "Last Maintainance", "Lock Code", "Depot"];
var staffTableRows = ["Staff ID", "Fullname", "Role", "DOB", "Full Address", "Mobile", "Landline", "Email", "Notes"];
var repairTableRows = ["Repair ID", "Bike ID", "Fault", "Reported Data", "Repair Started", "Reapir Completed", "Parts Required", "Assigned Mechanic", "Repair Notes"];
var customerTableRows = ["Customer ID", "Fullname", "DOB", "Full Address", "Mobile", "Landline", "Email", "Notes"];
var collectionsTableRows = ["Job ID", "Collection Depot", "Delivery Depot", "Time and Date Started", "Time and Date Completed", "Assigned Driver"];
for (i = 0; i < noRows; i++) {
//creation
var br = document.createElement("br");
checkboxes[i] = document.createElement('input');
lables[i] = document.createElement('label');
//setting
checkboxes[i].type = "checkbox";
checkboxes[i].name = "checkbox" + i;
checkboxes[i].value = "value";
checkboxes[i].checked = "true";
checkboxes[i].class = "checkboxClass"
checkboxes[i].id = "checkbox" + i;
lables[i].htmlFor = "checkbox" + i;
//what lables
if (table === "bikeInnerTable") {
console.log("Bikes Lables")
lables[i].appendChild(document.createTextNode(bikesTableRows[i]));
}else if (table === "staffInnerTable") {
console.log("Staff Lables")
lables[i].appendChild(document.createTextNode(staffTableRows[i]));
}else if (table === "repairInnerTable") {
console.log("Repair Lables")
lables[i].appendChild(document.createTextNode(repairTableRows[i]));
}else if (table === "customerInnerTable") {
console.log("Customer Lables")
lables[i].appendChild(document.createTextNode(customerTableRows[i]));
}else if (table === "collectionsInnerTable") {
console.log("Collections Lables")
lables[i].appendChild(document.createTextNode(collectionsTableRows[i]));
}
//appending
document.getElementById('dynamicSearchContents').appendChild(lables[i]);
document.getElementById('dynamicSearchContents').appendChild(checkboxes[i]);
document.getElementById('dynamicSearchContents').appendChild(br);
}
$('.checkboxClass').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
console.log("blahahaha");
}
});
}
Edit:
A button is pressed which is located on each of the tables, it calls a function to show the search/filter div, and also the below code to populate it's contents
Pass the third argument in the jquery on function like so:
$('body').on('change', '.checkboxClass', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
console.log("blahahaha");
}
});
}
This will bind any future elements with '.checkboxClass' that are created to this same function.

Having trouble with createElement and appendChild

I have a reasonably simple idea that I would like to implement.
I have an array of objects with two properties: "id" and "name" I would like to list these in a series of "p" tags that would be within a "div".
So here is the HTML:
<body>
<div id="listView"></div>
</body>
And here is the JavaScript in the tag:
sessionStorage.eventid = 2;
var playerList = [];
playerList[0].id = 0;
playerList[0].name = "Add New Player";
playerList.push({
id: 5,
name: "Asako"
});
playerList.push({
id: 6,
name: "James"
});
playerList.push({
id: 7,
name: "Brian"
});
playerList.push({
id: 8,
name: "Helmut Spargle"
});
function listAll() {
var element = document.getElementById("listView");
var div;
var node;
for (var i = 0; i < playerList.length; i++) {
div = document.createElement("div");
div.setAttribute("onClick", "javascript: formOver(" + playerList[i].id + ")");
node = "<p>" + playerList[i].name + "<br />\n" +
"<small>&nbsp</small>\n" +
"</p>\n";
div.appendChild(node);
element.appendChild(div);
}
}
window.onLoad = function(){
listAll();
}
This doesn't fill the with anything. I have put this up on JSFiddle as well.
Have I misunderstood how Array.push works? Or something to do with appendChile and createElement?
Thanks in advance for your help.
Two problems - up front, trying to set the id and name on playerList[0] (which doesn't exist yet) won't work.
Second, trying to add a whole "node" full of html, jQuery-style, doesn't work in a plain-JS world. You need to build up the individual elements.
sessionStorage.eventid = 2;
var playerList = [];
playerList.push({
id: 0,
name: "Add New Player"
});
playerList.push({
id: 5,
name: "Asako"
});
playerList.push({
id: 6,
name: "James"
});
playerList.push({
id: 7,
name: "Brian"
});
playerList.push({
id: 8,
name: "Helmut Spargle"
});
function listAll() {
var element = document.getElementById("listView");
var div = document.createElement("div");
var node = "some string";
for (var i = 0; i < playerList.length; i++) {
div = document.createElement("div");
div.setAttribute("onClick", "formOver(" + playerList[i].id + ")");
var p = document.createElement('p');
p.innerHTML = playerList[i].name;
var br = document.createElement('br');
p.appendChild(br);
var small = document.createElement('small');
small.innerHTML = ' ';
p.appendChild(small);
div.appendChild(p);
element.appendChild(div);
}
}
listAll();
Example: http://jsfiddle.net/NF45y/
Initially:
var playerList = [];
playerList[0].id = 0;
You should get an error here about trying to set the id property of undefined. You can do:
var playerList = [{}];
playerList[0].id = 0;
playerList[0].name = "Add New Player";
or add the object the same way the others are. Within the function;
function listAll() {
var element = document.getElementById("listView");
var div;
var node;
for (var i = 0; i < playerList.length; i++) {
div = document.createElement("div");
div.setAttribute("onClick", "javascript: formOver(" + playerList[i].id + ")");
Don't use setAttribute to add listeners that way, it's not how it's intended to be used and doesn't work everywhere, use DOM properties for simplicity:
div.onclick = function(){...};
Since you are setting values inside a loop, you need to break the closure with the variables. An immediately invoked function expression (IIFE) can help:
div.onclick = (function(id) {
return function(){formOver(id);}
}(playerList[i].id));
Don't use XML syntax in an HTML document, and there isn't much point in the '\n' unless you are going to read the markup:
node = "<p>" + playerList[i].name + "<br><small>&nbsp</small></p>";
div.appendChild(node);
appendChild expects a DOM element, not markup. Since this is the only content of the div, you can use the markup to set its innerHTML property (you might want to change the name of node to say markup):
div.innerHTML = node;
element.appendChild(div);
}
}

listbox return wrong value in wordpress3.9

I used the listbox UI element in Wordpress 3.8, but it does not work in its newer version (3.9). I wrote this JS code to test it:
(function() {
var ICONS;
var icon = function(id) {
return '<i class="fa fa-' + id + '"></i>';
}
ICONS = ["rub", "ruble", "rouble", "pagelines", "stack-exchange", "arrow-circle-o-right", "arrow-circle-o-left", "caret-square-o-left", "toggle-left", "dot-circle-o", "wheelchair", "vimeo-square", "try", "adjust", "anchor", "archive", "arrows", "arrows-h", "arrows-v", "asterisk", "ban", "bar-chart-o", "barcode", "bars", "beer", "bell", "bell-o", "bolt", "book", "bookmark", "bookmark-o", "briefcase", "bug"]
var menuval=[];
for (var i = 0; i < ICONS.length; i++) {
var _id = ICONS[i];
menuval.push({text: icon( _id )+' '+_id, onclick: function(){setcontentfun(_id)}
});
}
tinymce.PluginManager.add("font_awesome_glyphs", function(editor, url) {
var menucreate=editor.addButton('fontAwesomeGlyphSelect', {
type: 'listbox',
text: 'Icons',
icon: false,
values: menuval
});
});
function setcontentfun(id) {
alert(id);
return false;
}
})();
This created displayed a listbox, but when I click on a menu item instead of alerting the last element of "ICON" array it displays all elements in listbox. How can I alert the list item, which I clicked?
Just did some updates in your code:
var menuval=[];
var insertVar = function (val) {
return function () {
editor.insertContent(val);
}
};
for (var i = 0; i < SHORTCODES.length; i++) {
var _id = SHORTCODES[i];
var _code = SHORTCODE_EXE[i];
var variable = insertVar(_code);
//alert(_id+' '+ SHORTCODES[i]+' '+SHORTCODE_EXE[i]);
menuval.push({text: _id, onclick: variable });
}

Categories