Javascript 为 HTML 字段赋值

Javascript assign value to HTML field

本文关键字:赋值 字段 HTML Javascript      更新时间:2023-09-26

我正在尝试从JS脚本中保存HTML字段(供以后在表单中使用)。

这是代码:

形式

<form class="new_client" id="new_client" action="/clients" accept-charset="UTF-8" method="post">
      <div class="form-group">
        <input class="form-input" type="hidden" name="client[city]" id="client_city">
      </div>
      <div class="form-group">
        <input class="form-input" type="hidden" name="client[address]" id="client_address">
      </div>
      <div id="locationField">
        <input autocomplete="off" class="autocomplete" placeholder="Enter your address" type="text">
      </div>
      <div class="text-center">
        <button class="btn button-general ">Save</button>
      </div>
</form>

还有javascript:

function configureGeoAutocomplete(context) {
  if( context === undefined ) {
    context = $('body');
  }
  var element = context.find('.autocomplete')
  //It doesn't really matter what this line does, it's from Google Places API
  var autocomplete = new google.maps.places.Autocomplete(
      element[0], {types: ['geocode']});
  autocomplete.addListener('place_changed', fillInAddress)
}
function fillInAddress() {
  var client_address = autocomplete.getPlace().formatted_address;
  document.getElementById("client_address").value = client_address;
}

在加载表单所在的模态时查询 javascript

jQuery(function() {
  $('div.modal').on('loaded.bs.modal', function(e) {
    configureGeoAutocomplete(context);
  }
}

我想将该client_address保存到文本字段中,以便在提交表单时我可以拥有该信息。

听起来像

是 cookie 的绝佳候选者,如果你被允许使用它们:http://www.w3schools.com/js/js_cookies.asp。 另一个想法是在查询字符串中传递它。 它不是PII或类似的东西。 尝试在该输入上使用事件代码。 我不喜欢按"输入"!

onkeypress="if (event.keycode==13) { // do something }"

处理表单提交事件:

$(function() {
   $("#new_client").submit(function(e) {
      e.preventDefault();
      // This is your value stored in the field.
      $("#client_address").val();
   });
})

显然,出于某种原因,如果我按 ID 搜索元素,它不会保存字段上的信息。如果我按类搜索:

function fillInAddress() {
  var place = autocomplete.getPlace();
  $(".client-address").val(place.formatted_address);
}

它按预期工作。

相关文章: