I want to add a select list to my website using a button.
I need to use nodes because i need to be able to access it within the DOM so i can retrieve its value later on so I cant use innerHTML.
My problem is that createTextNode seems to surround my list in quotation marks and so it will not display. Can anyone help me out
<!doctype html>
<html>
<head>
<title> Pop Up </title>
<script>
function change()
{
var theDiv = document.getElementById("dropDownList");
var content = document.createTextNode("<select name='scrapbookID' id='scrapbookID'><option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option></select>");
theDiv.appendChild(content);
}
</script>
<style type = "text/css">
</style>
</head>
<body>
<div id = "signout">
Your are Currently signed in.<br />
Sign Out
<div id = "dropDownList">
<button onclick="change()">Add List</button>
</div>
</div>
</body>
What you need to have is .createElement() it creates a given element, where as createTextNode creates text node with given content.
function change()
{
var theDiv = document.getElementById("dropDownList");
var select = document.createElement('select');
select.name = 'scrapbookID';
select.id = 'scrapbookID';
select.innerHTML = "<option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option>"
theDiv.appendChild(select);
}
Demo: Fiddle
When you’re creating a text node, it’s treated as exactly that: text, not HTML. But it’s cleaner to just build the DOM properly!
function change() {
var theDiv = document.getElementById("dropDownList");
var selectBox = document.createElement("select");
selectBox.id = "scrapbookID";
selectBox.name = "scrapbookID";
var options = {
"15": "one",
"18": "two",
"20": "three",
"21": "four"
};
for(var x in options) {
if(options.hasOwnProperty(x)) {
var option = document.createElement("option");
option.value = x;
option.appendChild(document.createTextNode(options[x]));
selectBox.appendChild(option);
}
}
theDiv.appendChild(selectBox);
}
Related
I currently stumbled upon trouble with the inability to add a class to div/form elements via classList.add method.
The same very method works perfectly for other elements like input or button.
However, no magic happens with the div and the form.
Please, ignore that the JS code is linked externally within the HTML.
Here all that matters that these two lines don't work:
form.classList.add = "formList";
buttonWrapper.classList.add = "buttonContainer";
(function(){
function formCreation () {
//Here I add elements"
let container = document.createElement('div');
let form = document.createElement('form');
let input = document.createElement('input');
let buttonWrapper= document.createElement('div');
let buttonCreator = document.createElement('button');
let buttonRemover = document.createElement('button');
input.placeholder = 'Enter your new task';
buttonRemover.textContent = 'Delete'
buttonCreator.textContent = 'Add';
//Here I'm trying to add classess//
form.classList.add = "form";
//It won't work for the form'
buttonWrapper.classList.add = "buttonContainer";
//Neither it would work for the buttonWraper div"
input.classList.add('input');
buttonCreator.classList.add('creator');
buttonRemover.classList.add('remover')
container.append(form);
buttonWrapper.append(buttonCreator);
buttonWrapper.append(buttonRemover);
form.append(input);
form.append(buttonWrapper);
return {
form,
input,
buttonCreator,
};
}
document.addEventListener('DOMContentLoaded', function () {
let containerApp = document.getElementById('container');
let heading = createAppTitle('Things to be done');
let todoItem = formCreation();
let listItself = todoListCreator();
containerApp.append(heading);
containerApp.append(todoItem.form);
containerApp.append(listItself);
});
}());
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="container" class="container"></div>
<script src="index.js"></script>
</body>
</html>
I don't understand how this code would work on any element type.
The format:
form.classList.add = "formList";
buttonWrapper.classList.add = "buttonContainer";
is wrong.
Try
form.classList.add("formList");
buttonWrapper.classList.add("buttonContainer");
See MDN for info on using classList and its properties.
I am new just started a course on JS and wanted to have fun on an assignment but perhaps got a little ahead of myself. I decided to do a simple recreation of The Bridge of Death from Monty Python
I am trying to use JS in a HTML file to create a dropdown menu and then when a certain option is selected it changes the color of the paragraph elements.
I am unsure how to pull the values of the options created in the select form to style the element.
What I have now creates the dropdown but the options don't change anything
Sorry if this is super janky, I literally started a week ago.
Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = list.options[list.selectedIndex].values;
document.p.style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.onchange = "changeBackground(this)";
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I feel like there is a better way to create the select form. I could also use html to create it and then hide then reveal it in the q2_func.
Any suggestions on where I could go from here?
Some limitations based on the assignment: no seperate files for js or css, just use js to change the style (no jquery or ajax)
Also the "blue...no..." should lead to an alert but that isn't working either...
Thank you in advance!
-Kevin
Here's your code solution.
If you want to add onchange function you need to use setAttribute function to add onchange function on selectbox in q3_func().
You didn't defined any list veriable in changeBackground function that you want to use in that function event that you're getting colors parameter and you can use colors.options and colors.selectIndex
You can't use document.p directly because p is not defined as veriable or it's not a document but it's a part of document. You can use document.getElementsByTagName('p')[0] [0] indecate index of tags.
For example:
Your are using p tag 5 time in body [0] indecates first p tag and [1] indecates to 2nd.
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = colors.options[colors.selectedIndex].values;
document.getElementsByTagName('p')[0].style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.setAttribute("onchange", "changeBackground(this)");
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I hope you understand this.
I figured out the alert trigger!
Using the changes Abdul made I added the following code to the end of the changeBackground function:
var x = document.getElementById("colors").selectedIndex;
var y = document.getElementById("colors").options;
if (y[x].index === 4){
alert("Ahhhhgggg!!! .... *Death*");
};
It works completely now.
Thank you
Kevin
I am trying to create forms dynamically using javascript, but I struggled with creating radio buttons in the form properly. The problem is I can't display a label beside each radio button
here is the index.html file
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<form id="myform">
</form>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
and the custom.js file
document.body.onload = newElement;
function newElement() {
var form = document.getElementById("myform");
var questions = {
name : "q1",
qType : "radio",
qLabel : "Is your system is automated online advising?",
options : ["Yes", "No"]
}
var label = document.createElement("label");
var lblContent = document.createTextNode(questions["qLabel"]);
label.appendChild(lblContent);
form.appendChild(label);
switch(questions["qType"]) {
case "radio":
var input = [];
var option;
var optionContent;
for(var i = 0; i < questions["options"].length; i++) {
input[i] = document.createElement("input");
input[i].setAttribute("type", questions["qType"]);
input[i].setAttribute("name", questions["name"]);
option = document.createElement("label");
optionContent = document.createTextNode(questions["options"][i]);
option.appendChild(optionContent);
input[i].appendChild(option);
form.appendChild(input[i]);
}
break;
}
}
Replace the last two lines of the for loop with
form.appendChild(input[i]);
form.appendChild(option);
There are two steps on my code. First step a user fills some fields and then data is submitted by ajax to server. Ajax returns a HTML select input that user must choose a value. This is the second step.
The problem is, when I try to get the value of select in javascript, it shows me null.
The code I use to get select value works in normal situation. But when select is retrieved by ajax, this problem occurs.
Code to get select value
var e = document.getElementById("ordernum");
var num = e.options[e.selectedIndex].value;
Here's an example HTML file showing how to dynamically generate a select element and get the value back from it on its onchange event via event.target.value:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
const GameDifficulty = {
EASY:1,
MEDIUM:2,
HARD:3,
INSANE:4
};
function init(event) {
console.log(event);
var body = document.getElementById('body');
var select = document.createElement('select');
select.id = 'selDifficulty';
for (var diff in GameDifficulty) {
var option = document.createElement('option');
option.value = GameDifficulty[diff];
option.innerHTML = diff;
select.appendChild(option);
}
select.onchange = test;
body.appendChild(select);
console.log(body);
}
function test(event) {
console.log(event.target.value);
}
window.onload = init;
</script>
</head>
<body id="body">
</body>
</html>
I am new in javascript and in this moment I am trying to use "Basic DOM and JS". I am doing a dropdown menu, what gets his elements from an array. There is an input field, where you can add new items into the array.I also made a button to push and save the item into array and make the dropdown automatically with DOM.
My problem if you push the button, it makes always a new dropdown menu. Otherwise the array works good, but I need just one dropdown menu with the items of array. I think this problem comes out at listing with ul li too. Here is my whole code and thanks for helping
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
var menu = document.createElement("select");
document.body.appendChild(menu);
for(var i = 0; i<select.length; i++){
var option = document.createElement("option");
var text = document.createTextNode(select[i]);
option.appendChild(text);
menu.appendChild(option);
}
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
You are creating the select tag every time array() is invoked. So create select tag once and rest of the time create option tag when array() is invoked. Here is your solution.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
var selectIsCreated = false;
var menu;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
if(!selectIsCreated){
menu = document.createElement("select");
document.body.appendChild(menu);
selectIsCreated = true;
}
var option = document.createElement("option");
var text = document.createTextNode(select[select.length-1]);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
So Suman already answered your question, but in terms of simplifying the code or the approach, I think you could take a different approach by removing the use of the "select" array entirely. The array isn't necessary to add in the value to the select list, as you can get everything you need from the input element, so you just need to work on adding the option to the actual select DOM element.
Here is the desired functionality re-factored a bit with this in mind.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
function createSelect() {
select = document.createElement('select');
select.id = 'select';
document.body.appendChild(select);
return document.getElementById('select');
}
function addOption(){
var input = document.getElementById("input");
var value = input.value;
// This will attempt to grab the 'select' element, but if it finds
// that it doesn't exist (i.e. getElementById returns a "falsy" value)
// then it will return the value of the createSelect function.
// This could also be done with more explicit "if" statements
var menu = document.getElementById('select') || createSelect();
// The same effect could be achieved by running this code:
/*
var menu = document.getElementById('select');
// If the select element hasn't been created/added to the page yet,
// then the above call to getElementById will return a "falsy" value,
// i.e. a value that isn't a strict boolean type but JS will treat it
// as "false".
if (!menu) {
menu = createSelect();
}
*/
var option = document.createElement("option");
var text = document.createTextNode(value);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<!--
I've renamed the array() function since we don't even
have an array anymore
-->
<input onclick="addOption()" type="button" value="Add">
</body>
</html>
You can see this in action on this jsFiddle