[英]Javascript assign value to HTML field
我正在嘗試從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,那么聽起來很適合使用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);
}
它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.