Javascript quotest strings to array - javascript

I am trying to convert these strings, into elements of an array:
strings = "Antigua and Barbuda"
"Argentina"
"Armenia"
"Aruba"
"Australia"
"Austria"
"Azerbaijan"
"Bahamas"
"Bahrain"
"Bangladesh"
"Barbados"
"Belarus"
"Belize"
"Benin"
"Bermuda"
"Bhutan"
"Bolivia"
"Bosnia and Herzegovina"
"Botswana"
"Bouvet Island"
"Brazil"
"British Indian Ocean Territory"
"Brunei Darussalam"
"Bulgaria"
"Burkina Faso"
"Burundi"
"Cambodia"
"Cameroon"
"Canada"
"Cape Verde"
"Cayman Islands"
"Central African Republic"
"Chad"
"Chile"
"China"
"Christmas Island"
"Cocos (Keeling) Islands"
"Colombia"
"Comoros"
"Congo, The Democratic Republic of The"
"Cook Islands"
"Croatia"
"Cuba"
"Cyprus"
"Denmark"
"Djibouti"
"Dominica"
"Dominican Republic"
"Ecuador"
"Egypt"
"El Salvador"
"Equatorial Guinea"
"Eritrea"
"Estonia"
"Ethiopia"
"Falkland Islands (Malvinas)"
"Faroe Islands"
"Fiji"
"Finland"
"French Guiana"
"French Polynesia"
"French Southern Territories"
"Gabon"
"Gambia"
"Georgia"
"Ghana"
"Gibraltar"
"Greece"
"Greenland"
"Grenada"
"Guadeloupe"
"Guam"
"Guinea"
"Guinea-bissau"
"Guyana"
"Haiti"
"Heard Island and Mcdonald Islands"
"Holy See (Vatican City State)"
"Honduras"
"Hong Kong"
"Hungary"
"Iceland"
"India"
"Indonesia"
"Iran, Islamic Republic of"
"Iraq"
"Ireland"
"Jamaica"
"Japan"
"Jordan"
"Kazakhstan"
"Kenya"
"Kiribati"
"Korea, Democratic People's Republic of"
"Korea, Republic of"
"Kuwait"
"Kyrgyzstan"
"Lao People's Democratic Republic"
"Latvia"
"Lesotho"
"Liberia"
"Libyan Arab Jamahiriya"
"Liechtenstein"
"Lithuania"
"Luxembourg"
"Macao"
"Macedonia, The Former Yugoslav Republic of"
"Madagascar"
"Malawi"
"Malaysia"
"Maldives"
"Mali"
"Malta"
"Marshall Islands"
"Martinique"
"Mauritania"
"Mauritius"
"Mayotte"
"Micronesia, Federated States of"
"Moldova, Republic of"
"Monaco"
"Mongolia"
"Montserrat"
"Mozambique"
"Myanmar"
"Namibia"
"Nauru"
"Nepal"
"Netherlands Antilles"
"New Caledonia"
"New Zealand"
"Nicaragua"
"Niger"
"Nigeria"
"Niue"
"Norfolk Island"
"Northern Mariana Islands"
"Norway"
"Oman"
"Pakistan"
"Palau"
"Palestinian Territory"
"Papua New Guinea"
"Paraguay"
"Peru"
"Philippines"
"Pitcairn"
"Poland"
"Portugal"
"Puerto Rico"
"Qatar"
"Reunion"
"Romania"
"Russian Federation"
"Rwanda"
"Saint Helena"
"Saint Kitts and Nevis"
"Saint Lucia"
"Saint Pierre and Miquelon"
"Saint Vincent and The Grenadines"
"Samoa"
"San Marino"
"Sao Tome and Principe"
"Saudi Arabia"
"Senegal"
"Serbia and Montenegro"
"Seychelles"
"Sierra Leone"
"Singapore"
"Slovakia"
"Slovenia"
"Solomon Islands"
"Somalia"
"South Africa"
"South Georgia and The South Sandwich Islands"
"Spain"
"Sri Lanka"
"Sudan"
"Suriname"
"Svalbard and Jan Mayen"
"Swaziland"
"Syrian Arab Republic"
"Taiwan, Province of China"
"Tajikistan"
"Tanzania, United Republic of"
"Thailand"
"Timor-leste"
"Togo"
"Tokelau"
"Tonga"
"Trinidad and Tobago"
"Turkey"
"Turkmenistan"
"Turks and Caicos Islands"
"Tuvalu"
"Uganda"
"Ukraine"
"United Kingdom"
"United States Minor Outlying Islands"
"Uruguay"
"Uzbekistan"
"Vanuatu"
"Venezuela"
"Viet Nam"
"Virgin Islands, British"
"Virgin Islands, U.S."
"Wallis and Futuna"
"Western Sahara"
"Yemen"
"Zambia"
"Zimbabwe";
I have tried with the following function but it won't work:
function extractAllText(str){
const re = /"(.*?)"/g;
const result = [];
let current;
while (current = re.exec(str)) {
result.push(current.pop());
}
return result;
}
console.log(extractAllText(strings));
Any help?

This answer assumes that your string of quoted countries is actually defined as this:
var input = "\"Antigua and Barbuda\" \"Argentina\" \"Armenia\"";
That is, you have proper delimiting quotes around your string of countries. We can try splitting on:
" "
after first removing the leading and trailing double quote from the string. This would leave us with an array of unquoted countries.
var input = "\"Antigua and Barbuda\" \"Argentina\" \"Armenia\"";
input = input.replace(/^"(.*)"$/, "$1");
var countries = input.split("\" \"");
console.log(countries);

Once your strings variable is properly formed with a wrapping string, your code as written works fine.
const strings = '"Antigua and Barbuda" "Argentina" "Armenia" "Aruba" "Australia" "Austria" "Azerbaijan" "Bahamas" "Bahrain" "Bangladesh" "Barbados" "Belarus" "Belize" "Benin" "Bermuda" "Bhutan" "Bolivia" "Bosnia and Herzegovina" "Botswana" "Bouvet Island" "Brazil" "British Indian Ocean Territory" "Brunei Darussalam" "Bulgaria" "Burkina Faso" "Burundi" "Cambodia" "Cameroon" "Canada" "Cape Verde" "Cayman Islands" "Central African Republic" "Chad" "Chile" "China" "Christmas Island" "Cocos (Keeling) Islands" "Colombia" "Comoros" "Congo, The Democratic Republic of The" "Cook Islands" "Croatia" "Cuba" "Cyprus" "Denmark" "Djibouti" "Dominica" "Dominican Republic" "Ecuador" "Egypt" "El Salvador" "Equatorial Guinea" "Eritrea" "Estonia" "Ethiopia" "Falkland Islands (Malvinas)" "Faroe Islands" "Fiji" "Finland" "French Guiana" "French Polynesia" "French Southern Territories" "Gabon" "Gambia" "Georgia" "Ghana" "Gibraltar" "Greece" "Greenland" "Grenada" "Guadeloupe" "Guam" "Guinea" "Guinea-bissau" "Guyana" "Haiti" "Heard Island and Mcdonald Islands" "Holy See (Vatican City State)" "Honduras" "Hong Kong" "Hungary" "Iceland" "India" "Indonesia" "Iran, Islamic Republic of" "Iraq" "Ireland" "Jamaica" "Japan" "Jordan" "Kazakhstan" "Kenya" "Kiribati" "Korea, Democratic People\'s Republic of" "Korea, Republic of" "Kuwait" "Kyrgyzstan" "Lao People\'s Democratic Republic" "Latvia" "Lesotho" "Liberia" "Libyan Arab Jamahiriya" "Liechtenstein" "Lithuania" "Luxembourg" "Macao" "Macedonia, The Former Yugoslav Republic of" "Madagascar" "Malawi" "Malaysia" "Maldives" "Mali" "Malta" "Marshall Islands" "Martinique" "Mauritania" "Mauritius" "Mayotte" "Micronesia, Federated States of" "Moldova, Republic of" "Monaco" "Mongolia" "Montserrat" "Mozambique" "Myanmar" "Namibia" "Nauru" "Nepal" "Netherlands Antilles" "New Caledonia" "New Zealand" "Nicaragua" "Niger" "Nigeria" "Niue" "Norfolk Island" "Northern Mariana Islands" "Norway" "Oman" "Pakistan" "Palau" "Palestinian Territory" "Papua New Guinea" "Paraguay" "Peru" "Philippines" "Pitcairn" "Poland" "Portugal" "Puerto Rico" "Qatar" "Reunion" "Romania" "Russian Federation" "Rwanda" "Saint Helena" "Saint Kitts and Nevis" "Saint Lucia" "Saint Pierre and Miquelon" "Saint Vincent and The Grenadines" "Samoa" "San Marino" "Sao Tome and Principe" "Saudi Arabia" "Senegal" "Serbia and Montenegro" "Seychelles" "Sierra Leone" "Singapore" "Slovakia" "Slovenia" "Solomon Islands" "Somalia" "South Africa" "South Georgia and The South Sandwich Islands" "Spain" "Sri Lanka" "Sudan" "Suriname" "Svalbard and Jan Mayen" "Swaziland" "Syrian Arab Republic" "Taiwan, Province of China" "Tajikistan" "Tanzania, United Republic of" "Thailand" "Timor-leste" "Togo" "Tokelau" "Tonga" "Trinidad and Tobago" "Turkey" "Turkmenistan" "Turks and Caicos Islands" "Tuvalu" "Uganda" "Ukraine" "United Kingdom" "United States Minor Outlying Islands" "Uruguay" "Uzbekistan" "Vanuatu" "Venezuela" "Viet Nam" "Virgin Islands, British" "Virgin Islands, U.S." "Wallis and Futuna" "Western Sahara" "Yemen" "Zambia" "Zimbabwe"';
function extractAllText(str){
const re = /"(.*?)"/g;
const result = [];
let current;
while (current = re.exec(str)) {
result.push(current.pop());
}
return result;
}
console.log(extractAllText(strings));
All I did was use single quotes to wrap the list and then escape any single quotes internal to the content (for instance "Lao People's Democratic Republic" has to become "Lao People\'s Democratic Republic". Otherwise, it seems to work fine.

Related

How to trigger alert on click OR press of enter button

I am playing with W3School's autocomplete and I set it to alert when an item from the dropdown autocomplete menu is clicked, but now I want to have the same functionality for when a user hits enter, but only if the user input matches a country exactly (case insensitive). They should not be able to trigger the alert with enter if they partially typed a country name.
I have tried setting multiple event listeners, as well as using one to call two different functions, but I am not understanding the logic behind what I'm trying to complete.
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) {
return false;
}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if ((arr[i].toUpperCase()).includes(val.toUpperCase())) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
b.innerHTML += arr[i];
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
if (arr[i].toUpperCase() == val.toUpperCase()) {
closeAllLists();
}
// if (e.keyCode == 13 && acList === null && document.getElementById("inputField").value.length != 0)
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
alert('clicked');
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function(e) {
closeAllLists(e.target);
});
}
var countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Anguilla", "Antigua & Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central Arfrican Republic", "Chad", "Chile", "China", "Colombia", "Congo", "Cook Islands", "Costa Rica", "Cote D Ivoire", "Croatia", "Cuba", "Curacao", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Polynesia", "French West Indies", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauro", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "North Korea", "Norway", "Oman", "Pakistan", "Palau", "Palestine", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda", "Saint Pierre & Miquelon", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Korea", "South Sudan", "Spain", "Sri Lanka", "St Kitts & Nevis", "St Lucia", "St Vincent", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor L'Este", "Togo", "Tonga", "Trinidad & Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks & Caicos", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States of America", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Virgin Islands (US)", "Yemen", "Zambia", "Zimbabwe"];
/*initiate the autocomplete function on the "inputField" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("inputField"), countries);
window.onload = function() {
document.getElementById("inputField").focus();
};
.autocomplete-items {
background-color: black;
color: white;
width: 27%;
}
<form id="form" autocomplete="off" action="/action_page.php">
<div class="form-group autocomplete d-inline-flex align-items-center mt-3">
<label for="form-control" class="seasonsLabel me-3"></label>
<input type="text" class="form-control" id="inputField" required>
</div>
</form>
Trivial to add
I must comment that the code is another example of why I never recommend w3schools. It is suboptimal. In any case here is what you need added without changing the other code
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (countries.includes(capitalize(this.value))) alert("Found")
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) {
return false;
}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if ((arr[i].toUpperCase()).includes(val.toUpperCase())) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
b.innerHTML += arr[i];
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
if (arr[i].toUpperCase() == val.toUpperCase()) {
closeAllLists();
}
// if (e.keyCode == 13 && acList === null && document.getElementById("inputField").value.length != 0)
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
alert('clicked');
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (countries.includes(capitalize(this.value))) alert("Found")
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function(e) {
closeAllLists(e.target);
});
}
var countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Anguilla", "Antigua & Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central Arfrican Republic", "Chad", "Chile", "China", "Colombia", "Congo", "Cook Islands", "Costa Rica", "Cote D Ivoire", "Croatia", "Cuba", "Curacao", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Polynesia", "French West Indies", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauro", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "North Korea", "Norway", "Oman", "Pakistan", "Palau", "Palestine", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda", "Saint Pierre & Miquelon", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Korea", "South Sudan", "Spain", "Sri Lanka", "St Kitts & Nevis", "St Lucia", "St Vincent", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor L'Este", "Togo", "Tonga", "Trinidad & Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks & Caicos", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States of America", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Virgin Islands (US)", "Yemen", "Zambia", "Zimbabwe"];
/*initiate the autocomplete function on the "inputField" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("inputField"), countries);
window.onload = function() {
document.getElementById("inputField").focus();
};
.autocomplete-items {
background-color: black;
color: white;
width: 27%;
}
<form id="form" autocomplete="off" action="/action_page.php">
<div class="form-group autocomplete d-inline-flex align-items-center mt-3">
<label for="form-control" class="seasonsLabel me-3"></label>
<input type="text" class="form-control" id="inputField" name="inputField" required><input type="submit" />
</div>
</form>
use keypress for enter button.
use click for mouse click.
var input = document.getElementById("myInput");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
<h3>Trigger Button Click on Enter</h3>
<p>Press the "Enter" key inside the input field to trigger the button.</p>
<input id="myInput" value="Some text..">
<button id="myBtn" onclick="javascript:alert('Hello World!')">Button</button>

Access object value by key using Javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have the following object called data, how can I access the value for key name using Javascript
const data = {
"bar2": {
"address": "138/140 Gouger St, Adelaide SA 5000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "Disco Mexico, blends party vibes with fuss-free Mexican food in a small-bar setting.",
"imgURLs": [
"https://url",
"https://url"
],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https://firebasestorage.googleapis.com/v0/b/vipeeps-2018.appspot.com/o/venueImages%2FDisco_Mex_o.jpg?alt=media&token=60d76240-221c-415c-8d0d-7324d95a30ba"
}
}
const data = {
"bar2": {
"address": "138/140 Gouger St, Adelaide SA 5000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "Disco Mexico, blends party vibes with fuss-free Mexican food in a small-bar setting.",
"imgURLs": [
"https://url",
"https://url"
],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https://firebasestorage.googleapis.com/v0/b/vipeeps-2018.appspot.com/o/venueImages%2FDisco_Mex_o.jpg?alt=media&token=60d76240-221c-415c-8d0d-7324d95a30ba"
}
}
console.log(data.bar2.name)
Access the property how you would any other - data.bar2.name:
const data = {
"bar2": {
"address": "138/140 Gouger St, Adelaide SA 5000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "Disco Mexico, blends party vibes with fuss-free Mexican food in a small-bar setting.",
"imgURLs": [
"https://url",
"https://url"
],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https://firebasestorage.googleapis.com/v0/b/vipeeps-2018.appspot.com/o/venueImages%2FDisco_Mex_o.jpg?alt=media&token=60d76240-221c-415c-8d0d-7324d95a30ba"
}
};
const name = data.bar2.name;
console.lo(name);
You can use . notation like data.bar2.name, or index notation like data['bar2']['name']

How to replace letters in string to dashes but not spaces

I am creating hangman and with this code I replace the content in string with dashes, but some strings are two words -- "hello world" -- which the output is - - - - - - - - - - - 11 characters instead of ten. How do I avoid replacing the space?
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++){
replaceWithDash[i] = "_";
}
console.log(randomPick);
console.log(replaceWithDash);
}
beginGame();
While you're looping over your letters, you'll want to check whether or not the target letter is a space or not. If it's not a space, replace it with a dash. If it is a space, however, you should replace it with a space instead.
Note that considering you're making use of the second array replaceWithDash rather than simply replacing the letters, you'll need to explicitly state that the letter in the new array should contain a space, rather than simply only running the logic when there is not a space. As such, the else is required in the following (or else you'd end up with undefined indexes):
for (i = 0; i < randomPick.length; i++) {
if (randomPick[i] !== " ") {
replaceWithDash[i] = "_";
}
else {
replaceWithDash[i] = " ";
}
}
This can be seen in the following:
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"
];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++) {
if (randomPick[i] !== " ") {
replaceWithDash[i] = "_";
}
else {
replaceWithDash[i] = " ";
}
}
console.log(randomPick);
console.log(replaceWithDash);
}
beginGame();
Hope this helps! :)
To answer your question, basically you need to check if the value you are inserting into the array is a space or not. If you want to do something different when it is a space, you can add an else statement to do so. Here you will just iterate over that element of the array and then use filter_array to clean it up.
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++){
if(randomPick.charAt(i-1) != " "){
replaceWithDash[i] = "_";
}
}
console.log(randomPick);
console.log(filter_array(replaceWithDash));
}
beginGame();
function filter_array(test_array) {
var index = -1,
arr_length = test_array ? test_array.length : 0,
resIndex = -1,
result = [];
while (++index < arr_length) {
var value = test_array[index];
if (value) {
result[++resIndex] = value;
}
}
return result;
}

Salesforce Dependent picklist State and Country

I have got a solution for Salesforce Dependent Picklist values for Salesforce Site. As the Dependency is not publicly available for site I have found a solution using javascript and the country and state list are as per published by Salesforce on Feb'16 Edition. The code snippet is added below.
<!--- Include required libraries --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" />
<script src="/soap/ajax/36.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/36.0/apex.js" type="text/javascript"></script>
<script src="../static/102010/js/picklist.js"></script>
<script type="text/javascript">
var country_arr = new Array("American Samoa", "Anguilla", "Antigua and Barbuda", "Argentina", "Aruba", "Australia", "Austria", "Bahamas", "Bangladesh", "Barbados", "Belgium", "Belize", "Bermuda", "Bolivia", "Brazil", "Brunei Darussalam", "Cambodia", "Canada", "Cayman Islands", "Chile", "China", "Colombia", "Cook Islands", "Costa Rica", "Cyprus", "Denmark", "Dominica", "Dominican Republic", "Ecuador", "El Salvador", "Faroe Islands", "Finland", "France", "French Guiana", "French Polynesia", "Germany", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guyana", "Haiti", "Honduras", "Hong Kong", "India", "Indonesia", "Ireland", "Italy", "Jamaica", "Japan", "Laos", "Liechtenstein", "Macao", "Malaysia", "Maldives", "Martinique", "Mauritania", "Mexico", "Micronesia, Federated States Of", "Monaco", "Montserrat", "Myanmar", "Nepal", "Netherlands", "Norway", "Nepal", "New Zealand", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Portugal", "Paraguay", "Reunion", "Russian Federation", "Solomon Islands", "Sweden", "Suriname", "El Salvador", "Swaziland", "Turks and Caicos Islands", "Thailand", "Timor-Leste", "Trinidad and Tobago", "Taiwan", "United Kingdom", "United States", "Uruguay", "Saint Vincent and the Grenadines", "Venezuela", "Virgin Islands (British)", "Vietnam", "Vanuatu", "Samoa", "South Africa");
// States
var s_a = new Array();
s_a[0]="";
s_a[1]="";
s_a[2]="";
s_a[3]="";
s_a[4]="BUENOS AIRES|CATAMARCA|CHACO|Chubut|CORDOBA|CORRIENTES|ENTRE RIOS|FORMOSA|JUJUY|LA PAMPA|LA RIOJA|MENDOZA|MISIONES|NEUQUEN|RIO NEGRO|SALTA|SAN JUAN|SAN LUIS|SANTA CRUZ|SANTA FE|SANTIAGO DEL ESTERO|TIERRA DEL FUEGO|TUCUMAN";
s_a[5]="";
s_a[6]="AUSTRALIAN CAPITAL TERRITORY|NEW SOUTH WALES|NORTHERN TERRITORY|QUEENSLAND|SOUTH AUSTRALIA|TASMANIA|VICTORIA|WESTERN AUSTRALIA";
s_a[7]="Burgenland|Salzburg|Vienna|Vorarlberg";
s_a[8]="";
s_a[9]="";
s_a[10]="";
s_a[11]="ANTWERP|FLEMISH BRABANT|HAINAUT|LIMBURG|LUXEMBOURG|NAMUR|WALLOON BRABANT";
s_a[12]="";
s_a[13]="";
s_a[14]="";
s_a[15]="ACRE|ALAGOAS|AMAPA|AMAZONAS|BAHIA|CEARA|DISTRITO FEDERAL|ESPIRITO SANTO|GOIAS|MARANHAO|MATO GROSSO|MATO GROSSO DO SUL|MINAS GERAIS|PARA|PARAIBA|PARANA|PERNAMBUCO|PIAUI|RIO DE JANEIRO|RIO GRANDE DO NORTE|RIO GRANDE DO SUL|RONDONIA|RORAIMA|SANTA CATARINA|SAO PAULO|SERGIPE|TOCANTINS";
s_a[16]="";
s_a[17]="";
s_a[18]="ALBERTA|BRITISH COLUMBIA|MANITOBA|NEW BRUNSWICK|NEWFOUNDLAND|NORTHWEST TERRITORIES|NOVA SCOTIA|NUNAVUT|ONTARIO|PRINCE EDWARD ISLAND|QUEBEC|SASKATCHEWAN|YUKON TERRITORY";
s_a[19]="";
s_a[20]="AISEN|ANTOFAGASTA|VALPARAISO";
s_a[21]="Anhui|Beijing|Chongqing|Fujian|Gansu|Guangdong|Guizhou|Hainan|Hebei|Heilongjiang|Henan|Hubei|Hunan|Jiangsu|Jiangxi|Jilin|Liaoning|Qinghai|Shaanxi|Shandong|Shanghai|Shanxi|Sichuan|Tianjin|Xizang|Yunnan|Zhejiang";
s_a[22]="";
s_a[23]="";
s_a[24]="";
s_a[25]="";
s_a[26]="";
s_a[27]="";
s_a[28]="";
s_a[29]="";
s_a[30]="";
s_a[31]="";
s_a[32]="AHVENANMAA";
s_a[33]="";
s_a[34]="";
s_a[35]="";
s_a[36]="";
s_a[37]="";
s_a[38]="";
s_a[39]="";
s_a[40]="";
s_a[41]="";
s_a[42]="";
s_a[43]="";
s_a[44]="";
s_a[45]="";
s_a[46]="Andhra Pradesh|Arunachal Pradesh|Assam|BIHAR|Chandigarh|Chhattisgarh|Delhi|Goa|Gujarat|Haryana|Himachal Pradesh|Jharkhand|Karnataka|Kerala|Lakshadweep|Madhya Pradesh|Maharashtra|Manipur|Meghalaya|Mizoram|Nagaland|ORISSA|Puducherry|Punjab|Rajasthan|Sikkim|Tamil Nadu|Tripura|Uttar Pradesh|Uttarakhand|West Bengal";
s_a[47]="";
s_a[48]="";
s_a[49]="AGRIGENTO|ALESSANDRIA|ANCONA|AOSTA|AREZZO|ASCOLI PICENO|ASTI|AVELLINO|BARI|BELLUNO|BENEVENTO|BERGAMO|BIELLA|BOLOGNA|BOLZANO|BRESCIA|BRINDISI|CAGLIARI|CALTANISSETTA|CAMPOBASSO|CARBONIA-IGLESIAS|CASERTA|CATANIA|CATANZARO|CHIETI|COMO|COSENZA|CREMONA|CROTONE|CUNEO|ENNA|FERRARA|FOGGIA|FROSINONE|GORIZIA|GROSSETO|IMPERIA|ISERNIA|LA SPEZIA|LATINA|LECCE|LECCO|LIVORNO|LODI|LUCCA|MACERATA|MATERA|MEDIO CAMPIDANO|MESSINA|MODENA|NOVARA|NUORO|OGLIASTRA|OLBIA-TEMPIO|ORISTANO|PALERMO|PARMA|PAVIA|PERUGIA|PESARO E URBINO|PESCARA|PIACENZA|PISA|PISTOIA|PORDENONE|POTENZA|PRATO|RAGUSA|RAVENNA|RIETI|RIMINI|ROVIGO|SALERNO|SASSARI|SAVONA|SIENA|SONDRIO|TARANTO|TERAMO|TERNI|TRAPANI|TRENTO|TREVISO|TRIESTE|UDINE|VARESE|VERBANO-CUSIO-OSSOLA|VERCELLI|VERONA|VIBO VALENTIA|VICENZA|VITERBO";
s_a[50]="";
s_a[51]="AICHI|AKITA|AOMORI|CHIBA|EHIME|FUKUI|FUKUOKA|FUKUSHIMA|GIFU|HIROSHIMA|HOKKAIDO|HYOGO|Ibaraki|ISHIKAWA|IWATE|KAGAWA|KAGOSHIMA|KANAGAWA|KOCHI|KUMAMOTO|KYOTO|MIE|MIYAGI|MIYAZAKI|NAGANO|NAGASAKI|NARA|NIIGATA|OITA|OKAYAMA|OKINAWA|OSAKA|SAGA|SAITAMA|SHIGA|SHIMANE|SHIZUOKA|TOCHIGI|TOKUSHIMA|TOKYO|TOTTORI|TOYAMA|Wakayama|YAMAGATA|YAMAGUCHI|YAMANASHI";
s_a[52]="";
s_a[53]="";
s_a[54]="";
s_a[55]="";
s_a[56]="";
s_a[57]="";
s_a[58]="";
s_a[59]="AGUASCALIENTES|BAJA CALIFORNIA|BAJA CALIFORNIA SUR|CAMPECHE|CHIAPAS|CHIHUAHUA|COAHUILA|COLIMA|DISTRITO FEDERAL|DURANGO|GUANAJUATO|GUERRERO|HIDALGO|JALISCO|MICHOACAN|MORELOS|NAYARIT|NUEVO LEON|OAXACA|PUEBLA|QUERETARO|QUINTANA ROO|SAN LUIS POTOSI|SINALOA|SONORA|TABASCO|TAMAULIPAS|TLAXCALA|VERACRUZ|YUCATAN|ZACATECAS";
s_a[60]="";
s_a[61]="";
s_a[62]="";
s_a[63]="";
s_a[64]="";
s_a[65]="DRENTHE|FLEVOLAND|FRIESLAND|GELDERLAND|GRONINGEN|LIMBURG|NOORD-BRABANT|NOORD-HOLLAND|OVERIJSSEL|UTRECHT|ZEELAND|ZUID-HOLLAND";
s_a[66]="";
s_a[67]="";
s_a[68]="";
s_a[69]="";
s_a[70]="";
s_a[71]="";
s_a[72]="";
s_a[73]="";
s_a[74]="";
s_a[75]="";
s_a[76]="";
s_a[77]="";
s_a[78]="";
s_a[79]="";
s_a[80]="";
s_a[81]="BLEKINGE|DALARNA|GAVLEBORG|GOTLAND|HALLAND|JAMTLAND|JONKOPING|KALMAR|KRONOBERG|NORRBOTTEN|OREBRO|OSTERGOTLAND|SKANE|SODERMANLAND|STOCKHOLM|UPPSALA|VARMLAND|VASTERBOTTEN|VASTERNORRLAND|VASTMANLAND|VASTRA GOTALAND";
s_a[82]="";
s_a[83]="";
s_a[84]="";
s_a[85]="";
s_a[86]="";
s_a[87]="";
s_a[88]="";
s_a[89]="";
s_a[90]="";
s_a[91]="Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|District of Columbia|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Puerto Rico|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virgin Islands|Virginia|Washington|West Virginia|Wisconsin|Wyoming";
s_a[92]="";
s_a[93]="";
s_a[94]="";
s_a[95]="";
s_a[96]="";
s_a[97]="";
s_a[98]="";
s_a[99]="";
function populateStates( countryElementId, stateElementId ){
var selectedCountryIndex = document.getElementById( countryElementId ).selectedIndex;
//var stateElement = document.getElementById( stateElementId );
var stateElement = $("#page\\:MainForm\\:MainPageBlock\\:stateID");
stateElement.length=0; // Fixed by Julian Woods
stateElement.options[0] = new Option('Select State','');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i=0; i<state_arr.length; i++) {
stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
}
}
function createCountries(){
var country_sl="{!OpwrapAccBillCountry}";
var sel=$.inArray(country_sl, country_arr);
console.log("sel="+sel);
var countryElement = $("#countryID");
countryElement.find('option').remove().end().append('<option value="">--Select--</option>');
var part1='<option value=\"';
var part2='\">';
var part3='</option>';
for (var i=0; i<country_arr.length; i++) {
//countryElement.options[countryElement.length] = new Option(country_arr[i],country_arr[i]);
//console.log(country_arr[i]);
countryElement.append(part1+country_arr[i]+part2+country_arr[i]+part3);
}
countryElement.val(country_sl);
loadDependentPicklist();
var stateElement = $("#stateID");
var state_sl="{!OpwrapAccBillState}";
stateElement.val(state_sl);
}
function loadDependentPicklist(){
var countryElementId = $("#countryID");
var countryElement_hid = $("#page\\:MainForm\\:MainPageBlock\\:country_hid");
countryElement_hid.val(countryElementId.val());
var stateElement = $("#stateID");
stateElement.find('option').remove().end().append('<option value="">--Select--</option>');
var selectedCountryIndex=countryElementId.prop('selectedIndex');
var state_arr = s_a[selectedCountryIndex].split("|");
var part1='<option value=\"';
var part2='\">';
var part3='</option>';
for (var i=0; i<state_arr.length; i++) {
//stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
console.log("state_arr[i]="+state_arr[i]);
stateElement.append(part1+state_arr[i]+part2+state_arr[i]+part3);
}
}
function stateSel(){
var stateElement = $("#stateID");
var stateElement_hid=$("#page\\:MainForm\\:MainPageBlock\\:state_hid");
stateElement_hid.val(stateElement.val());
}
</script>
<script type="text/javascript">
$( document ).ready(function() {
console.log( "ready!" );
createCountries();
});
</script>

How to display JSON data in a select box using jQuery?

This is my JSON data:
{
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria"
}
How to display this JSON data in a selectlist?
Use $.each and iterate over all your elements. This should work:
$.each(jsonData, function(key, value)
{
$('<option></option>').val(key).text(value).appendTo('#yourSelectList');
});
Here's one way (takes fewer function calls):
var myJson = {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria"
};
$.each(myJson, function(key, val) {
$('#mySelect').append('<option value="' + key + '">' + val + '</option>');
});

Categories