cw2504 cw2504 - 20 days ago 5
HTML Question

use jquery to change a link on a button when two options are selected

Hi I want to create a simple search form so when a user selects option 1 it then displays specific options. I then want the link on a button to take them to that page on the website.

I have this code from another thread which works great (without the button) but how would I make a button so if animal was selected in the first box then wolf was selected in the second box the button link would change to www.mysite.com/wolf.html?

Thanks



$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>




Answer

Use this:

HTML:

<select name="select1" id="select1">
  <option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

<a href="" ></a>

JS:

$("#select1").change(function() {
  if ($(this).data('options') == undefined) {
    /*Taking an array of all options-2 and kind of embedding it on the select1*/
    $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
  var link = 'www.mysite.com/'+ $('#select2 :selected').text() +'.html';
  $('a').attr({href:link}).text(link);
});

$("#select2").change(function() {
var link = 'www.mysite.com/'+ $("option:selected", this).text() +'.html';
  $('a').attr({href:link}).text(link);
});