Why are the dynamic options appearing so small? - javascript

I have a drop-down menu that I am dynamically adding options to (based on an AJAX call) on an onfocus event. For some reason, the first time I click on the box, the options appear condensed into a tiny box, but the second time it works just fine. Does anyone know what might be causing this phenomenon? (Note: Because it involves AJAX, I can't insert a fiddle that could simulate the error, but I will post the code itself)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Remove Class | IMS</title>
<link rel="stylesheet" type="text/css" href="../css/form.css"/>
</head>
<body>
<form>
<label for="class">Class:</label>
<select name="class" onfocus="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>
<hr/>
<button type="button" onclick="sendData()">Remove Class</button>
</form>
</body>
</html>
JS Code:
function genDrop(e, json) {
e.innerHTML = "";
var data = eval("({data: " + json + "})");
data = data.data;
for (var i = 0; i < data.length; i++) {
var option = data[i];
var o = document.createElement("option");
o.value = option.id;
o.innerHTML = option.name;
o.setAttribute("descript", option.descript);
o.style.width = "500px !important"
o.style.maxWidth = "200%";
e.appendChild(o);
}
}
function loadClasses(e) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
genDrop(e, http.responseText);
}
}
http.open("GET", "getclasses.php", true);
http.send();
}

Use onload instead of onfocus
<select name="class" onload="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>

Related

I cannot get CallBack / Javascript Api

Currently I am working on Translate App ( Via Yandex Api );
I have one problem that I could not understand...
If Someone would help me with it;
I'd be very happy.
So Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translator App</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!--jQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<section class="main">
<div class="header">
<h1>Welcome to Translator</h1>
<h2>Translate in English,Spanish,German,Turkish</h2>
<div class="language">
<div class="languageto">
<select class="firstlanguages" name="languages" id="langs">
<option value="en">English</option>
<option value="tr">Turkish</option>
<option value="de">German</option>
<option value="sp">Spanish</option>
</select>
</div>
<div class="tolanguage">
<select id="tolanguage" name="tolanguage">
<option value="toeng">Turkish</option>
<option value="totr">English</option>
<option value="tode">German</option>
<option value="tosp">Spanish</option>
</select>
</div>
</div>
<form id="translate-form">
<div class="translate">
<textarea class="firstmsj" name="word" placeholder="Maximum 500 Character" id="word" value="Nasılsın"></textarea>
<textarea class="secondmsj" name="message" disabled placeholder="Your Translate"></textarea>
</div>
<input class="translatebtn" type="submit" value="Translate">
</form>
</div>
</section>
<script src="js/translate.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And I have 2 Different JS files ;
First is App.js
eventListeners();
function eventListeners(){
let form = document.getElementById("translate-form");
form.addEventListener("submit", translateWord);
document.querySelector('.firstlanguages').onchange = function(){
//Arayüz işlemleri
}
}
let word = document.getElementById("word").value;
let lang = document.getElementById("langs").value;
const translate = new Translate(word,lang);
function translateWord(e){
translate.translateWord();
e.preventDefault();
}
Second javascript file is Translate.js
function Translate(word,language){
this.apikey = "trnsl.1.1.20200430T094119Z.fcb3cffaccaa7301.9f383b774f2aaea42d9be57e8799a3310f7074c1";
this.word = word;
this.language = language;
// XHR Object
this.xhr = new XMLHttpRequest();
}
Translate.prototype.translateWord = function(){
// Ajax Works
const endpoint = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${this.apikey}&text=${this.word}&lang=${this.language}`;
this.xhr.open("GET",endpoint);
this.xhr.onload = () =>{
if(this.xhr.status === 200){
console.log(this.xhr.responseText);
}else{
console.log("Hata");
}
}
this.xhr.send();
};
The mistake is , whenever I submit it;
The error message is ;
translate.js:28 GET https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20200430T094119Z.fcb3cffaccaa7301.9f383b774f2aaea42d9be57e8799a3310f7074c1&text=&lang=en 400 (Bad Request)
and when we see the link we cannot see ${this.word} is placed in my URL.
When I check the code after submit, also xhr.send() has been red...
this.xhr.send();
Except that everything works perfectly so far.
What could be the issue?
Thank you for your help!
You are getting an empty this.word because you are instantiating the Translate object out of the event handler:
const translate = new Translate(word,lang);
Initially, the input is empty, hence the blank space in this.word.
Solution: move the variables and instantiate inside the translateWord handler, so that they get updated on each search.
function translateWord(e){
let word = document.getElementById("word").value;
let lang = document.getElementById("langs").value;
const translate = new Translate(word,lang);
translate.translateWord();
e.preventDefault();
}
You will see, now it responds with 200 and the corresponding JSON data.

Chrome Extension- Take input from user and append to websites to open them in new tab

Hi i am creating a google chrome extension which will take input from the user and append that input to some particular urls i have in my javascript file and then open those websites in new tab. But its not working. i am pasting my extension popup.html and popup.js files here.
What am i doing wrong here?
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('Submit_btn').addEventListener('click', main);
function myFunction() {
var x = document.getElementById("frm1");
var text = x.elements[0].value;
if (text.localeCompare("One") == 0) {
var t = x.elements[1].value;
window.open("https://www.example.com/" + t);
window.open("https://www.example.com/" + t);
window.open("http://www.example.com/" + t);
} else if (text.localeCompare("Two") == 0) {
var t = x.elements[1].value;
window.open("https://www.example.com/" + t);
window.open("https://www.example.com/" + t);
window.open("https://www.example.com/" + t);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<form id="frm1">
<select name="List">
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<br><br> Query: <input type="text" name="fname" id="frm2"><br>
</form>
<button onclick="myFunction()" id="Submit_btn">Submit</button>
</body>
</html>

Add elements With innerHTML and onclick event

start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>challenge</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="selector.css" />
</head>
<body>
<header>
<h1>challenge 2 </h1>
<h2>Create an HTML select</h2>
</header>
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
<script src="selector.js"></script>
</body>
</html>
It is supposed to create a new <option> for my <select>, but it executes for 1s only, and then every thing disappears.
I tried to print i on the console but even on the console make the results and every thing was gone.
I am sure I did every thing good so what is the solution to make it work here?
The form is being submitted when you click the button.
onload event can be used to set the click event of the button.
Prevent the submit:
<form onsubmit="return false;">
JS:
window.onload = function() {
btn = document.getElementById('btn');
btn.onclick = function() {
start = document.forms[0].start;
end = document.forms[0].end;
result = document.getElementById('result');
selector = document.getElementById('selector');
i = start.value;
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
}
start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
'use strict';
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button type="button" value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
Use type="button" into your button.
as simple example on your code, just add parameter event, and prevent defaults event of form submit, you can also change the type of
<button value="generate" id="btn" type='button'> generate</button>
btn.onclick = (event)=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
event.preventDefault();
}
If you are trying to add a new option to the select use the "appendChild()" function:
var form = document.getElementByTagName("form")[0];
var btn = document.getElementById('btn');
//To avoid refresh the page when the form is submited.
form.addEventListener("click", function(e){e.preventDefault()},false);
btn.onclick = () => {
var result = document.getElementById('selector'),
var option= document.createElement("option");
option.innerHTML = "some text";
result.appendChild(option);
}
This wild add a new option in the select each time you click the add button

Break <option> items in loop

I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?
// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
// var xhr = new XMLHttpRequest();
// xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
// xhr.onreadystatechange = function() {
// if (xhr.readyState == 4 && xhr.status == 200) {
// var items = JSON.parse(xhr.responseText);
var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
var output = '<select>'
for (var i in items) {
output += '<option>' + items[i].address + '</option> <br>'
}
output += '</select>'
document.getElementById("replaceOption").innerHTML = output
// }
// }
// xhr.send();
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select>
<option id="addressList" value="select station" selected="selected">Select Station..</option>
<option id="replaceOption">0</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>
Append your options to the select element it's self. The reason why it's all on one line is because you're adding the new options inside an existing option rather than appending them after the existing option.
// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
for (var i in items) {
document.getElementById("mySelect").innerHTML += '<option>' + items[i].address + '</option>';
}
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select id="mySelect">
<option id="addressList" value="select station" selected="selected">Select Station..</option>
<option id="replaceOption">0</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>
document.addEventListener('DOMContentLoaded', function () {
let selectEl = document.getElementById('select-el');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (res) {
if (xhr.readyState == 4 && xhr.status == 200) {
let items = JSON.parse(xhr.responseText);
console.log(items);
items.forEach(function (item) {
let option = document.createElement('option');
option.value = item.name;
option.innerText = item.address;
selectEl.appendChild(option);
});
}
}
xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
xhr.send();
});
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body>
<div>
<div id="addressDropdown">
<form>
<select id="select-el"></select>
<br/>
<input type="submit" value="Go" id="sumbit" href="#" />
</form>
</div>
</div>
</body>
</html>
The problem is that you're inserting an extra <select> into the existing select. Here's what your output HTML looks like:
<form>
<select>
<option id="addressList" ...</option>
<option id="replaceOption">
<select>
<option>Smithfield North</option>
...
What you want to do instead is to append the options to the select box directly, rather than replacing the existing one. Note that the select box has an ID now instead of the option box. Here's the code that you need:
//GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var items = JSON.parse(xhr.responseText);
// get the select box by id
var addressList = document.getElementById("addressList")
// loop through all of the items and add an option to the list
for (var i in items) {
var option = document.createElement("option");
option.text = items[i].address;
option.value = i
addressList.add(option)
}
}
}
xhr.send();
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select id="addressList">
<option value="select station" selected="selected">Select Station..</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>

Storing User Input from Form into an Array - undefined is not a function (evaluating - error

I believe i'm missing something simple. I think i have the code
var textarea = document.getElementById("printArray");
firstLastNameInput.value = textarea.join("\n");
in the wrong spot, also i think i could be using the wrong variable.
Is my onClick calling the wrong function? Not really sure what I am doing wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<title>assign 8</title>
<meta charset="utf-8">
<style>
form {text-align:center;text-size:2em;}
</style>
<script>
var firstLastName = [];
var yearBirth = [];
var education = [];
var marital = [];
var firstLastNameInput = document.getElementById("firstLastName");
var yearBirthInput = document.getElementById("yearBirth");
var educationInput = document.getElementById("education");
var maritalInput = document.getElementById("marital");
function insert () {
firstLastName.push( firstLastNameInput.value );
yearBirth.push( yearBirthInput.value );
education.push( educationInput.value );
marital.push( maritalInput.value );
clearAndShow();
}
function clearAndShow () {
var textarea = document.getElementById("printArray");
firstLastNameInput.value = textarea.join("\n");
firstLastNameInput.value = "";
yearBirthInput.value = "";
educationInput.value = "";
maritalInput.value = "";
}
</script>
</head>
<body>
<form>
<input type="text" id="firstLastName" value="First & Last Name">
<br>
<input type="text" id="yearBirth" value="Year of Birth (ex: 1900)">
<br>
<select id="education" size="3">
<option>Education:</option>
<option>__________</option>
<option>High School Diploma</option>
<option>College Degree</option>
<option>Graduate Degree</option>
</select>
<br>
<select id="marital" size="2">
<option>Marital Status:</option>
<option>__________</option>
<option>Yes</option>
<option>No</option>
</select>
<br>
<input type="submit" value="Submit" onClick="clearAndShow()">
</form>
<textarea id="printArray"></textarea>
</body>
</html>
var textarea = document.getElementById("printArray");
is the reference to <textarea> node. So it has not method join()
You should get the value of it first:
var textarea = document.getElementById("printArray").value;
It will be string and it has not method join() too. In JavaScript you can simply:
firstLastNameInput.value = textarea + '\n';

Categories