0

I have an image that contains a data-keyword attribute. Can anyone show me how to get its string and show it in the input field when I click on the image? I can get the text link .special_field_link to work but not the image .image_keyword. (FIDDLE) The following code doesn't work:

HTML

<input id="a_input_id" type="text">
<a href="" class="special_field_link">@ABC<a>
<a href="" class="special_field_link">@DEF<a>
<img src="image.jpg" class="image_keyword" data-keyword="Hello" alt="pic">

JS:

$('.special_field_link,.image_keyword').click(function (e)   {
   e.preventDefault();
   if($(this).is('.image_keyword')){
      var keyword = $(this).data('keyword');
      $('#a_input_id').val(  ( $('#a_input_id').val()+" "+$(this).keyword.html() ).trim()  );      
   } 
   else {         
      $('#a_input_id').val(  ( $('#a_input_id').val()+" "+$(this).html() ).trim()  );
   }
});
1

3 Answers 3

1

One of your selectors is broken: $('.special_field_link,image_keyword') is missing the . in what should be .image_keyword

You are accessing the data attribute correctly with .data('keyword'), but you don't need the call to .html():

var keyword = $(this).data('keyword');
$('#a_input_id').val(  ( $('#a_input_id').val()+" "+keyword ).trim()  );      

Fiddle: http://fiddle.jshell.net/s8nUh/178/

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

Comments

1

Try

$('.image_keyword').click(function (e)   {
    $('#a_input_id').val($('.image_keyword').data('keyword'));
});

Comments

0

This is just an example. Feel free to adapt it to your code.

image.addEventListener("click", function() {
    var data = image.getAttribute("data-keyword");
    input.value = data;
})

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.