Best way to create new DOM elements using Jquery - javascript

is it better to create a DOM element like this:-
var option='';
var objY = $('select[name="yaxis"]');
for(var key in summaryObj)
{
option += '<option value="'+summaryObj[key]+'">'+key+'</option>';
}
objY.html(option);
or like this,
var objY = $('select[name="yaxis"]');
var option = document.createElement("option");
for(var key in summaryObj)
{
var san = summaryObj[key];
objY.append($(option).clone().attr({value:san,text:key}));
}

For perfomance, this is probably among the fastest ways
var option = document.createElement("option");
var frag = document.createDocumentFragment();
for (var key in summaryObj) {
var clone = option.cloneNode();
clone.value = san;
clone.innerHTML = key;
frag.appendChild(clone);
}
$('select[name="yaxis"]').append(frag);
For readability, I like this
var objY = $('select[name="yaxis"]');
var frag = [];
$.each(summaryObj, function(key, val) {
frag.push(
$('<option />', {
value : san,
text : key
})
);
});
objY.append(frag);

In jQuery, you Do it like this:
var select = $('<select>').attr('name','yaxis');
var option = $("<option>");
option.text('word').value('word');
select.append(option);

Related

Javascript. Change a form option based on a previous one

I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}

appending to the DOM - vanilla javascript

I wanted to practice my vanilla javascript skills since I've been so library-heavy lately. My goal was to filter an array of JSON data (by events after 10/01/2015), and then append them as list items to the DOM, with the class being "events", and give the ability to delete events. Why isn't this working?
https://jsfiddle.net/youngfreezy/7jLswj9b/
function convertToJSData(arr) {
for (var i = 0; i < arr.length; i++) {
// var from = "10-11-2011";
var from = arr[i].date;
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0] - 1, numbers[1]);
arr[i].date = date;
}
console.log(arr[0].date);
return arr;
}
function getByDate(data) {
convertToJSData(data);
var filterDate = new Date(2015, 09, 01);
return data.filter(function (el) {
return el.date >= filterDate;
});
}
var filteredDates = getByDate(events);
filteredDates.sort(function (a, b) {
return a.date - b.date;
});
console.log(filteredDates.length); //returns 6
var appendHTML = function (el) {
var list = document.getElementById("events");
for (var i = 0; i < filteredDates.length; i++) {
var listItem = filteredDates[i].name;
listItem.className = "event-list";
list.appendChild(listItem);
}
};
appendHTML(document.body);
var deleteEvent = function () {
var listItem = this.parentNode;
var ul = listItem.parentNode;
//Remove the parent list item from the ul
ul.removeChild(listItem);
}
when you do:
var listItem = filteredDates[i].name;
listItem.className = "event-list";
list.appendChild(listItem);
listItem is a string. You cannot append it as a child, you need to create a DOM element and append that:
var newEl = document.createElement('div');
newEl.className = "event-list";
newEl.innerHTML = filteredDates[i].name;
list.appendChild(newEl);
On a separate note, to just focus on the vanilla JS part of the question, maybe something like the following should illustrate the idea more generally:
let newElement = document.createElement("div");
newElement.innerHTML += `<ul><li>Item 1</li><li>Item 2</li></ul>`;
newElement.className = "item-list";
document.getElementById("root").append(newElement);

Use associative Javascript arrays to populate dropdown, then fill text box

I'm new to Javascript (but fairly proficient in php) and I'm trying to use a set of associative arrays to perform two tasks.
First: Populate a dropdown menu (this part is working)
var select = document.getElementById('FName');
var options = fNames;
for(var i = 0; i < (options.length-1); i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
The 'fNames' variable is an array with a list of strings which I've taken from a php array. I have another array, called 'fDesc' which is indexed to match the 'fNames' array. Something like this:
var fNames = ["aName", "bName", "cName"]
var fDesc = ["aDesc", "bDesc,", "cDesc"]
They're currently separate arrays, not a single multidimensional one.
How can I make "aDesc" appear in a text box when "aName" is selected from the pulldown menu?
First of all, the for element is population less elements, you should remove the -1 of (options.length-1)
Then you need to asociate a handler event for select.onchange and use index of to retrieve the index of the array.
HTML:
<select id='FName'></select>
<input id='AName' type='text'/>
JS:
var fNames = ["aName", "bName", "cName"];
var fDesc = ["aDesc", "bDesc,", "cDesc"];
var select = document.getElementById('FName');
var options = fNames;
for(var i = 0; i < (options.length); i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
select.onchange = function(){
var textbox = document.getElementById('AName');
textbox.value = fDesc[fNames.indexOf(select.value)];
}
JsFiddle:
http://jsfiddle.net/dBtUz/
better put aName as text and aDesc as value.
HTML
<select id='FName' onchange='fillText()'></select>
<input id='Fdesc' type='text'/>
Javascript
window.onload = function(){
var fNames = ["aName", "bName", "cName"]
var fDesc = ["aDesc", "bDesc", "cDesc"]
var select = document.getElementById('FName');
for(var i = 0; i < (fNames.length); i++) {
var el = document.createElement("option");
el.textContent = fNames[i];
el.value = fDesc[i];
select.appendChild(el);
}
select.selectedIndex = -1;
}
function fillText(){
document.getElementById('Fdesc').value = document.getElementById('FName').value;
}
You need to search the index of the selected value and then you get with that index the same position in your search array.
Updated Solution also with manual fill:
<script>
document.addEventListener('DOMContentLoaded', onDomContentLoaded);
// data
var fNames = ["aName", "bName", "cName"];
var fDesc = ["aDesc", "bDesc", "cDesc"];
function onDomContentLoaded() {
var mySelect = document.getElementById("mySelect");
fillSelect(mySelect);
mySelect.addEventListener('change', onSelectChange);
}
function fillSelect(mySelect) {
for(var i = 0; i < (fNames.length); i++) {
var opt = fNames[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
mySelect.appendChild(el);
}
}
function onSelectChange(){
var selectedValue = this.options[this.selectedIndex].value;
//console.log('selected value', selectedValue);
var selectedValueIndexInArray = fNames.indexOf(selectedValue);
var fieldOutput = document.getElementById("output");
fieldOutput.innerHTML = fDesc[selectedValueIndexInArray];
}
</script>
<select id="mySelect"></select>
<div id="output"></div>
Working Example
http://jsfiddle.net/x92ka/4/

hr tag in javascript

I am working on phonegap and I am new to it. I want to draw a line using hr under the menu items which are displayed. but unfortunately I am unable to do so.
if somebody can help in this regard. Thanks in advance.
here is the code snippet
{
success:function(res,code) {
entries = [];
var xml = $(res);
var items = xml.find("item");
$.each(items, function(i, v) {
category1.push($(v).find("category").text());
/* $("#status").append("menu_type <b>"+menu_type+"</b><br/>"); */
console.log( "PRICE" + ": " + $(v).find("menu_type").text() );
});
var category = category1.unique();
var select = document.getElementById("selectNumber");
for(var i = 0; i < category.length; i++) {
var el1 = document.createElement("li");
var opt = category[i];
var el = document.createElement("a");
el.textContent = opt;
el.value = opt;
el1.appendChild(el);
select.appendChild(el1);
}
}
Try adding something like this
document.getElementById("ElementBelowWhichHRShouldCome").appendChild(document.createElement('hr'));
Try innerHTML. Here is an example:
http://jsfiddle.net/Wxv6n/
var doc = document;
var get = function(id){return doc.getElementById(id);};
get("foo").innerHTML = '<hr/>';
..and don't forget to cache your references to document
After Every Menu Item,you can use this.Its pretty simple.
$("#menu_item").after('<hr/>');
after() in jquery
DEMO FIDDLE

How do I populate a select box automatically with values from a IndexedDB objectStore?

I would like to iterate over a IndexedDB objectStore, get the results and populate this select box.
This is my HTML
<tr>
<td>
<select id="opt" name="opt"></select>
</td>
</tr>
This is my JavaScript
function populateOptions() {
var options = [ "1", "2", "3", "4", "5"];
var opt = document.getElementById("opt");
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.value = options[i];
var optionText = document.createTextNode(options[i]);
option.appendChild(optionText);
opt.appendChild(option);
}
}
populateOptions();
Try the following:
var dbreq = indexeddb.open("db");
dbreq.onsuccess = function (conn){
var trans = dbreq.result.transaction(["objectstore"]);
var obj = trans.objectStore("objectstore");
var cursor = obj.openCursor();
cursor.onsuccess = function (e) {
if (!cursor.result) {
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = cursor.result.value;
var optionText = document.createTextNode(cursor.result.value);
option.appendChild(optionText);
opt.appendChild(option);
cursor["continue"]()
} else {
// cursor ended
}
}
Or use my linq2indexeddb library and do it like this:
var db = linq2indexedDB("db");
db.linq.from("objectstore").select.then(null, null, function(e){
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = e.data;
var optionText = document.createTextNode(e.data);
option.appendChild(optionText);
opt.appendChild(option);
});
for more information about indexeddb I can reffer to my blog. Here I frequently post information about the indexedDB API.
In html :
<body onload="load()">
In javascript :
function load(){
populateOptions();
}
or shortly :
<body onload="populateOptions()">

Categories