javascript - 如何从具有相同名称的输入中获取值(数组)

时间:2017-01-16 16:45:49

标签: javascript jquery

我想使用billingname[]billingcity[],但我不知道如何为这些输入编写.value。 (现在我使用了诸如billingname1,billingname2之类的序号,但我不想要序号)

<script>
    function FillBilling(f) {
      if(f.billingtoo1.checked == true) {
        f.billingname1.value = f.shippingname.value;
        f.billingcity1.value = f.shippingcity.value;
      }
        if(f.billingtoo1.checked == false) {
        f.billingname1.value = '';
        f.billingcity1.value = '';
      }

      if(f.billingtoo2.checked == true) {
        f.billingname2.value = f.shippingname.value;
        f.billingcity2.value = f.shippingcity.value;
      }
        if(f.billingtoo2.checked == false) {
        f.billingname2.value = '';
        f.billingcity2.value = '';
      }
    }
    </script>



    <td bgcolor="eeeeee">
    <b>Mailing Address</b>
    <br><br>
    <form id="add_field">
    Name:
    <input type="text" name="shippingname">
    <br>
    City:
    <input type="text" name="shippingcity">
    <br>
    <input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo1">
    <em>Check this box if Billing Address and Mailing Address are the same.</em>
    <p>
    <b>Billing Address</b>
    <br><br>
    Name:
    <input type="text" name="billingname1">
    <br>
    City:
    <input type="text" name="billingcity1">
    </p>

    <input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo2">
    <em>Check this box if Billing Address and Mailing Address are the same.</em>
    <p>
    <b>Billing Address</b>
    <br><br>
    Name:
    <input type="text" name="billingname2">
    <br>
    City:
    <input type="text" name="billingcity2">
    </p>
    </form>
    </td>

1 个答案:

答案 0 :(得分:2)

如果您不打算给每个字段一个唯一的标识符(可能是id属性),则必须遍历所有字段以获取每个字段的值:

$('input[name="billingname[]"]').each(function() { 
    this.value = f.shippingname.value; 
});

不确定代码如何在您的环境中实际运行,但它应该给您一个想法。