1

It's my first day working with JavaScript, and I need help on a simple demo. I need to take the value from class="populateValue", and make it fill in the text box and alert when the button is clicked.

Right now it is returning '[object Object]' in both text box and alert.

My code is:

<section>
    <form>
        <input type="text" id="demoText" />
        <button class="populateValue" value="1234">Populate Value</button>
    </form>
</section>

<script>
    $(document).ready(function () {
        $('.populateValue').on('click', function (event) {
            event.preventDefault();
            $('#demoText').val($('.populateValue'))
            alert($('#demoText').val());
        });
    });
</script>

Any advice?

1
  • One of the features on jQuery is that many (if not most) of its functions have one version that sets, and with one fewer argument, it gets. Commented Oct 16, 2012 at 15:35

1 Answer 1

7

change this line:

$('#demoText').val($('.populateValue').val());
Sign up to request clarification or add additional context in comments.

4 Comments

perfect! Care to explain why you need to add the additional .val?
@user1678151: $('.populateValue') is a jQuery object containing the element, $('.populateValue').val() is a string containing its value. '[object Object]' is what happens when you try to read an object as a string.
see comment by @RocketHazmat.
$("#demotext").val(this.value) is even more concise. this refers to the object that was clicked, ie the button.

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.