最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fill data in input boxes automatically - Stack Overflow

programmeradmin0浏览0评论

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?

Share Improve this question edited Mar 19, 2017 at 2:36 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked Feb 10, 2012 at 10:34 user1199657user1199657 1
  • 3 Yes, it's possible with JavaScript. What have you tried? People will be happier to help you if you show some effort. – James Allardice Commented Feb 10, 2012 at 10:36
Add a comment  | 

3 Answers 3

Reset to default 8

On button click, call this function

function fillValuesInTextBoxes()
{
    var text = document.getElementById("firsttextbox").value;

    document.getElementById("secondtextbox").value = text;
    document.getElementById("thirdtextbox").value = text;
    document.getElementById("fourthtextbox").value = text;
}

Yes, it's possible. For example:

 <form id="sampleForm">
     <input type="text" id="fromInput" />
     <input type="text" class="autofiller"/>
     <input type="text" class="autofiller"/>
     <input type="text" class="autofiller"/>
     <input type="button"value="Fill" id="filler" >
     <input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
 </form>

with the javascript

 function fillValues() {
       var value = $("#fromInput").val();
       var fields= $(".autofiller");
       fields.each(function (i) {
         $(this).val(value);
       });
 }

 $("#filler").click(fillValues);

assuming you have jQuery aviable. You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/

Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:

 fillValuesNoJQuery = function () {
       var value = document.getElementById("fromInput").value;
       var oForm = document.getElementById("sampleForm");
       var i = 0;
       while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
 }

You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/

or if input:checkbox

document.getElementById("checkbox-identifier").checked=true; //or ="checked"
发布评论

评论列表(0)

  1. 暂无评论