Michael Connell
Michael Connell

Reputation: 9

Load data into a div when a select option is chosen

Hi I have recently been playing around with jquery. I originally had three buttons with names of cities on and using the simple jquery .load function to enter the data into another separate div.

<script>
$(document).ready(function(){
    $(".London").click(function(){
        $("#div1 h2").load("London.txt");
    });
    $(".NewYork").click(function(){
        $("#div1 h2").load("NewYork.txt");
    });
    $(".Shanghai").click(function(){
        $("#div1 h2").load("Shanghai.txt");
    });
});
</script>

I now want to change this and use a select box to do the same thing however when trying this it doesn't work.

  <select class="Select">
    <option value="" disabled selected hidden>Select a City</option>
    <option value="NewYork" class="NewYork">New York</option>
    <option value="Shanghai" class="Shanghai">Shanghai</option>
    <option value="London" class="London">London</option>
  </select>

Upvotes: 0

Views: 1413

Answers (3)

user2575725
user2575725

Reputation:

Use change event of <select> instead

$(function() {
  var h2 = $('#div1').find('h2');
  $('.Select').on('change', function(e) {
    var city = $(this).val();
    h2.text('City changed to:' + city);
    var url = city + '.txt';
    h2.load(url, function(resp, status, req) {
      if ('error' === status) {
        h2.text('Failed to load url: ' + url);
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="Select">
  <option value="" disabled='' selected=''>Select a City</option>
  <option value="NewYork">New York</option>
  <option value="Shanghai">Shanghai</option>
  <option value="London">London</option>
</select>
<div id="div1">
  <h2>Please select city from top</h2>
</div>

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44087

What you're doing with the selectors is wrong. <option> elements give their value attribute to the <select> when they are selected, so if you use

$(".Select").value

after you select an option, it will take the value of the selected option. Here's how I fixed your code:

$(".Select").on("change", function(){
    if ($(".Select").value == "London") {
        $("#div1 h2").load("London.txt");
    } else if ($(".Select").value == "NewYork") {
        $("#div1 h2").load("NewYork.txt");
    } else if ($(".Select").value == "Shanghai") {
        $("#div1 h2").load("Shanghai.txt");
    }
});

Upvotes: 0

zerosand1s
zerosand1s

Reputation: 750

You will have to use change event to of select. So try this

<script>
$(document).ready(function(){
    $(".Select").change(function(){
        if($(this).val() === "London") { //load London.txt } 
        else if($(this).val() === "NewYork") { //load NewYork.txt }
        else if($(this).val() === "Shanghai") { //load Shanghai.txt }
    });
});
</script>

Upvotes: 1

Related Questions