简体   繁体   中英

How to auto insert text in an html form and auto submit it?

我正在做一个项目,我只想创建一个用于发布回复的html表单,但如果用户懒得回复,他/她只需单击自动生成注释即可直接在表单上插入文本然后自动发布..

$( "#lazybutton" ).click(function() {
  $('#inputBox').val("Hey I feel too lazy to type"); // filled automatically in input box        
    setTimeout(function(){
      $('#form').submit(); //submitting form
    }, 2000);
});

added sleep time so users can see input box for 2 sec after filled it.

Assuming you want to execute at client site.

create a Array/String of predefined answer and create a click handler of Posting button then insert predefined answer to comment box and post it.

$(document).ready(function () {
    var RandComment= ["First Random Comment","Second Random Comment","Third Random Comment"]
    $("#btnSubmit").click(function () {
        var pickRandomComment = RandComment[parseInt(Math.random() * RandComment.length-1)];
        $("#txtCommentBox").val(pickRandomComment);        
        //Call ajax if want to implement

    });
});

For this, first, you should generate the text and append the generated text to comment field. But after I'm not sure what do you want as asking for "automatically posted". Do you want to post the form as like normally pressing the submit button? If yes, you may use the below code as logic.

$("button#lazyGenerate").on("click", function(){
  var generatedText = "bla bla and bla";
  $("#yourCommentField").val(generatedText);

$("input[name='submitButtonName']").click();

});

Using jQuery, the input can be populated using .val() then submitting the form using .submit() which will be the same as the submit button being clicked.

 $(document).on('click', '#autogen', function(){ $('#myTextarea').val('Some comment here'); $('#myForm').submit(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <form id="myForm" action="/" method="post"> <input type="text" id="myTextarea" name="myTextarea"> <input type="submit" value="Submit"> </form> <button id="autogen">Generate</button> 

Reference: jQuery Documentation

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