Reputation: 7092
I have a test, and need a hint function.
When the user clicks on hint the first letter of the answer has to be written in the input field. If he clicks again, the second letter is added etc.
The answer is written in data-right data attribute like this:
<div class="question">
<input class="input" type="text" placeholder="(gehen)" data-right="gegangen" />
<div class="res"><b></b></div>
<a class="hint">Hint</a>
</div>
Question,
Whats the simplest way to do this? Basically keep adding one more letter fron the answer in data-right in the input with every click on .hint?
I think I can handle the DOM navigation, but not sure how to do the output.
Upvotes: 0
Views: 80
Reputation: 144689
You can use the jQuery .data()
method for getting the value of the data-*
attribute and .val()
method for setting the value:
$('a.hint').on('click', function(event) {
event.preventDefault();
$(this).closest('.question').find('input').val(function(_, val){
var i = val.length,
right = $(this).data('right');
if (right.indexOf(val) !== 0) return right.slice(0, 1);
return val + right.slice(i, i+1);
})
})
Upvotes: 3
Reputation: 1626
You have to read data from attribute http://jsfiddle.net/4T5Ng/
$(document).ready(function(){
var dr = $(".input").attr("data-right").split("");
var index = 0;
$(".hint").click(function(){
if(index < dr.length)
$(".input").val($(".input").val() + dr[index]);
index++;
});
});
Upvotes: 1