user3590094
user3590094

Reputation: 119

Javascript -> redirect by select and pick selected value

i have in index.html this code:

 <select id="myselect" class="form-control"  ONCHANGE="location.href = 'drzave.html'">
        <option selected disabled>Odabir:</option>
        <option value="2010">2010</option>
        <option value="2011">2011</option>
        <option value="2012">2012</option>
        <option value="2013">2013</option>
        <option value="2014">2014</option>
        <option value="2015">2015</option>
      </select>

When i change it, it redirect on drzave.html. In drzave.html i have included data.js with code:

var test = $( "#myselect" ).val();
    console.log(test)

I'm trying to get selected value on index.html , but i receive undefined message.

Thanks, Tomislav

Upvotes: 1

Views: 388

Answers (2)

Buzinas
Buzinas

Reputation: 11725

You wont be able to get the #mySelect selected value in any other page than index.html.

To achieve what you want, the best way is by saving the selected value to the sessionStorage. E.g:

<select id="myselect" class="form-control">
  <option selected disabled>Odabir:</option>
  <option value="2010">2010</option>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
  <option value="2015">2015</option>
</select>
<script>
  document.getElementById('myselect').addEventListener('change', function(e) {
    sessionStorage.setItem('myselect', this.value);
    location.href = 'drzave.html';
  });
</script>

And then, in your drzave.html page, you can get the value by doing:

var test = sessionStorage.getItem('myselect');
console.log(test);

Other ways are:

Probably there are other ways, but I don't think any of them will be better.

I've created a plnkr for you to show the usability.

Upvotes: 2

S.Kiers
S.Kiers

Reputation: 4206

If I understand correctly, you want the selected option's value passed through to the page drzave.html?

If so, you would

function redirectFunction() {
  window.location.replace ('drzave.html?myselect=' + $('#dropDownId').val())
  // then on landing page you will have to parse this value out of the querystring
  // or you could use cookies to set the value to the next page (google jquery.cookie)
}


$(document).ready(function() {
  $("#myselect").on("change", redirectFunction);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<select id="myselect" class="form-control">
  <option selected disabled>Odabir:</option>
  <option value="2010">2010</option>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
  <option value="2015">2015</option>
</select>

Upvotes: 1

Related Questions