Here is the code I have, I am trying to append the elements in the array to a drop down select box. The code works fine until the appendChild method. I can't figure out why that one line is not working. Here is the code
</head>
<body>
<h1> Eat Page</h1>
<p id="test">Hi</p>
<select id="CusineList"></select>
<script type="text/javascript">
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i <cuisines.length; i++){
var optionElement = document.createElement("option");
optionElement.innerHTML = cuisines[i];
optionElement.value = i;//cuisines[i];
//document.getElementById("test").innerHTML = cuisines.length;
sel.appendChild(optionElement);
}
</script>
<p> When </p>
</body>
</html>
You have spell miss.
Your id is CusineList, but when you use CuisineList to select.
Beside that, your code works.
There's a typo on
var sel = document.getElementById('CuisineList');
This should be
var sel = document.getElementById('CusineList');
Or change your html. From
<select id="CusineList"></select>
To
<select id="CuisineList"></select>
When we append node using java script, after setting nodes' attributes/properties first we have to append this node into its related parent and after appending node, we can set its content or related inner HTML / text.
here is the solution for above issue:
var cuisines = ["Chinese", "Indian"];var sel = document.getElementById('CusineList');
var optionElement;
for (var i = 0; i < cuisines.length; i++) {
optionElement = document.createElement("option");
optionElement.value = i;
sel.appendChild(optionElement);
optionElement.innerHTML = cuisines[i];
document.getElementById("test").innerHTML = cuisines.length;
}
I have created a bin with the solution on http://codebins.com/codes/home/4ldqpcn
Related
I'm using following code for translation elements with data-i18next attribute:
const elementsToTranslate = document.querySelectorAll('[data-i18next]');
for (let i = 0; i < elementsToTranslate.length; i++) {
elementsToTranslate[i].innerText = i18next.t(elementsToTranslate[i].getAttribute('data-i18next'));
}
But it replaces all child elements.
I have h1 element with span child:
<h1 data-i18next="header-title" class="header__title">
<span data-i18next="header__subtitle" class="header__subtitle"></span>
</h1>
After running translation function it becomes:
<h1 data-i18next="header-title" class="header__title">translated-text</h1>
But I need child items to stay. Without jquery.
Result I need:
<h1 data-i18next="header-title">translated-title
<span data-i18next="header__subtitle">translated-span</span>
</h1>
Create a textnode and prepend it in the element. This should end up in the result you seek according to your edit.
The function i18next.t() is not known, since you did not provide it. Thus I replace it with the attribute text for now.
<html>
<head>
<script>
//Scope for the little translator and the list of textnodes
;(function(ns){
'use strict';
var _List = []; //Stores the created textnodes
//Removes the textnodes from the List
function _removeNodes(){
if(_List && _List.length){
for(var i=_List.length-1; i>=0; i--){
_List[i].parentNode && _List[i].parentNode.removeChild(_List[i])
};
_List = []
}
};
ns.Translator = {
Translate: function(){
_removeNodes();
const elementsToTranslate = document.querySelectorAll('[data-i18next]');
for (let i = 0; i < elementsToTranslate.length; i++){
var tE = elementsToTranslate[i];
var tText = tE.getAttribute('data-i18next'); //i18next.t(tE.getAttribute('data-i18next'));
var tN = document.createTextNode(tText);
_List.push(tN); //The node gets stored, so it can be removed again later
tE.insertBefore(tN, tE.firstChild)
}
}
}
}(window._ = window._ || {}));
window.onload = function(){
_.Translator.Translate()
_.Translator.Translate()
_.Translator.Translate()
}
</script>
</head>
<body>
<h1 data-i18next="header-title" class="header__title">
<span data-i18next="header__subtitle" class="header__subtitle"></span>
</h1>
</body>
</html>
Result:
<h1 data-i18next="header-title" class="header__title">header-title
<span data-i18next="header__subtitle" class="header__subtitle">header__subtitle</span>
</h1>
updated. I want to translate both: title and span inside it.
#caesay subtitle is span and it's better to put it inside
I am completely new to HTML and JavaScript and I am completely lost.
I am trying to create a to do list where input adds to the top of the list, and when an item in the list is clicked, it is removed.
I am trying to avoid using JQuery or anything outside of pure js.
<!DOCTYPE html>
<html>
<script type="text/JavaScript">
var number_of_items = 0;
var list = [];
var list_container = document.createElement("div");
list_container.id = "container";
function makelist(){
list_container.innerHTML = "";
list.unshift(document.getElementById("todo").value);
++number_of_items;
document.getElementsByTagName("body")[0].appendChild(list_container);
var list_element = document.createElement("ul");
list_container.appendChild(list_element);
for( var i=0 ; i < number_of_items ; ++i){
var list_item = document.createElement("li");
list_item.innerHTML = list[i];
//The problem is here
list_item.onClick = function(){
alert("working");
list.splice(i, 1);
--number_of_items;
makelist();
}
list_element.appendChild(list_item);
}
}
</script>
<body>
Todo: <input type="text" id="todo">
<input type="button" value="Submit" onclick="makelist()" />
</body>
</html>
The problem is, the list_item onclick function never activates. Why?
I apologize in advance for any problems with the way I stated my question.
http://jsbin.com/wicopu/1/edit
use onclick instead of onClick...
or even better ... use event listeners
Here is my code for my current todo list.
<html>
<head>
<title>ToDo</title>
</head>
<body>
<script>
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
var textnode = document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
}
</script>
<p id="do"> </p>
<input type='text' id='input'/>
<input type='button' onclick='addText()' value='Add To List'/>
</body>
</html>
It works to add objects but I have no idea what the javascript is to remove objects?
I wonder if someone could help me with a remove script like a X mark on the side of a new added object or something just to remove 1 after you add it,
Cheers
I think I found a solution to your problem. Check my fiddle:
http://jsfiddle.net/Kq4NF/
var c = 1;
function addText(){
var input = document.getElementById('input').value;
var node = document.createElement("P");
node.setAttribute('id', 'anchor'+c);
var textnode = document.createTextNode(input);
node.appendChild(textnode);
var removenode = document.createElement("input");
removenode.setAttribute('type', 'button');
removenode.setAttribute('value', 'X');
removenode.setAttribute("onclick", "removeText('anchor"+c+"')");
node.appendChild(removenode);
c++;
document.getElementById('do').appendChild(node);
}
function removeText(item){
var child=document.getElementById(item);
document.getElementById('do').removeChild(child);
}
Good luck!
var list = document.getElementById("do");
list.removeChild(list.childNodes[0]);
list - represents the p tag with ID do
list.ChildNodes - list of child elements appended to your p tag with ID as do.
list.ChildNodes[0] - represents the first child appended to the list, where 0 is the index.
To remove a specific element, either represent the is as index or point directly the element like
var list = document.getElementById("do");
var node = document.createElement("P");
var textnode = document.createTextNode(input);
textnode.id = "do1"; // Add id to the child element
node.appendChild(textnode);
document.getElementById('do').appendChild(node);
// This is to remove it using ID
list.removeChild(document.getElementById("do1"));
Hope you can understand.
I am new to javascript and I'm struggling with the following code that will be in a form for registration of multiple candidates.
It creates 2 dependant select boxes (country and area) for each candidate.
Clicking the button 'Add Candidate' once allows the dependant boxes to work fine but clicking the button again stops it working. Accessing the selected values from the form when there is more than one candidate is also impossible as they will overwrite each other.
I have tried creating the select names as arrays using a count variable which I increment each time the ff function is called but I can't get it to work.
All help will be much appreciated!
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<title>Select Populate Test</title>
<script>
var UnitedStates = new Array();
UnitedStates[0] = "Texas";
UnitedStates[1] = "California";
UnitedStates[2] = "Arizona";
UnitedStates[3] = "Nevada";
UnitedStates[4] = "Florida";
var UnitedKingdom = new Array();
UnitedKingdom[0] = "Surrey";
UnitedKingdom[1] = "Kent";
UnitedKingdom[2] = "Dorset";
UnitedKingdom[3] = "Hampshire";
function populateDropdown(arry)
{
document.myForm.stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
document.myForm.stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
function updateDropdown(str)
{
var stateArray
var selectedCountry;
var countryDropdown = document.myForm.countrySelect;
for (var i = 0; i < countryDropdown.options.length; i++)
{
if (countryDropdown.options[i].selected)
{
selectedCountry = countryDropdown.options[i].value;
}
}
if (selectedCountry == 1)
{
stateArray = UnitedStates;
populateDropdown(stateArray);
}
if (selectedCountry == 2)
{
stateArray = UnitedKingdom;
populateDropdown(stateArray);
}
}
counter = 0;
function ff()
{
counter++;
var box = document.getElementById("details"+counter);
var cselectBox = document.createElement("Select");
cselectBox.name="countrySelect";
cselectBox.onchange = function()
{
updateDropdown();
}
var option1 = document.createElement("OPTION");
option1.text="United States";
option1.value=1;
cselectBox.options.add(option1);
var option2 = document.createElement("OPTION");
option2.text="United Kingdom";
option2.value=2;
cselectBox.options.add(option2);
document.getElementById("details"+counter).innerHTML+="</p><p>"+counter+". Candidate Country";
box.appendChild(cselectBox);
var box2 = document.getElementById("detailsx"+counter);
var ccselectBox = document.createElement("Select");
ccselectBox.name="stateSelect";
document.getElementById("detailsx"+counter).innerHTML+="</p><p>"+counter+". Candidate City";
box2.appendChild(ccselectBox);
}
</script>
</head>
<body>
<form name="myForm" >
<input type="button" value="Add Candidate" onClick="ff(); populateDropdown(UnitedStates);"">
<!--- Note: 6 Candidates will be the maximum. -->
<div id="details1"><b></b></div>
<div id="detailsx1"><b></b></div>
<div id="details2"><b></b></div>
<div id="detailsx2"><b></b></div>
<div id="details3"><b></b></div>
<div id="detailsx3"><b></b></div>
<div id="details4"><b></b></div>
<div id="detailsx4"><b></b></div>
<div id="details5"><b></b></div>
<div id="detailsx5"><b></b></div>
<div id="details6"><b></b></div>
<div id="detailsx6"><b></b></div>
</form>
</body>
</html>
There are multiple problems here. We'll tackle the one you're dealing with first.
When you name multiple controls with the same name, like stateSelect, you'll get the first one each time you try to reference it. If you instead set the id to 'stateSelect' + counter, you'll get a unique id, which you can then retrieve with document.getElementById(). So in the function to populate the dropdown would look like this:
function populateDropdown(arry)
{
var stateSelect = document.getElementById('stateSelect'+counter);
stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
here is the fiddle I used to verify those changes.
You'll also need to add an event to each country dropdown to repopulate the state dropdown when it changes, and the structure needs a little work for that. If you're not opposed to frameworks, knockout would make this incredibly simple to run.
Here is the fiddle with everything working correctly and comments added at key changes
Update: Added link to the fiddle(s)
I'm trying to change a paragraph element by its ID in JavaScript to a h1.
My HTML
<body>
<p id="damn"> Hello </p>
</body>
My JavaScript
<script>
document.getElementByID("damn").<required missing code to change to h1>
</script>
The required result is
<body>
<h1 id="damn"> Hello </h1>
</body>
function changeTagName(el, newTagName) {
var n = document.createElement(newTagName);
var attr = el.attributes;
for (var i = 0, len = attr.length; i < len; ++i) {
n.setAttribute(attr[i].name, attr[i].value);
}
n.innerHTML = el.innerHTML;
el.parentNode.replaceChild(n, el);
}
changeTagName(document.getElementById('damn'), 'h1');
(fiddle)
var elem=document.getElementById("damn");
var parent=elem.parentNode;
var newElement=document.createElement("h1");
newElement.textContent=elem.textContent;
newElement.id=elem.id;
parent.replaceChild(newElement, elem);
That should do the trick. Play around with me.