0

I have a drop down field on my form. When I select a value from the drop down it immediately resets the focus to the top of the form.

To be clearer I have a drop down menu at the top of the screen and several input fields. The user would have to scroll down to the actual drop down field in order to select it. Once they select the value the page scrolls back to the top.

How can I keep the position the user selected on the form once a user selects a value from the drop down? [NOTE: It will not show up on stack overflow you would have to copy and paste the code and try it on your own browser].

I know it has to do with the code inside the HTML.

document.getElementById("locale").options[value].selected;
window.location.hash="country-select";

Because I keep getting an error: Uncaught TypeError: Cannot read property 'selected' of undefined

So far I have

    // creates the page dynamically
    function GetSelectedItem(){
          var option = document.getElementById("locale").value;
    }
 
<!doctype html>  
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>MyWebsite</title>
    <link rel="stylesheet" href="languageswitcher.css">
    <script>

  document.getElementById("locale").addEventListener('change', function(event) {
   var selected = event.target.options[ event.target.selectedIndex ].value 
   console.log(selected);
   window.location.hash = selected; 
  });
    </script>
  </head>

  <body>

    <header>

      <div id="country-select">
        <form action="" method = "get">
          <select id= "locale" name="locale">
            <option value="en_US">English(US)</option>
            <option value="en_GB">English(UK)</option>
            <option value="bg_BG">Bulgarian</option>
            <option value="cs_CS">Czech</option>
            <option value="da_DK">Danish</option>
            <option value="de_DE">German</option>
            <option value="ek_GR">Greek</option>
            <option value="es_ES">Spanish</option>
            <option value="et_ET">Estonian</option>
            <option value="fi_FI">Finnish</option>
            <option value="fr_FR">French</option>
            <option value="hu_HU">Hungarian</option>
            <option value="it_IT">Italian</option>
            <option value="lt_LT">Lithuanian</option>
            <option value="lv_LV">Latvian</option>
            <option value="nl_NL">Dutch</option>
            <option value="no_NO">Norwegian</option>
            <option value="pl_PL">Polish</option>
            <option value="pt_PT">Portugese</option>
            <option value="ro_RO">Romanian</option>
            <option value="sk_SK">Slovak</option>
            <option value="sl_SL">Slovenian</option>
            <option value="sv_SE">Swedish</option>
          </select>
          <input value="Select" type="submit"/>
        </form>
      </div>
    </header>
    <script src="jquery_1.5.min.js"></script>
    <script src="languageswitcher.js"></script>
  </body>
</html>

Thanks for your help everyone, I am just trying to self learn and so far it's going great but I've been stuck on this for around 2 weeks and I have no idea why that .selected won't work at all. Also if there is any other efficient way to do this code such as using arrays that would be nice to know as well. Thanks again

Giorgio
  • 41
  • 8
  • Use: selBox.options[selBox.selectedIndex].value where selBox is your drop-down box (locale, I think, in your case). You get an error because value doesn't have a Selected property. Because of the error the cursor loses focus and defaults to the top of the screen / page. – Tony Duffill Jun 23 '16 at 15:40
  • @TonyDuffill Thank you Tony, however, that fixed the error but it still didn't help fix my overall problem. For example, if I switch the language to Italian and hit "submit", the link changes perfectly fine but the select box goes all the way back to English(US) – Giorgio Jun 23 '16 at 15:45

3 Answers3

1

It's easier if you add an event listener to your select element:

document.getElementById("locale").addEventListener('change', function(event) {
  var selected = event.target.options[ event.target.selectedIndex ].value 
  console.log(selected);
  window.location.hash = selected; 
});

jsFiddle

Note: You wont see the hash change on jsfiddle but it changes. Check out the console log.

Edit: Try wrapping your code in this event which waits for the DOM tree to load before executing the code.

document.addEventListener("DOMContentLoaded", function(event) { 

  // creates the page dynamically
  function GetSelectedItem(){
    var option = document.getElementById("locale").value;
  }


  document.getElementById("locale").addEventListener('change', function(event) {
    var selected = event.target.options[ event.target.selectedIndex ].value 
    console.log(selected);
    window.location.hash = selected; 
  });
});

jsFiddle DOM wait

andybeli
  • 836
  • 7
  • 14
  • Thanks Andy but doing that I got another error saying... Uncaught TypeError: Cannot read property 'addEventListener' of null – Giorgio Jun 23 '16 at 16:07
  • 1
    This is because your are looking for the element before it exits in the DOM tree (you need to execture after it's ready) or because there is a small space between your ` – andybeli Jun 23 '16 at 16:31
  • That's all of my code. All of my Javascript code is inside of the header in the HTML file. – Giorgio Jun 23 '16 at 16:39
  • 1
    I updated my answer. btw you need to follow certain rules to upload code to jsfiddle (separate it, for html don't include the doctype, head elements, etc) – andybeli Jun 23 '16 at 17:09
  • Thanks so much Andy! The error isn't there anymore but my drop-down menu still isn't working like it's suppose to :( So what I'm trying to do is if I select Italian on the drop down menu, it will go to the italian path in the url, BUT once it does the drop down menu will switch back to the very first item on the drop down menu [English(US)] which I do not want, I want it to stay on Italian – Giorgio Jun 23 '16 at 17:16
  • https://jsfiddle.net/jjswhccd/ Here is another link for what I have, if you test it out and you switch it to a different language, the link on the end of the URL will change but the drop-down menu won't and it keeps switching back all the way to the top. – Giorgio Jun 23 '16 at 17:21
1

There are several problems:

  • you can clean up all those if-else statements with select-case. However, it doesn't appear you need any of that code at all because you can probably select the option you want without any of them.
  • the title element you put on all your options seems redundant. Since they just appear to signify the index, you can access them using the options[] array.
  • You never set the value of title in your JS code, so it's always undefined. Since title is never set, value is never set either. Because of that options[title] is undefined (which is the error you provided in bold).
  • You didn't post the code for languageswitcher.js, so we don't know what's going on in there.
Rick
  • 1,863
  • 2
  • 19
  • 46
  • Thank you @Rick but I did post for languageswitcher.js, it's the very first code. That small written function – Giorgio Jun 23 '16 at 16:02
1

There are several issues going on besides the one you are currently seeing.

  • The title variable does not seem to be set prior to being used. An initial value will be needed otherwise you will get a Uncaught ReferenceError: title is not defined error.
  • The title variable is being assigned rather than being checked. You are using '=' instead of '==' or '===' in your if statements. This is causing the first if block to not only always be true but also set title to "0" and value to "en_US".
  • document.getElementById("locale").options will not give you the options ordered by their value. They are ordered by their index number. I would reccomend changing that line to document.getElementById('locale').value = value

If you are trying to set the window's hash based on the value of the option that is selected then I would go with andybeli's answer. If you do not wish for the window to jump when the hash is updated then you can do one of the answers provided here:

How can I update window.location.hash without jumping the document?

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}
Community
  • 1
  • 1
  • Thank you @Darknesskight, I tried andybeli's answer and for some reason it still gave me an error... Uncaught TypeError: Cannot read property 'addEventListener' of null....... I deleted all of the titles since they are redundant. – Giorgio Jun 23 '16 at 16:10
  • 1
    You are likely receiving that error because the select element does not exist prior to that line of JavaScript running. You can either move that JavaScript block to be with the other JavaScript blocks at the bottom of the HTML or have that code in a window.onload function. – Darknesskight Jun 23 '16 at 16:24
  • Okay will do and try that and take that and put it in the window.onload function. Thanks so much for your help! – Giorgio Jun 23 '16 at 16:26