javascript 使用javascript自动填写表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17932263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:09:32  来源:igfitidea点击:

Automatic form fill using javascript

javascript

提问by Strimer_SK

here is my code:

这是我的代码:

function setActualDate()
{
var d1 = new Date();
var y = d1.getFullYear();
var d = d1.getDate();
var m1 = d1.getMonth() + 1;
var m2 = d1.getMonth();

document.getElementById('entryDate').value = (y+"-"+m1+"-"+d);
document.getElementById('selectedYear').value = y;
document.getElementById('selectedMonth').value = ("0"+m2);
}
</script>
</head>

<body onload="setActualDate()">
<div id="page">
<h3> Welcome to Money Logger!</h3>

<form name="enter" action="enter.php" method="post">
Enter
<select name="mode">
<option selected="selected" value=""></option>
<option value="1">the money withdraw</option>
<option value="2">the money income</option>
</select>
<input id ="entryDate" type="date" name="entryDate">
<input type="text" name="entryName">
<input type="text" name="entryValue">
<input type="submit" value="Enter">
<input type="reset" value="Clear">                    
</form>

<form name="getEntry" action="getEntry.php" method="post">
Choose month and year for monthly overview:
<select name="month">
   <option id = "selectedMonth" selected="selected" value=""></option>

</select>
<select name="year">
<option id = "selectedYear" selected="selected" value=""></option>
</select>
<input type="submit" value="Display">
</form>
</div>
</body>

I used simple javascript to automatically fill the form inputs "entryDate, selectedYear, selectedMonth" by actual date and some other dates used by the further scripts.

我使用简单的 javascript 按实际日期和其他脚本使用的其他一些日期自动填写表单输入“entryDate、selectedYear、selectedMonth”。

My problem is, that when the site is loaded, only first input is automatically filled - the input with id = entryDate.

我的问题是,当网站加载时,只有第一个输入会自动填充 - id = entryDate 的输入。

The next 2 inputs are empty. But, when I press F5 and the site is reloaded again, the 2 inputs are filled correctly.

接下来的 2 个输入是空的。但是,当我按 F5 并再次重新加载站点时,2 个输入已正确填充。

Could you please help me fix it to have all 3 forms filled when the site is loaded for the first time...

您能否帮我修复它以在第一次加载网站时填写所有 3 个表格...

Thank you

谢谢

回答by user428517

You are not using <select>and <option>correctly. <select>represents a dropdown, which can contain multiple <option>elements.

您没有正确使用<select><option><select>表示一个下拉菜单,可以包含多个<option>元素。

An <option>element represents an option in the dropdown. You close an <option>with </option>. Whatever is BETWEEN the tags will appear in the dropdown:

一个<option>元素代表下拉列表中的一个选项。你关闭一个<option>with </option>。无论标签之间是什么,都将出现在下拉列表中:

<option>Hello</option>   <!--user sees "Hello" as an option in the dropdown-->

On the other hand, an <option>'s valueattribute contains the string that will be sent to the server, if the option is selected, when the form is submitted. You can think of this as the "real" value of the <option>: the user won't see it, but it's the one that matters. Whatever is between <option>and </option>is visible by the user, but doesn't actually DO anything.

另一方面,如果选择了该选项,则在提交表单时,<option>value属性包含将发送到服务器的字符串。您可以将其视为 的“真实”价值<option>:用户不会看到它,但它才是最重要的。用户可以看到<option>和之间的</option>任何内容,但实际上并没有做任何事情。

Any oneof a dropdown's options can be "selected" (that is, visible as the chosen option in the dropdown) by giving it a selectedattribute set to selected(selected="selected"). When a user chooses an option, this attribute gets set automatically (and the selectedattribute on the other options gets cleared).

任何一个的下拉的选项可以被“选择”(即,如在下拉列表中选择的选项可见)通过给它一个selected属性设置为selectedselected="selected")。当用户选择一个选项时,该属性会自动设置(并且selected其他选项上的属性会被清除)。

So first of all, let's get your selectedYeardropdown looking right. You'll need to manually provide some years as options:

所以首先,让我们让你的selectedYear下拉菜单看起来正确。您需要手动提供一些年份作为选项:

<select id="selectedYear" name="year">
    <option value="2013">2013</option>
    <option value="2012">2012</option>
    <option value="2011">2011</option>
</select>

Note that you need to specify the year bothbetween the tags AND in each <option>'s valueattribute, as explained above. Also note that I moved the idto the <select>. There's rarely a reason to select an individual <option>of a <select>; typically to modify a dropdown's options, you should select the <select>tag itself.

请注意,您需要指定一年标记之间以及每个<option>value属性,如上面解释的。另外请注意,我感动id<select>。有很少的理由选择一个单独<option><select>; 通常要修改下拉列表的选项,您应该选择<select>标签本身。

So, let's try that. I'll re-create the dropdown above, but I'll add its options using JavaScript:

所以,让我们试试看。我将重新创建上面的下拉列表,但我将使用 JavaScript 添加其选项:

<select id="selectedYear" name="year"></select>

<script type="text/javascript">
    var dropdown = document.getElementById('selectedYear');
    var start_year = 2011;
    var end_year = 2013;

    for (var i =  start_year; i <= end_year; i++) {
        dropdown.innerHTML += '<option value="' + i + '">' + i + '</option>';
    }
</script>

The innerHTMLfunction lets you set the HTML content betweenan element's opening tag (in this case <select id="selectedYear" name="year">and closing tag (</select>).

innerHTML函数使您可以元素的开始标记(在本例中为<select id="selectedYear" name="year">结束标记 ( </select>))之间设置 HTML 内容。

Knowing this, it's pretty easy to select the option you want using JavaScript. Remember you can do this by setting the selectedattribute of the <option>to "selected". Here's a portion of your setActualDatefunction, showing how to set the default year for just the selectedYeardropdown:

知道了这一点,就可以很容易地使用 JavaScript 选择您想要的选项。请记住,您可以通过将 的selected属性设置<option>为“已选择”来实现此目的。这是您的setActualDate函数的一部分,展示了如何仅为selectedYear下拉列表设置默认年份:

<script type="text/javascript>
function setActualDate() {
    var d1 = new Date();
    var year = d1.getFullYear();
    var dropdown = document.getElementById('selectedYear');

    //loop through the dropdown's options
    for (var i = 0; i < dropdown.options.length; i++) {
        var option = dropdown.options[i];

        //check if this is the option we want to set
        if (option.value == year) {
            option.selected = true;
        } else {
            //ensure all other options are NOT selected
            option.selected = false;
        }

        //NOTE: you can simplify the above if-else to just:
        //option.selected = (option.value == year);
    }
}
</script>

That should be enough to get you started. I hope it all makes sense.

这应该足以让你开始。我希望这一切都有意义。

回答by Moazzam Khan

Use the following HTML for month -

使用以下 HTML 一个月 -

<!-- HTML for month -->
<select id = "selectedMonth" name="month">
   <option  value="1">Jan</option>
   <option  value="2">Feb</option>
   <option  value="3">Mar</option>
   <option  value="4">Apr</option>
   <option  value="5">May</option>
   <option  value="6">Jun</option>
   <option  value="7">Jul</option>
   <option  value="8">Aug</option>
   <option  value="9">Sep</option>
   <option  value="10">Oct</option>
   <option  value="11">Nov</option>
   <option  value="12">Dec</option>
 </select>

 <!-- HTML for year -->
<select id="selectedYear" name="year">
   <option value="2010">2010</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
</select>

and script

和脚本

//script for setting month
var monthEl = document.getElementById('selectedMonth');
monthEl.options[m2].selected = "selected"

//for year 
var yearEl = document.getElementById('selectedYear');
yearEl.options[y].selected = "selected"

回答by Icarus

You are getting the elements by their ID so the first time the script runs only fills out the first elements it finds (probably the ones in the first form).

您通过它们的 ID 获取元素,因此脚本第一次运行时只填写它找到的第一个元素(可能是第一个表单中的元素)。

Since you have several elements to fill out automatically, you should be setting classes to on them and use these classes to select the ones you are interested in. For example:

由于您有几个元素要自动填写,您应该在它们上设置类并使用这些类来选择您感兴趣的那些。例如:

<form id="form1">
    <input class="entryDate" type="text"> <!-- note the class=..." -->
</form>
<form id="form2">
    <input class="entryDate" type="text">
    <select name="mode" class="selectedMonth"> <!-- note the class=..." -->
        <option selected="selected" value=""></option>
        <option value="1">the money withdraw</option>
        <option value="2">the money income</option>
    </select>
</form>

Now your code should be something like this:

现在你的代码应该是这样的:

window.onload = function setActualDate() {
    var d1 = new Date();
    var y = d1.getFullYear();
    var d = d1.getDate();
    var m1 = d1.getMonth() + 1;
    var m2 = d1.getMonth();
    var entryDates = document.getElementsByClassName('entryDate');
    var years = document.getElementsByClassName('selectedYear');
    var months = document.getElementsByClassName('selectedMonth');
    var i, j;
    for (i in entryDates)
    entryDates[i].value = (y + "-" + m1 + "-" + d);
    for (i in months) {
        for (j in months[i].options)
        if (months[i].options[j].value == m1) {
            months[i].options[j].selected = true;
            break;
        }
    }
    //similarly for years...
};

Here's a fiddle demonstrating it: http://jsfiddle.net/QDdAp/2/

这是一个演示它的小提琴:http: //jsfiddle.net/QDdAp/2/