DaveYme
DaveYme

Reputation: 89

Javascript elements classes

I'll try be specific with what I'm trying to do and what I've tried so far.

I've been tasked with building a drop down menu with 200 countries. When a country is selected it will display what payment processors are available for your selected country.

I've got something working here ( only 3 countries ) http://davidstokes.com/1/payments/payments-dropdown.html I've also added the code to JS fiddle but for some reason doesn't work, Might be external files not loading correcting.

`function showDivIE() {
 document.getElementById('ireland').style.display = "block";
 document.getElementById('canada').style.display = "none";
 document.getElementById('uk').style.display = "none";
}
function showDivCA() {
document.getElementById('canada').style.display = "block";
document.getElementById('ireland').style.display = "none";
document.getElementById('uk').style.display = "none";
}
function showDivUK() {
document.getElementById('uk').style.display = "block";
document.getElementById('ireland').style.display = "none";
document.getElementById('canada').style.display = "none";
}'

https://jsfiddle.net/dave5000/0jwhwezq/

But you'll be able to see what code I have.

I want to change the document.getElementById selector to something else that lets me select multiple items. So when i need to hide country x/y/z i can enter then all in one area and not have to have multiple getElementsBy options.

Any help or suggestions would be great.

Upvotes: 0

Views: 61

Answers (2)

Dmitry Ponkin
Dmitry Ponkin

Reputation: 424

Add a common class to each of the blocks, i.e. for Ireland replace this:

<div id="ireland" style="display:none;">

with this:

<div id="ireland" style="display:none;" class="countryblock">

Given that all the blocks have a common class, you can use the following function:

function showDiv(id) {
    // $(selector) is a shortcut for jQuery(selector)
    $('.countryblock').hide(); // Hides every block with a table that is not currently hidden
    $('#'+id).show(); // Shows one particular block you want to show
}

And call it like that:

showDiv('uk');

Upvotes: 2

Martina
Martina

Reputation: 769

You can use 'getElementsByClassName' instead of 'getElementById'. Just add a class to each div e.g. country

document.getElementsByClassName('country')

You can then loop through each element and set the style.

Also there's getElementsByTagName if you prefer not adding a class, but then you have to filter the div with 'dropdown' class.

Upvotes: 1

Related Questions