0

I am trying to change an Image SRC based on a variable in javascript.

I have the following modal:

<div class="modal-body">
    <img src="https://www.w3schools.com/js/landscape.jpg" alt="image" width="400" name="image_modal" id="image_modal">
    <div class="form-group">
        <label>Image Name</label>
        <input type="text" name="image_name" id="image_name" class="form-control" />
    </div>
    <div class="form-group">
        <label>Image Description</label>
        <input type="text" name="image_description" id="image_description" class="form-control" />
    </div>
    <div class="form-group">
        <label>Path</label>
        <input type="text" name="path" id="path" class="form-control" />
    </div>  
</div>
<div class="modal-footer">
    <input type="hidden" name="image_id" id="image_id" value="" />
    <input type="submit" name="submit" class="btn btn-info" value="Edit" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>

I then try to change the initial dummy SRC in JS:

...
$.ajax({
   url:"edit.php",
   method:"post",
   data:{image_id:image_id},
   dataType:"json",
   success:function(data)
   {
    $('#imageModal').modal('show');
    $('#image_id').val(image_id);
    $('#image_name').val(data.image_name);
    $('#path').val(data.path);
    $('#image_description').val(data.image_description);
    document.getElementById("image_modal").src = val(data.path);
   }
});

I am checking if the src URL is correct by showing it in the modal (data.path) and it is correctly outputted.

But when trying to change src with document.getElementById("image_modal").src = val(data.path);no image is shown, like if the variable was not correctly interpreted.

4
  • 5
    Consistency question: why are you using document.getElementById when you're very clearly bought into jQuery? Why is that one line not $("#image_modal").attr("src", ...)? Commented May 3, 2020 at 23:07
  • 3
    Does this answer your question? Changing the image source using jQuery Commented May 3, 2020 at 23:07
  • 1
    Do you get any error in the console - e.g. 404, etc? Commented May 3, 2020 at 23:29
  • you are right mike. this works Commented May 3, 2020 at 23:44

1 Answer 1

0

Your problem is here: val(data.path);

Unless you've defined it, val() is undefined. You should be able to just use data.path, assuming it's the string you're after.

Use this instead

document.getElementById("image_modal").src = data.path;

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.