简体   繁体   中英

How do I create a text box with a submit button that performs a callback on click to a javascript function using js or jQuery?

I'm new to javascript and am having a hard time finding the answer to this. Any help is appreciated.

If you had the following HTML:

<input type="text" />
<input id="button" type="button" value="Click Me" />

You can bind a function to be executed when a click event fires on that button like this:

$(function() {
    $('#button').click(function() {
        // Do logic here
    });
});

Creating it all on the fly

You can insert the previous HTML into your document using jQuery. First select another element in the DOM which locates where you wish to insert the HTML:

$('#someElement')

Then you can use any of the jQuery insertion methods in order to inject some HTML of your own:

$('#someElement')
    .append('<input type="text" />')
    .append('<input id="button" type="button" value="Click Me" />');

Now that your elements are in the DOM, you can select them and bind a callback to the click event in the normal way:

$('#button').click(function() {
    // Do logic here
});

the html : <textarea id="txt"></textarea><input type="button" id="button">submit</input>
and the js:


var d = document.getElementById('button');// identifying the button 
function myFunction(){
   var text = document.getElementById('txt').value;//getting the user's input
   // and whatever you want to do with the user's input
}
d.addEventListener('click',myFunction,false);//attaching myFunction to be called on the button click`
If you use jQuery, the syntax is a bit simpler :
 $('#button').click(myFunction); // or $('#button').click(function(){ var text = $('#txt').val(); //and again your logic here }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM