Jethro Knowles
Jethro Knowles

Reputation: 11

jquery not changing src of element

I have a select element in my HTML, i then have an iframe that displays PDFs. i have some jquery code that should change the "src" attribute of the iframe when a user selects an option but so far i cant seem to get it to trigger. when i click an option from the select nothing happens. i have tried using .change() and .on("change") but they do not work. i have console.log within the function but it does not log anything into the console.

The jquery

$(document).ready(function(){
    var x = $("#demo-category").val();
    $("#demo-category").on("change", "#demo-category", function(){
        $("#readframe").attr("src", x);
        console.log(x);
        console.log("test");
   });
});

should you need any more information i will provide it if i can.

Upvotes: 0

Views: 56

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371233

Event delegation (that is, your

.on("change", "#demo-category", function(){

) is for when the element that triggers the event is different from the element that the listener is added to. When you want to add a plain listener to a single element, don't pass another selector - if you do that, the listener won't fire. Instead just call .on('change', fn....

Also, you're retrieving x on document load. Retrieve the new value after #demo-category changes instead:

$(document).ready(function() {
  $("#demo-category").on("change", function() {
    var x = $(this).val();
    $("#readframe").attr("src", x);
    console.log(x);
    console.log("test");
  });
});

Upvotes: 1

D. Seah
D. Seah

Reputation: 4592

I think this will work

$(document).ready(function(){
  $("#demo-category").on("change", function(){
      $("#readframe").attr("src", $(this).val());
  });
});

Upvotes: 1

Related Questions