How to change HTML element without ID using Javascript? - javascript

I have a list with 250 countries in a HTML dropdown(for the sake of space I've only included 5 below):
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
Unfortunately I cannot edit the HTML element themselves, so I was wondering if there is a way to hide all of them except for Alaska (value=AK) using Javascript?
I currently have the following:
var country = document.querySelectorAll('select[name="postalCountry"] option');
var e;
for (e = 0; e < country.length; e++){
country[e].style.display = 'none';
}
country[2].style.display = 'initial';
But that gets a bit messy since I would have to go through a lot of countries to find out the index number of a country at the end of the list.
Any suggestion is greatly appreciated !

If you are only going to style them it's better to just use CSS:
select[name="postalCountry"] option
{
display: none;
}
select[name="postalCountry"] option[value="AK"]
{
display: initial;
}
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK" selected>Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option
Edit: added selected attribute so "Alaska" is selected by default initially.

Perhaps you can use the "value" of each option like follows
var country = document.querySelectorAll('select[name="postalCountry"] option');
for (var e = 0; e < country.length; e++){
if(country[e].value == "AK"){
country[e].style.display = 'initial';
document.getElementById("country_select").value = country[e].value;
} else {
country[e].style.display = 'none';
}
}
<select name="postalCountry" id="country_select" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>

Use JavaScript to make Alaska the first element of the select element, and set the select's value to "AK":
var sel = document.querySelector('select[name="postalCountry"]');
optAK = document.querySelector('option[value="AK"]');
sel.prepend(optAK);
sel.value = 'AK';
In CSS, hide all but the first option:
select[name="postalCountry"] option:not(:first-child) {
display: none;
}
That will overcome a bug in Chrome which shows the first option even if it's hidden.
Snippet:
var sel = document.querySelector('select[name="postalCountry"]');
optAK = document.querySelector('option[value="AK"]');
sel.prepend(optAK);
sel.value = 'AK';
select[name="postalCountry"] option:not(:first-child) {
display: none;
}
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>

Before we start: the aceppted answer is right and works well.
Here's an alternative approach showing the use of ES2015 spread operator (...) to iterate through a NodeList as an Array. This way we can use find method to target the right <option> without the use of formal loops and conditions.
Remeber that it only works in browsers that supports the spread operator (anything but IE). Also, note that it's a kind of syntax sugar which can be considered better or worst based on personal preferences but being a little slower than the traditional iterational approach, so use with sense.
let options = [...document.querySelectorAll('#country_select option')]
options.forEach(e => e.style.display = 'none')
let selected = options.find(e => e.value === 'AK')
selected.style.display = 'initial'
selected.selected = true
<select id="country_select">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>

Related

Make the selected option uppercase in a dropdown using vanilla JS

I need to make the text uppercase on the selected option only in a <select>. I found a working example using jQuery but I need to convert it to vanilla JS.
I've actually got it pretty close, when you choose an option, it makes the selected value uppercase. But when you choose another, it leaves the previous option uppercase also.
I can't figure out how to say "Capitalise all options EXCEPT the selected option, which I would like to be uppercase".
Any guidance will be appreciated.
Here is a working Fiddle of where I am so far.
How about just using CSS
* {
font-family: arial;
}
select option {
text-transform: capitalize;
}
select, select option:checked {
text-transform: uppercase;
}
<select name="title" id="title">
<option selected="" disabled="">Categories</option>
<option value="photo-galleries">Photo Galleries</option>
<option value="photography">photography</option>
<option value="romeo-juliet">Romeo & Juliet</option>
<option value="swan-lake">Swan Lake</option>
<option value="symmetries">Symmetries</option>
</select>
<select name="day" id="day">
<option selected="" disabled="">Day of the week</option>
<option value="monday">Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday">Wednesday</option>
<option value="thursday">Thursday</option>
<option value="friday">Friday</option>
<option value="saturday">Saturday</option>
<option value="sunday">Sunday</option>
</select>
Here's a javascript version as well
[].slice.call( document.querySelectorAll('option') ).forEach(ucfirst);
document.getElementById('title').addEventListener('change', fn, false);
document.getElementById('day').addEventListener('change', fn, false);
function ucfirst(el) {
el.innerHTML = el.innerHTML.charAt(0).toUpperCase() + el.innerHTML.slice(1).toLowerCase();
}
function fn() {
var options = this.getElementsByTagName('option');
var selected = options[this.selectedIndex];
[].slice.call(options).forEach(ucfirst);
selected.value = selected.innerHTML = selected.innerHTML.toUpperCase();
}
FIDDLE

Make multiple select menus jump to the first option

I've got 2 select menus. Example below.
How do I make both select menus jump to the first option when a button is clicked?
<select class="personlist">
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<select class="personlist">
<option value="Ten">Ten</option>
<option value="Eleven">Eleven</option>
</select>
I came across similar posts while googling. But was not able to get it right.
document.getElementsByClassName('personlist').value=[0];
getElementsByClassName returns an HTMLCollection object which is an array like object so you need to iterate over it and set the value
function reset() {
var els = document.getElementsByClassName('personlist');
for (var i = 0; i < els.length; i++) {
els[i].options[0].selected = true;
}
}
<select class="personlist">
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<select class="personlist">
<option value="Ten">Ten</option>
<option value="Eleven">Eleven</option>
</select>
<button onclick="reset()">d</button>
If you JQuery, you can use :
$('#select-a').click(function() {
$('select.personlist').each(function() {
$(this).find('option').first().prop('selected', true)
});
});

Changing values in dynamically generated html using Jquery

As the title says, I'm wondering if there's a way to change the value of html items that are generated by jquery. Here's the code that I currently have:
the javascript
<script type="text/javascript">
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
$(".row:first").clone(true).insertAfter(".row:last");
$('#dateDueMonth['+i+']').val(curentMonth + 1);
})
});
</script>
My thought here was that after the row was cloned, I could then change the dropdowns content based upon it's current name, but obviously that's not working, and I've been unable to find a way to "hook" into dynamic html content.
and the base html
<select id="months" name="months">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td><div id="showRows"><div class="row" id="row[]"><td class="td_alt"><select id="dateDueMonth[]" name="dateDueMonth[]" >
<option value="0">Select</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option selected value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="dateDueYear[]" name="dateDueYear[]">
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected value="2011">2011</option>
</select>
Now the generation of dynamic html and form submission works great. Gives me the data that I can use for my back end code. However having it so that I can increment the values in the various dropdowns as I see fit would make data entry by the folks using this page a whole lot easier, hence the issue.
To all that reply, thanks for your help with this jquery/JS noob.
EDIT: For this what I want to have is a form that can spawm multiples copies of the first line encased within the showRows div. When this is submitted, I want it to be able to collect that information in arrays for each select/input statement for the rows that are generated. For example if I selected two months, dateDueMonth, dateDueYear, and amount would be arrays in my form that would have two entries each. The current code does this, but by default it has the default elements for the dropdown menus set the same as the row of HTML that it is cloning.
Not sure what you want to do, but it should work like this
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
var arr;
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
arr=[$(".row:first").clone(true).insertAfter(".row:last")];
$('#dateDueMonth['+i+']').val(curentMonth + 1); //don't know why its here
arr[0].text("your value"); //apply the index you wanna change
})
});
Are you trying to achieve this kind of markup? Demo
<div id="showRows"><div class="row" id="row[0]"><select id="dateDueMonth[0]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[0]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
</div><div class="row" id="row[1]"><select id="dateDueMonth[1]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[1]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
...
This may be what you need. See my demo linked above.
for (var i = 1; i <= this.selectedIndex; i++) {
row = $(".row:first").clone(true)[0];
row.id = "row["+i+"]";
$(row).find("[id^='dateDueMonth']").attr("id","dateDueMonth["+i+"]").val((curentMonth + i) % 12 + 1);
$(row).find("[id^='dateDueYear']").attr("id","dateDueYear["+i+"]");
$(row).insertAfter(".row:last");
}
you cannot use ids as array in JavaScript. if you want, you have to put array index as well when you create element. or else just access the select element as bellow
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++) {
$(".row:first").clone(true).insertAfter(".row:last");
$('.row:last select').val(curentMonth + 1);
}
})
});
Working sample

Take out option from JavaScript

How to take out option value = 0 using JavaScript from below:
<select>
<option value=0>0</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
var select = document.getElementsByTagName("select")[0];
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value === "0") {
select.remove(i);
}
}
See a live example. Annoyingly the value is a string so you have to === compare to the string. And getting the select by tagName assuming it's the only select on the page is prone to failure
using
<select id="foo"> ... </select>
and
var select = document.getElementById("foo");
Would be better.
If you can use jQuery:
$('select > option[value=0]').remove();
Obviously you should use the id of the select instead of select or you will hit all select items on that page.

How to use javascript or jQuery to quickly select a preset of multi-select listbox items?

So say my page has a list of indexes '1,3,4,5,9,12' and a multi-select listbox with 12 items in it.
What's a fast way to use javascript to tell the listbox to multi-select all items at those indexes?
How would this be done using jQuery?
So for example if the user selects the 'caramel' preset associated with the 'candybar' listbox, it will select all the candy bars that have caramel... I think you get the idea.
This could do the trick:
<select id="select" multiple="multiple">
<option value="1">test 1</option>
<option value="2">test 2</option>
<option value="3">test 3</option>
<option value="4">test 4</option>
<option value="5">test 5</option>
<option value="6">test 6</option>
<option value="7">test 7</option>
<option value="8">test 8</option>
<option value="9">test 9</option>
<option value="10">test 10</option>
<option value="11">test 11</option>
<option value="12">test 12</option>
</select>
Javascript (jQuery):
indexes = [1,3,4,5,9,12]
$(document).ready(function(){
for(i=0; i<indexes.length; i++){
$('#select option:eq(' + (indexes[i]-1) + ')').attr('selected', 'selected');
}
});
Without jQuery:
window.onload = function(){
var indexes = [1,3,4,5,9,12];
var options = document.getElementById('select').options;
for(i=0; i<indexes.length; i++){
options[indexes[i]-1].selected = true;
}
}
The jquery select plugin has a selectOptions(value[, clear]) method which selects multiple values in a select box. But it takes the values as parameter instead of indexes.
You'd be better off setting classes on the option elements and addressing them that way, rather than by index:
<select id="my-select">
<option class="caramel">Twix</option>
<option>Mounds</option>
<option class="caramel">Milky Way</option>
<!-- ... -->
</select>
And then:
$("option.caramel", "#my-select").each(function () { this.selected = true });
Edit:
But if you really want to do it by index, you could do:
function selectOptionsByIndex(select, indexes) {
var i = 0;
select.children().each(function (j) { if (indexes[i] == j) { ++i; this.selected = true } });
}
selectOptionsByIndex($("#my-select"), [ 1, 3, 4, 5, 9, 12 ]);
(This depends on the list of supplied indexes being in ascending order.)

Categories

Resources