2

I know how to operate this menu with a switch case routine, but I want to change my switch case to an object literal.

Part A knows how to get the onchange value and open a window. Part B knows how to find the value in a name:value pair in an object, but only if it's given a hard-coded name to match a value to. I have to combine Part A and Part B's capabilities. Since Part A and Part B both work independently of each other, it should be a simple matter to combine them, but I've been at it four days and I don't know how.

PART A: This select menu had the hard-coded links in the value attributes replaced with values which are used as names in an object. As is, this opens tabs as it should, but I want to get the right corresponding value of the link from the object called "lynk" in Part B.

<select id="sed">
    <option value="" selected>Select:</option>
    <option value="prev" >PREV</option>
    <option value="next">NEXT</option>
    <option value="home">home</option>
    <option value="gimme">contribute</option>
</select>

<script>
document.getElementById('sed').addEventListener ('change', valuu);

function valuu() {
ddd = document.getElementById("sed").value;
window.open(ddd, '_self');
}
</script>

PART B: This script is from an online example of a way to get the corresponding value from an object. It returns the correct link as a string if pasted into the console. The correct answer is hard-coded as 'gimme' in the last line of the script. I have to replace 'gimme' with code which gets the onchange value from the select option values and looks up the corresponding link in the object.

<script>
/*Works when pasted into console*/
function foo(bar) {
  var lynk = {
    'default': (''),
    'next': ('nextly.html'),
    'prev': ('previous.html'),
    'gimme': ('http://patreonx.com/bxaxly'),
    'home': ('index.html')
  };
  return lynk[bar];
}
foo('gimme');
</script>
Luther
  • 514
  • 4
  • 17

1 Answers1

1

This should make it dynamic.

function valuu() {
   ddd = document.getElementById("sed").value;
   window.open(foo(ddd), '_self');
}

You can do all this in one function like,

document.getElementById('sed').addEventListener ('change', function(e){
   var lynk = {
    'default': (''),
    'next': ('nextly.html'),
    'prev': ('previous.html'),
    'gimme': ('http://patreon.com/bearly'),
    'home': ('index.html')
   };
   window.open(lynk[e.target.value]);
});
Robin C Samuel
  • 1,215
  • 15
  • 33
  • Part A works, Part B works. I need to make them work together. – Luther Aug 07 '17 at 05:58
  • Please see the updated answer, the second code snippet. – Robin C Samuel Aug 07 '17 at 05:59
  • I made one change since your code was opening new windows, you left out the , '_self'); in the window.open line. When testing I changed to:window.open(lynk[e.target.value], '_self'); and it works great, thanks. – Luther Aug 07 '17 at 07:02