Can't get the value of HTML select in AJAX response - javascript

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>

Related

Copy the content from a Sheets Cell to a Google Sites

I'm using the new Google Sites and I want to display a text box in it, but my goal is to show a text that is written in a cell in a Google sheet. So I can just edit the content in this sheet and it also change in the site.
I've written this code, but it is not working. Someone know what I can do?
function doGet() {
return HtmlService.createHtmlOutputFromFile('txtSheetToSite');
}
function getText(row, col) {
const ss = SpreadsheetApp.openById("here_goes_the_sheet_id");
const sheet = ss.getSheetByName("Orientacoes");
var row = row;
var col = col;
var value = sheet.getRange(row, col).getValue();
return value;
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function copyTxt(2,1){
var text = google.script.run.getText();
console.log(text);
document.getElementById("titulo").innerText = text;
}
copyTxt();
</script>
</head>
<body>
<div id="titulo"> </div>
</body>
</html>
The code is using google.script.run the wrong way. From https://developers.google.com/apps-script/guides/html/reference/run
Return
void — this method is asynchronous and does not return directly; however, the server-side function can can return a value to the client as a parameter passed to a success handler; also, return types are subject to the same restrictions as parameter types, except that a form element is not a legal return type
Replace
function copyTxt(2,1){
var text = google.script.run.getText();
console.log(text);
document.getElementById("titulo").innerText = text;
}
by
function copyTxt(){
google.script.run.withSuccessHandler(function(text){
console.log(text);
document.getElementById("titulo").innerText = text;
})
.getText(2,1);
}

The value of input element changes but not shown in the browser(s)?

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.

Google Sheets App Script Html onload not working

I'm using google sheets and I'm creating a document that will pull through employees that are out of the office. I have a menu option to remove employee data, and it opens the sidebar where I have an HTML form (Image of my project). I'm trying to have it generate a dropdown list of current employees on the list.
I've developed the code to pull through the data I need:
function removeAnyone() {
var html = HtmlService.createHtmlOutputFromFile('RemoveAnyone');
SpreadsheetApp.getUi()
.showSidebar(html);
}
function getList() {
var headerRows = 1;
var sheet = SpreadsheetApp.getActive().getSheetByName("Data");
var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, 1);
var arrayValues = range.getValues();
return arrayValues;
}
Now we move over to my html, where I am simply trying to load the dropdown list using a for loop in the header:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function addOption_list() {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
</script>
</head>
<body onload="addOption_list()">
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
I threw a div in the body and have the function changing the value to "test" at the start, this was just to check and see if the function was even being called, which it doesn't seem like it is.
I also tried using window.onload (as shown below), but that didn't get me anywhere either.:
window.onload = function {
document.getElementById("output").innerHTML = "test";
var options = google.script.run.getList();
for (var i = 0; i < options.length; ++i;) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
document.myForm.selectEmployee.options.add(optn);
}
}
Any guidance you can give me would be really appreciated!
google.script.run doesn't return values. When you want to return values from GAS, please use withSuccessHandler. And the data retrieved by getValues() is 2 dimensional array. So how about this modification?
Modified script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
google.script.run.withSuccessHandler(addOption_list).getList();
}
function addOption_list(options) {
document.getElementById("output").innerHTML = "test";
var select = document.getElementById('selectEmployee');
for ( var i in options) {
var optn = document.createElement('option');
optn.value = options[i][0];
optn.text = options[i][0];
select.appendChild(optn);
}
}
</script>
</head>
<body>
<form id="myForm" onsubmit="submitForm(this)">
<select id="selectEmployee">
<option>Choose an employee</option>
</select>
</form>
<div id="output"></div>
</body>
</html>
Reference :
google.script.run
getValues()
If I misunderstand your question, I'm sorry.

dropdown menu in javascript with adding new elements

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

createTextNode surrounding my select list in unwanted quotation marks

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);
}

Categories

Resources