Home > Net >  Set HTML image src to form input
Set HTML image src to form input

Time:06-25

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>

CodePudding user response:

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">

  • Related