ColdFusion/Javascript 动态表单

ColdFusion/Javascript Dynamic Form

我正在努力使此表单动态化。我有一个循环,允许客户在用户选择循环次数时选择 1 到 5。我想弄清楚我需要在哪里添加 _<cfoutput>#Add#</cfoutput> 以便当它循环时它只添加一个数字并且仍然可以正常工作。 The loop is working, the form is working when "1 Loop" is chosen.我只是不确定在 JavaScript 中的何处添加 _<cfoutput>#Add#</cfoutput> 以使第二个循环也能正常工作,以便它接收新的名称和 ID。我尝试过的一切都刚刚打破 JavaScript。建议和建议将不胜感激!

循环的外观
http://jsfiddle.net/bobrierton/gettgpmj/5/(不循环 JavaScript 进行地理定位)

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  postal_code: 'short_name'
};
var componentForm2 = {
  route2: 'long_name',
  locality2: 'long_name',
  administrative_area_level_12: 'short_name',
  postal_code2: 'short_name'
};

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });
  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
  google.maps.event.addListener(autocomplete2, 'place_changed', function() {
    fillInAddress2();
  });
}

// [START region_fillform]
function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
  //var keys=[];for (var key in place.address_components[0]) keys.push(key);
  //alert(keys):
  document.getElementById('autocomplete').value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete').value : '');*/
  document.getElementById('route').value = '';
}

function fillInAddress2() {
    // Get the place details from the autocomplete object.
    var place = autocomplete2.getPlace();

    for (var component in componentForm2) {

      document.getElementById(component).value = '';
      document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm2[addressType + '2']) {
        var val = place.address_components[i][componentForm2[addressType + '2']];
        document.getElementById(addressType + '2').value = val;
      }
    }
  document.getElementById('autocomplete2').value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route2').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete2').value : '');*/
  document.getElementById('route2').value = '';
}
  // [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
        position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

function geolocate2() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete2.setBounds(circle.getBounds());
      });
    }
  }
  // [END region_geolocation]
initialize();

document.querySelector('#chbSame').addEventListener('change', checkedAddr);


function checkedAddr() {
  if (document.getElementById('chbSame').checked) {
    document.getElementById('route2').value = document.getElementById('route').value;
    document.getElementById('locality2').value = document.getElementById('locality').value;
    document.getElementById('administrative_area_level_12').value = document.getElementById('administrative_area_level_1').value;
    document.getElementById('postal_code2').value = document.getElementById('postal_code').value;
    
document.getElementById('autocomplete2').value = document.getElementById('autocomplete').value;
  } else {
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>

<body onload="initialize()">
<div class="clearfix">
 <label for="street_1">Mailing Address 1:</label>
 <input name="street_1" type="text" maxlength="120"  onfocus="geolocate()"  id="autocomplete"  size="54"  />
</div>

<div class="clearfix">
 <label for="m2street_1">Mailing Address 2:</label>
 <input name="m2street_1" type="text" maxlength="120"  size="54"  id="route"  />
</div>
        
<div class="clearfix">
 <label for="city_1">City:</label>
 <input name="city_1" type="text" maxlength="50"  size="30"  id="locality"  />
    
<div class="clearfix">
     <label for="state_1">State:</label>
     <input type="text" name="state_1"  id="administrative_area_level_1" size="8" maxlength="12">
    </div>

        
<div class="clearfix">
 <label for="street_1">Zip Code:</label>
 <input name="postal_1" type="text" maxlength="12"  size="8"  id="postal_code"  />
</div>
            
       <script type="text/javascript">
        function FillBilling_1(f) {
  if(f.billingtoo_1.checked == true) {
    f.pstreet_1.value = f.street_1.value;
 f.p2street_1.value = f.m2street_1.value;
    f.pcity_1.value = f.city_1.value;
 f.pstate_1.value = f.state_1.value;
 f.ppostal_1.value = f.postal_1.value;
  }
}
        </script>
        
<div class="clearfix">
 <input type="checkbox" name="billingtoo_1" onclick="FillBilling_1(this.form)" id="chbSame">
 <em>Check this box if Physical Address and Mailing Address are the same.</em>
</div>


        
<div class="clearfix">
 <label for="pstreet_1">Physical Address 1:</label>
 <input name="pstreet_1" type="text" maxlength="120"  onfocus="geolocate2()"  id="autocomplete2"  size="53"  />
</div> 

<div class="clearfix">
 <label for="p2street_1">Physical Address 2:</label>
 <input name="p2street_1" type="text" maxlength="120"  size="53"  id="route2"  />
</div>
        
<div class="clearfix">
 <label for="pcity_1">City:</label>
 <input name="pcity_1" type="text" maxlength="50"  size="30"  id="locality2"  />
    
<div class="clearfix">
     <label for="pstate_1">State:</label>
     <input type="text" name="pstate_1"  id="administrative_area_level_12" size="8" maxlength="12">
    </div>

       
<div class="clearfix">
 <label for="pstreet_1">Zip Code:</label>
 <input name="ppostal_1" type="text" maxlength="12"  size="8"  id="postal_code2"  />
</div>
 <br>
     <br>
         
<div class="clearfix">
 <label for="street_2">Mailing Address 1:</label>
 <input name="street_2" type="text" maxlength="120"  onfocus="geolocate()"  id="autocomplete"  size="54"  />
</div>

<div class="clearfix">
 <label for="m2street_2">Mailing Address 2:</label>
 <input name="m2street_2" type="text" maxlength="120"  size="54"  id="route"  />
</div>
        
<div class="clearfix">
 <label for="city_2">City:</label>
 <input name="city_2" type="text" maxlength="50"  size="30"  id="locality"  />
    
    <div class="clearfix">
     <label for="state_2">State:</label>
     <input type="text" name="state_2"  id="administrative_area_level_1" size="8" maxlength="12">
    </div>
        <div class="clearfix">
 <label for="street_2">Zip Code:</label>
 <input name="postal_2" type="text" maxlength="12"  size="8"  id="postal_code"  />
</div>
            
       <script type="text/javascript">
        function FillBilling_2(f) {
  if(f.billingtoo_2.checked == true) {
    f.pstreet_2.value = f.street_2.value;
 f.p2street_2.value = f.m2street_2.value;
    f.pcity_2.value = f.city_2.value;
 f.pstate_2.value = f.state_2.value;
 f.ppostal_2.value = f.postal_2.value;
  }
}
        </script>
        
<div class="clearfix">
 <input type="checkbox" name="billingtoo_2" onclick="FillBilling_2(this.form)" id="chbSame">
 <em>Check this box if Physical Address and Mailing Address are the same.</em>
</div>


        
<div class="clearfix">
 <label for="pstreet_2">Physical Address 1:</label>
 <input name="pstreet_2" type="text" maxlength="120"  onfocus="geolocate2()"  id="autocomplete2"  size="53"  />
</div> 

<div class="clearfix">
 <label for="p2street_2">Physical Address 2:</label>
 <input name="p2street_2" type="text" maxlength="120"  size="53"  id="route2"  />
</div>
        
<div class="clearfix">
 <label for="pcity_2">City:</label>
 <input name="pcity_2" type="text" maxlength="50"  size="30"  id="locality2"  />
    
    <div class="clearfix">
     <label for="pstate_2">State:</label>
     <input type="text" name="pstate_2"  id="administrative_area_level_12" size="8" maxlength="12">
    </div>
        
        <div class="clearfix">
 <label for="pstreet_2">Zip Code:</label>
 <input name="ppostal_2" type="text" maxlength="12"  size="8"  id="postal_code2"  />
</div>​

我们能做的第一件事就是清理你的 javascript。看起来您的页面每一行都有一个单独的 javascript,没有必要。

就像冷聚变一样,你不能说#form.static_and_#variable##,你可以做数组表示法:#form["static_and_" & variable]#。在 javascript 你可以做 object["static_and_" + variable].

您的页面只需要这个脚本一次——所以将它放在循环之外。我们现在将一个 n 变量传递给它。

<script type="text/javascript">
    function FillBilling(f,n) {
        if(f["billingtoo_" + n].checked == true) {
            f["pstreet_" + n].value = f["street_" + n].value;
            f["p2street_" + n].value = f["m2street_" + n].value;
            f["pcity_" + n].value = f["city_" + n].value;
            f["pstate_" + n].value = f["state_" + n].value;
            f["ppostal_" + n].value = f["postal_" + n].value;
        }
    }
</script>

正如 Leigh 所指出的那样,您绝对应该使用 getElementByID() 或什至合理处理向后兼容性的库(对不起 Netscape 3,您运气不好)(例如 jQuery ).

<script type="text/javascript">
    function FillBilling(f,n) {
        if(f.getElementByID("billingtoo_" + n).checked == true) {
            f.getElementByID("pstreet_" + n.value = f.getElementByID("street_" + n).value;
            // ...
        }
    }
</script>

然后复选框调用这样的函数。请注意 cfoutput 如何包装整个标签。这样做真的没有什么害处,而且让事情变得更加清晰,不是吗?此外,一些所见即所得的编辑器/代码格式化程序不接受嵌套在标签中的 cf 标签。

事实上,我真的很难阅读你的 javascript 的所有 cf 输出。将 # 转义为 ## 的需要实际上根本不是什么大问题。

<cfoutput><input type="checkbox" name="billingtoo_#Add#" onclick="FillBilling(this.form,'#Add#')" id="billingtoo_#add#"></cfoutput>

就我个人而言,我尽可能多地包装在 cfoutputs 中。我不会只包装复选框。

在您的代码中,您似乎在命名您未使用的 ID,但您的元素共享相同的 ID。这可能会给您带来问题,dom 中的每个元素在技术上都需要自己的 ID(虽然如果您有冲突它通常可以正常工作,但当您试图通过 ID 引用)。

您可以为元素赋予与名称属性相同的值,我觉得这很方便。我不需要记住元素的两个不同名称。所以你可以拥有:

<input type="text" name="searchbox" id="searchbox" />

如果我对问题的理解是正确的,那么您是在尝试根据输入的计数动态填充输入字段。为此,您需要将 html 填充代码移动到它自己的函数中:

function populateInputs(repeatCount) {
    for (i = 1; i <= repeatCount; i++) {
        var myHtml = '<div class="clearfix">' 
        .
        .
        .
        $('body').append(myHtml);
    }
}

然后,只要你想填充它就调用这个函数:

$(document).ready(function () {
    $('#go').on('click', function () {
        populateInputs($('#repeatCount').val());
    });
});

这里是 fiddle:http://jsfiddle.net/gettgpmj/4/

将常量 id 赋予使用循环创建的元素是个坏主意。在下面的代码片段中,我为元素 autocompleteautocomplete2 生成了唯一的 id(我已将 autocomplete2 重命名为 auto2complete)。为了初始化每个自动完成元素,使用了数组。

现在在 JavaScript 中使用 ColdFusion 变量进行循环,设置 totalLoops 如:

<cfoutput>
    <script>
        var totalLoops = #add#;
        /*rest of the code*/
    </script>
</cfoutput>

请注意,如果您的脚本嵌套在 <cfoutput>.

中,则不能在 <script> 中使用 jQuery id 选择器 #

var totalLoops=5;
    for (i = 0; i < totalLoops; i++) {          
        var myHtml = '<div class="clearfix">'
            + '   <label for="street_' + i + '">Mailing Address 1 ' + i + ':</label>'
            + '   <input type="text" id="autocomplete'+i+'" name="street_'+i+'" onFocus="geolocate()" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <label for="m2street_'+i+'">Mailing Address 2 '+i+':</label>'
         + '   <input type="text" name="m2street_'+i+'" id="route'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <label for="city_'+i+'">City: '+i+':</label>'
         + '   <input type="text" name="city_'+i+'" id="locality'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <label for="state_'+i+'">State: '+i+':</label>'
         + '   <input type="text" name="state_'+i+'" id="administrative_area_level_1'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="postal_'+i+'">Zip Code: '+i+':</label>'
         + '   <input type="text" name="postal_'+i+'" id="postal_code'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <input type="checkbox" name="billingtoo_'+i+'" id="chbSame" onclick="FillBilling_'+i+'(this.form)">'
            + '<em>Check this box if Physical Address and Mailing Address are the same.</em>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="pstreet_' + i + '">Physical Address 1 ' + i + ':</label>'
            + '   <input type="text" id="auto2complete'+i+'" name="pstreet_'+i+'" onFocus="geolocate2()" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <label for="p2street_'+i+'">Physical Address 2 '+i+':</label>'
         + '   <input type="text" name="p2street_'+i+'" id="route2'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
         + '   <label for="pcity_'+i+'">City: '+i+':</label>'
         + '   <input type="text" name="pcity_'+i+'" id="locality2'+i+'" value="">'
            + '<div class="clearfix">'
         + '   <label for="pstate_'+i+'">State: '+i+':</label>'
         + '   <input type="text" name="pstate_'+i+'" id="administrative_area_level_12'+i+'" value="">'
            + '</div>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="ppostal_'+i+'">Zip Code: '+i+':</label>'
         + '   <input type="text" name="ppostal_'+i+'" id="postal_code2'+i+'" value="">'
            + '</div>'
            + '<br />';
        $('body').append(myHtml);
    }

var placeSearch; 
var autocomplete = new Array();
var auto2complete = new Array();
var componentForm = new Array();
var componentForm2 = new Array();
for (i = 0; i < totalLoops; i++) {
    componentForm[i] = {
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      postal_code: 'short_name'
    };

    componentForm2[i] = {
      route2: 'long_name',
      locality2: 'long_name',
      administrative_area_level_12: 'short_name',
      postal_code2: 'short_name'
    };
}

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  for (i = 0; i < totalLoops; i++) {
   (function(i){
     autocomplete[i] = new google.maps.places.Autocomplete(
     /** @type {HTMLInputElement} */
     (document.getElementById('autocomplete'+i)), {
       types: ['geocode']
     });
     auto2complete[i] = new google.maps.places.Autocomplete(
     /** @type {HTMLInputElement} */
     (document.getElementById('auto2complete'+i)), {
       types: ['geocode']
     });
   // When the user selects an address from the dropdown,
   // populate the address fields in the form.
   google.maps.event.addListener(autocomplete[i], 'place_changed', function() {
     fillInAddress(i);
   });
   google.maps.event.addListener(auto2complete[i], 'place_changed', function() {
     fillInAddress2(i);
   });
 }(i));
  }
}

// [START region_fillform]
function fillInAddress(idx) {
  // Get the place details from the autocomplete object.
 
  var place = autocomplete[idx].getPlace();

  for (var component in componentForm[idx]) {
    document.getElementById(component+idx).value = '';
    document.getElementById(component+idx).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[idx][addressType]) {
      var val = place.address_components[i][componentForm[idx][addressType]];
      document.getElementById(addressType+idx).value = val;
    }
  }
  //var keys=[];for (var key in place.address_components[0]) keys.push(key);
  //alert(keys):
  document.getElementById('autocomplete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete').value : '');*/
  document.getElementById('route'+idx).value = '';
}

function fillInAddress2(idx) {
    // Get the place details from the autocomplete object.
    var place = auto2complete[idx].getPlace();

    for (var component in componentForm2[idx]) {

      document.getElementById(component+idx).value = '';
      document.getElementById(component+idx).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm2[idx][addressType+'2']) {
        var val = place.address_components[i][componentForm2[idx][addressType + '2']];
        document.getElementById(addressType + '2'+idx).value = val;
      }
    }
  document.getElementById('auto2complete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route2').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete2').value : '');*/
  document.getElementById('route2'+idx).value = '';
}
  // [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
        position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

function geolocate2() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete2.setBounds(circle.getBounds());
      });
    }
  }
  // [END region_geolocation]
initialize();

document.querySelector('#chbSame').addEventListener('change', checkedAddr);


function checkedAddr() {
  if (document.getElementById('chbSame').checked) {
    document.getElementById('route2').value = document.getElementById('route').value;
    document.getElementById('locality2').value = document.getElementById('locality').value;
    document.getElementById('administrative_area_level_12').value = document.getElementById('administrative_area_level_1').value;
    document.getElementById('postal_code2').value = document.getElementById('postal_code').value;
    
document.getElementById('auto2complete').value = document.getElementById('autocomplete').value;
  } else {
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>

编辑:片段已更新,以便自动填充城市、州、邮政编码。