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

前端 未结 4 2198
日久生厌
日久生厌 2020-12-14 08:49

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

相关标签:
4条回答
  • 2020-12-14 09:18

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

    0 讨论(0)
  • 2020-12-14 09:20

    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>
    
    0 讨论(0)
  • 2020-12-14 09:32

    Don't forget to keep the input field on focus for future typing with input.focus(); inside the function.

    0 讨论(0)
  • 2020-12-14 09:38

    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')       
    });​
    
    0 讨论(0)
提交回复
热议问题