Z with a Z
Z with a Z

Reputation: 603

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

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

Upvotes: 22

Views: 178703

Answers (4)

Potter Edgerton
Potter Edgerton

Reputation: 103

HTML

<form>
<input id="myinputfield" value="This is some text">
<br>
<button onclick="text()">Click me!</button>​
</form>

Javascript

const myinputfield = document.querySelector("#myinputfield");

function text() {
  myinputfield.value = myinputfield.value + "after clicking";
}

I know this question is almost ten years old but this answer does not use jquery so it may be useful to others.

https://codepen.io/frog22222/full/oNdPdVB

Upvotes: 1

PhearOfRayne
PhearOfRayne

Reputation: 5050

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/

Upvotes: 46

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">​

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});​

Upvotes: 4

Hat
Hat

Reputation: 1731

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>

Upvotes: 5

Related Questions