0

I have a couple of images that can be clicked on.
When click on an image I should add a name to a text field.
So in this example, an image of mickey mouse, the name of the image is "Mickey Mouse", this name should be in the text field.
With my code the whole image string is in the text box.

This is the image

<a onClick="insertText(this)" 
   href="#pagetwo" 
   data-transition="slide">
       <img src="images/mickey.png" 
            name="Mickey Mouse" 
            width="114" 
            height="114">
</a>

The function to write to the text field:

function insertText(txt) {
    document.getElementById('disney').value = txt.innerHTML;
}

The form field:

<label for="name">Melding:</label>
<input type="text" name="disneyfigure" 
       id="disney" readonly 
       value="<hier komt automatisch disney figuur>">
2
  • in your sample, what is the text you want to add in the textbox ? is it images/mickey.png ? Commented Feb 4, 2015 at 12:07
  • innerHTML in here document.getElementById('disney').value = txt.innerHTML; is whole img element you should instead get name attribute of this element. Commented Feb 4, 2015 at 12:07

3 Answers 3

3

The this in insertText(this) refers to the anchor tag. As such, when you request, the innerHTML it provides the html contained within the anchor tag.

Also, as you need to extract the name attribute, you must specifically retrieve this attribute.

Change the function to something like

function insertText(a) {
    document.getElementById('disney').value = a.getElementsByTagName('img')[0].getAttribute('name');
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to find the img inside the div, using querySelector or getElementsByTagName, then get it's name attribute using getAttribute():

function insertText(txt)
{
    var image = txt.getElementsByTagName('img')[0]; // find the image
    var text = image.getAttribute('name'); // get it's name attribute value
    document.getElementById('disney').value = text;
}
<div><a onClick="insertText(this)" href="#pagetwo" data-transition="slide"><img src="images/mickey.png" name="Mickey Mouse" width="114" height="114"></a></div>

<label for="name">Melding:</label>
<input type="text" name="disneyfigure" id="disney" readonly value="<hier komt automatisch disney figuur>">

Comments

0

You should use alt attribute for image name.

<img src="images/mickey.png" alt="Mickey Mouse" width="114" height="114">

Then you can easily fill it into input text with this code:

document.getElementById('disney').value = txt.alt;

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.