0

I tried to change src of an iframe, to change trailers, but after trying to utilize the answer of a different post: iframe src change on button click but I still couldn't get it to work, it keeps saying: "newSrc is not defined at HTMLButtonElement.onclick (index)(9:65)"

I want to thank everyone for their comments, I found the problem and solved it, I forgot to link the javascript on the page I was working on, the dumbest mistake that I could've made

Thank you Chris for helping with extra tips and Nermin for making me realise my dumb mistake

function newSrc() {
  var e = document.getElementById("Menu_trailers");
  var newSrc = e.options[e.selectedIndex].value;
  document.getElementById("trailers").src=newSrc;
}
      <figure class="trailer">
        <iframe src="https://www.youtube.com/embed/sfAc2U20uyg" id="trailers"> </iframe>
      </figure>
      <section class="button_trailer">
        <select id="Menu_trailers">
          <option value="https://www.youtube.com/embed/sfAc2U20uyg">Trailer 1</option>
          <option value="https://www.youtube.com/embed/o-L1mMZ31hM">Trailer 2</option>
        </select>
        <button onclick="newSrc();" class="button_next_trailer">Change trailer</button>
      </section>

3
  • You shouldn't use the same name for a local variable and a function, and you can read the <select>'s .value directly, but other than that, the code works for me: jsfiddle.net/adzrv10p (note that in order to solve this problem, you shouldn't google "how to change iframe src on button click", what you want is a) handle a button click b) change the attribute of an HTMLElement; if you split your problem into its parts and generalize the requirement, you will have a much easier time finding existing solutions) Commented May 2, 2022 at 11:00
  • stackoverflow.com/questions/52309180/… Commented May 2, 2022 at 11:05
  • Are you sure that your function is defined and javascript executed before the HTML is loaded and you click the button? Commented May 2, 2022 at 11:24

1 Answer 1

0

Here is the JS code to get the src from the select menu, then set it to the iframe element

function newSrc() {
  // Get The Select Menu Element
  var e = document.getElementById("Menu_trailers");
  // Set Select Menu Value (Selected Option) To Be The src Of The iframe
  document.getElementById("trailer").src = e.value;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.