Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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..

like image 550
Z with a Z Avatar asked Dec 18 '12 20:12

Z with a Z


People also ask

How can you send text input to an input field?

The line <input type="text"> creates a single line text input field, where the user can type any text input.

How do you add to the input field?

To append an element with a text message when the input field is changed, change() and appendTo() methods are used. The change() method is used to detect the change in the value of input fields. This method works only on the “<input>, <textarea> and <select>” elements.

Which tag is used to add a text field to a form?

The <input> tag specifies an input field where the user can enter data. The <input> element is the most important form element. The <input> element can be displayed in several ways, depending on the type attribute.


2 Answers

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/ ​

like image 157
PhearOfRayne Avatar answered Oct 12 '22 23:10

PhearOfRayne


this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>
like image 28
Hat Avatar answered Oct 13 '22 00:10

Hat