Add a string of text into an input field when user clicks a button

Issue

Basically just trying to add text to an input field that already contains a value.. the trigger being a button..

Before we click button, form field would look like.. (user inputted some data)

[This is some text]
(Button)

After clicking button, field would look like.. (we add after clicking to the current value)

[This is some text after clicking]
(Button)

Trying to accomplish using javascript only..

Solution

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />​

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/

Answered By – PhearOfRayne

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published