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
Related
I wrote a live search field for a part of my form, when the suggestions come and user clicks on one of them, a js function (selectedService) is being called to get the innerHTML of the li which the user clicked on!
everything works perfectly when you look at the code in 'Inspect Element' of the browser, but not on the web page!
after the user clicks on the on the suggestion the value property of input element changes in the code but on the browser. the content of input field is still what the user is typing in it.
here's the code :
<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="UTF-8">
</head>
<body>
<input value="" id="services" placeholder="click or type plz..."/>
<ul id="suggestions">
</ul>
<style>
/* some styles */
</style>
<script>
var input = document.getElementById("services");
var suggestions = document.getElementById("suggestions");
input.oninput = function() {
var q = input.value;
if (q.length < 2) {
suggestions.setAttribute("style","display: none");
return;
}
var xhr2 = new XMLHttpRequest;
xhr2.open("GET", "theURL/service-request-handler.php?q="+q, true);
xhr2.onreadystatechange = function() {
if (xhr2.readyState == 4 && xhr2.status == 200)
{
var result = xhr2.responseText;
console.log("server response = "+result);
var json = JSON.parse(result);
showSuggestions(json);
}
};
xhr2.send();
};
function showSuggestions(json) {
suggestions.setAttribute("style","display: block");
var li_list = '';
var i = 0;
for (i=0; i<json.length; i++)
li_list += '<li id="'+i+'" onclick="selectedService('+i+')">'+json[i]+'</li>';
suggestions.innerHTML = li_list;
}
function selectedService(i) {
li_target = document.getElementById(i);
console.log(li_target.innerHTML);
// input.innerHTML = li_target.innerHTML;
input.setAttribute("value",li_target.innerHTML);
suggestions.setAttribute("style","display: none");
}
</script>
</body>
</html>
the result in the Inspect Element :
I'd appreciate any help or suggestions :)
input.value = li_target.innerHTML
You can set value property directly:
input.value=li_target.innerHTML;
Probably you are using firefox browser, you should use this to work in both, chrome and firefox.
input.value = li_target.innerHTML;
This happens because property and attributes are different.
Attributes are defined on the HTML markup but properties are defined on the DOM.
You can use jQuery UI for autocomplete search.
I'm trying to build a simple todo list. I would like to add a (x) to each item in the list. The list has two existing items, and the rest will be added from user input.
My current code can only add (x) to existing items. I followed the following tutorial, but i think the way it adds (x) to both existing items and new input items are redundant. (note it basically uses "var span = document.createElement("SPAN"); ..." twice.
Is there a way that I can append the (x) in the end to all li items in the document?
// Create a "close" button and append it to each list item
var allListItems = document.getElementsByTagName("li");
function appendClose(x){
var close = document.createElement("span");
var text = document.createTextNode("(\u00D7)");
close.appendChild(text);
return x.appendChild(close);
}
// Turn object into array.
const peopleArray = Object.keys(allListItems).map(i => allListItems[i]);
console.log(peopleArray);
peopleArray.map(appendClose);
// Create new list item after button click.
function createNewElement(){
var li = document.createElement("li"); // create <li>
var v_userInput = document.getElementById("myInput");
var content = document.createTextNode(v_userInput.value);
li.appendChild(content);
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = ""; //fresh the input box;
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Work to-do</title>
</head>
<body>
<h1> Work to-do </h1>
<div id="myDiv">
<input id="myInput" type="text" placeholder="New item..." maxlength="27">
<button id="enter" onclick="createNewElement()">Add</button>
</div>
<ul id="myUL">
<li>Gym</li>
<li>Food</li>
</ul>
</body>
<script type="text/javascript" src="7_todo.js"></script>
</html>
You just have to write one more line inside createNewElement() to do that:
appendClose(li);
Further, you should also prevent empty values being appended to todo-list by checking the length of input value. I've added an example of that.
// Create a "close" button and append it to each list item
var allListItems = document.getElementsByTagName("li");
function appendClose(x){
var close = document.createElement("span");
var text = document.createTextNode("(\u00D7)");
close.appendChild(text);
return x.appendChild(close);
}
// Turn object into array.
const peopleArray = Object.keys(allListItems).map(i => allListItems[i]);
// console.log(peopleArray);
peopleArray.map(appendClose);
// Create new list item after button click.
function createNewElement(){
var li = document.createElement("li"); // create <li>
var v_userInput = document.getElementById("myInput");
// Prevents empty task in todo list
if(v_userInput.value.length === 0) {
alert('Enter something!');
return ;
}
var content = document.createTextNode(v_userInput.value);
li.appendChild(content);
appendClose(li); // Edited here
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = ""; //fresh the input box;
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Work to-do</title>
</head>
<body>
<h1> Work to-do </h1>
<div id="myDiv">
<input id="myInput" type="text" placeholder="New item..." maxlength="27">
<button id="enter" onclick="createNewElement()">Add</button>
</div>
<ul id="myUL">
<li>Gym</li>
<li>Food</li>
</ul>
</body>
<script type="text/javascript" src="7_todo.js"></script>
</html>
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'm relatively new to JavaScript and I can't seem to figure out how to output text in a textfield in HTML. I've looked at many solutions and although I'm very close (I think I am), I still can't get it to function properly.
I'm trying to sort a series of numbers by separating them with "; " and wish to show the result in the bottom text field by ascending or descending order. The action is done by pressing the button to sort them.
When trying to debug it, it seems that the variables are being assigned their values as they should, but the variable "output" just won't show up in the "Sorted Numbers" textfield. My code is incomplete as I'm just trying to test this for an ascending order before I add in the descending order.
Here is my code...
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Sorting Numbers</title>
</head>
<body>
Enter Numbers Here: <input type = "text" id = "numInput"><br><br>
Select Option: <select id = "menu">
<option value = "ascending">Ascending</option>
<option value = "descending">Descending</option>
</select><br><br>
Sorted Numbers: <input type = "text" id = "numOut"><br><br>
<button onclick = "sortNums()">Sort Numbers</button>
<script type = "text/javascript">
function sortNums() {
var choice = document.getElementById("menu");
var numbers = document.getElementById("numInput").value;
var output = document.getElementById("numOut").value;
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
}
}
</script>
</body>
</html>
Because you never assigned output to it afterwards:
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
document.getElementById("numOut").value = output;
}
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);
}