0

I am attempting to create a simple math quiz application for a child with on screen number keys that will append to an input field for the answer. I want to use jQuery event listener linked to a class so I do not have to call an onClick function for each number. I found this question elsewhere but I am unable to comment to further ask issue I am having as I have just joined stacked overflow and it states my reputation isn't high enough.

Link to other question: append value to an input field in JQuery

When I attempt to append I get an undefined when I attempt to click my buttons and I cannot see where the error in my code is. Any assistance would be greatly appreciated.

My jQuery:

$(".userIn").click(function() {
  var usrIn = $(this).data('usrIn');
  $("#answer").val(function() {
    return this.value + usrIn;
  });
});

Sample of my buttons:

<button type="button" class="btn btn-primary btn-block userIn" data-number="0" id="zero">0</button>

Here is the JSfiddle with all my linked style sheets and external js.

3 Answers 3

3

Change var usrIn = $(this).data('usrIn'); to var usrIn = $(this).attr('data-number');

Fiddle: https://jsfiddle.net/969r1gp0/4/

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

1 Comment

Thank you so much. Once I moved my function to the document.ready section of my js it began working in the browser as well.
1

Your data attribute is called data-number, not data-userin, so you should write:

var usrIn = $(this).data('number')

But as the text of the buttons really is what you want to add, you could do without the data attributes all together, and just do:

var usrIn = $(this).text();

2 Comments

Thank you! I tried this out and it still wasn't working in my code till I realized that it wasn't working the browser yet it was working in fiddle. Once I moved it into my $(document).ready section it began working. I will be using the other solution which I marked as answered but want to thank you as I tested both your solutions and they worked for me as well.
NB: jsfiddle does this automatically (putting the script in a load function). It is a setting that you can change, but is like that by default.
0

try this both, it's working

document.getElementById("input_id").value = you_value;
document.getElementById("input_id").textContent = you_value;

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.