0

I would like an image to be displayed based on what is entered inside the form. The problem is with figure_id as when displayed with console log it is a blank string even when text is submitted inside the form.

<form  method="GET" id="figure_choice_form">
    <label for="figure_id">Enter ID</label>
    <input type="text" id="figure_id" name="figure_id">
</form>

<img id="figure_image" src="RESULT_FROM_THE_FUNCTION" alt="img">

JavaScript I have tried

<script>
    function set_image_path(){
    var figure_id = document.getElementById("figure_id").value
    var image_path = `main/Bricklink/images/${figure_id}.png`
    document.getElementById("figure_image").img.src = image_path
    }
    set_image_path()
</script>
3
  • 1
    Typo error in your function set_image_path, .img.**scr** is incorrect, change it to .img.src Commented Jun 19, 2022 at 13:18
  • also need to add an event to the input, or a button to fire the function, firing it onload the value wont be filled Commented Jun 19, 2022 at 13:20
  • The problem seems to be with figure_id. When i console log it, it is a blank string, therefore image_path is "main/Bricklink/images/.png" Commented Jun 19, 2022 at 13:24

1 Answer 1

1

The problem is here document.getElementById("figure_image").img.src, there is no img property.

So change it to document.getElementById("figure_image").src

function set_image_path() {
  const figure_id = document.getElementById("figure_id");
  const figure_image = document.getElementById("figure_image");
  const image_path = `main/Bricklink/images/${figure_id.value}.png`;
  figure_image.src = image_path;
  console.log(figure_image.src);
}

//call function in submit listener
const form_figure = document.getElementById("figure_choice_form");
form_figure.addEventListener('submit', e => {
  e.preventDefault();
  set_image_path();
})

//call function in load page - if input has value
set_image_path();
<form method="GET" id="figure_choice_form">
  <label for="figure_id">Enter ID</label>
  <input type="text" id="figure_id" name="figure_id" value="image123">
  <button> Submit </button>
</form>

<img id="figure_image" src="RESULT_FROM_THE_FUNCTION" alt="img">

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.