Implementation of a external Javascript file into html - javascript

I'm working on an assignment and one of the requirements is that I use the form tag to create a list of all countries and their country code, the file was provided as an external Javascript file in an object array, I've never used an external javascript file before so I'm not sure how to access the array and put it into the form.
Currently this is how I my form looks:
https://jsfiddle.net/so0z3m0v/
<head>
<script src="myscripts.js"></script>
</head>
<body>
<form id="register" action="http://formpost.azurewebsites.net/home/test" method="post">
Country * <select name="country" form="register">
<option value="CA">Canada</option><br><br>
</select><br><br>
<input type="submit" value="submit">
</body>

You can easily access the array of external javascript like an internal one.
And this is how you access and populate it to your select tag.
// To clear the select options
var select = document.getElementById("country");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i] = null;
}
// Iterate your array and set it as new option in the select
countries.forEach(function(elem, index){
select.options[index] = new Option(elem.name, elem.code);
});
Fiddle: https://jsfiddle.net/so0z3m0v/1/

What you have is an array of objects. To access an item (object) in the array, use its index. Then you can access a property of that object with dot notation
var x= countries[0].name; //Andorra
Below is a loop that will access every piece of info and place it into a select.
Note I have given your select element and id attribute.
var ddlCountry = document.getElementById('ddlCountry');
for(var i=0;i<countries.length;i++)
{
var country = countries[i];
var name=country.name;
var node = document.createElement("OPTION");
var textnode = document.createTextNode(name);
node.appendChild(textnode);
ddlCountry.appendChild(node);
}
Working Example here https://jsfiddle.net/so0z3m0v/2/

Aaaand to put it all together
<head>
<script src="myscripts.js"></script>
</head>
<body>
<form id="register" action="http://formpost.azurewebsites.net/home/test" method="post">
Country * <select name="country" form="register">
<option value="CA">Canada</option><br><br>
</select><br><br>
<input type="submit" value="submit">
<script type="text/javascript">
// put it down here because the HTML must be loaded completely
// make a generic option node
var option = document.createElement("option");
// find the "select" element by it's name
var select = document.getElementsByName("country")[0];
// over the whole countries array
for(var i = 0; i < countries.length;i++){
// make a copy of the generic option element build above
// and append it to the end of the select element
select.appendChild(option.cloneNode());
// set the value of the option element to the code
select.lastChild.value = countries[i].code;
// set the text to the name of the country
select.lastChild.textContent = countries[i].name;
}
</script>
</body>

Related

How do i display my js variable multiple times on a page

I'm collected a variable from the user, a person name, and storing that in a variable. When I hit next, I want to display the name on several different locations, including a dropdown list. I can get it to display the name outside the dropdown list, but only once.
Here is my html:
Collecting the info
<label>Student Name</label>
<input type="text" name="Student Name" id="kidNameInput">
My Next button
<input type="button" value="Next" class="button" onclick="nextForm()"></input>
Displaying the info
<label>What did the student do well?</label>
<div class="custom-select">
<select name="did-well">
<option value="0"><span class="kid-name"></span> did a great job at…</option>
<option value="1"><span class="kid-name"></span> did this…</option>
<option value="2"><span class="kid-name"></span> did something else…</option>
<option value="3"><span class="kid-name"></span> was good…</option>
</select>
Here is my javascript:
function nextForm() {
var nameInput = document.getElementById("kidNameInput").value;
document.getElementsByClassName("kid-name")[0].innerText = nameInput;
}
I don't know if it helps. but between forms, all I am doing is hiding them. not sure if I need to have them on a seperate html pages or not.
It looks like you're only displaying the variable on index 0 (this first index).
When you perform getElementsByClassName it returns an array like object.
So in your code where you have :
document.getElementsByClassName("kid-name")[0].innerText = nameInput;
You should instead try something like:
let arr = document.getElementsByClassName("kid-name");
for(let i=o; i<arr.length; i++) {
arr[i].innerText = nameInput
}
You're getting only the fist kid-name and not all of them. You need to cycle the result of the function getElementsByClassName
function nextForm() {
var nameInput = document.getElementById("kidNameInput").value;
var x = document.getElementsByClassName("kid-name");
for (var i = 0; i < x.length; i++) {
x[i].innerText = nameInput;
}
};

How to take user input and add to array in Javascript?

I've got a page im trying to develop which will take user input and then add it to an array and then take that array and make a select and option list out of it as such.
<!DOCTYPE>
<html>
<head>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
for (var i = 0; i < option_list.length; i++){
var opt = option_list[i];
var option = document.createElement("option");
var select = document.getElementById("select");
option.setAttribute("id", opt); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value(opt); // adds value to option list
select.appendChild(option); // Adds option to the list.
}
function add_option(name){
var name = document.getElementById("name").value;
name.push(option_list());
}
</script>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
</body>
</html>
The issue i am having is that it says when i try and input the information i get back-
Uncaught TypeError: option_list is not a function
at add_option (selectTest.html:19)
at HTMLInputElement.onclick (selectTest.html:25)
I am unsure what i am doing wrong and any help would be greatly appreciated.
You should push name into option_list array. The correct syntax is option_list.push(name);
function add_option(){
var name = document.getElementById("name").value;
option_list.push(name);
}
Pushing elements into array works the other way:
option_list.push(name);
http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
name.push(option_list());
As it says, option_list is not a function, and balanced parentheses after an identifier designate a function call in C family languages, so option_list() is not a valid expression.
Additionally, did you really intend to loop from zero up to the length of an empty array (which is equally zero)?
<!DOCTYPE>
<html>
<head>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
var select = document.getElementById("select");
function add_option(name){
var name = document.getElementById("name").value;
var option = document.createElement("option");
var label = document.createTextNode(name);
option.setAttribute("id", name); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value = name; // adds value to option list
option.appendChild(label);
select.appendChild(option); // Adds option to the list.
}
</script>
</body>
</html>

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

Updating Selectbox options

I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!
Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;
This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Categories