[英]Can't set value for hidden field in form
我正在嘗試在Rails 3的表單中為隱藏字段設置值。
但是,當我將表單提交到數據庫時,沒有為這些字段編寫任何內容。
有我的JS:
function getGeocode() {
geocoder = new google.maps.Geocoder();
var street = $("#player_street").val()
var postalcode = $("#player_postalcode").val()
var city = $("#player_city").val()
var address = street + ", " + postalcode + ", " + city
var lat
var lng
//console.log(address)
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.hb
lng = results[0].geometry.location.ib
$("#player_lat").val(lat)
$("#player_lng").val(lng)
return true
} else {
return false
alert("Dein Player konnte nicht eingetragen werden, bitte probiere es noch einmal.");
}
})
}
當我將getGeocode()的returnvalue設置為false時,將設置隱藏字段的值。 但是,當我將returnvalue設置為true時,沒有數據庫條目。
這些字段已設置並在模型中工作,並且可以通過form_for幫助器的onsubmit方法訪問該函數。
有人知道如何解決這個問題嗎?
由於您使用的是jQuery,請使用:hidden
jQuery選擇器。
var street = $("#player_street:hidden").val()
geocoder.geocode( ...
是異步函數。 因此,它會在一段時間后接收響應並為字段設置值,而getGeocode()
函數的其余代碼將繼續運行。
如果您在函數中返回true
,則在地理編碼器返回結果之前提交表單。 如果返回false
,則會取消提交並設置值。
因此,您需要在回調中提交數據,例如:
$(#the_form_id).submit( function() {
geocoder = new google.maps.Geocoder();
var street = $("#player_street").val()
var postalcode = $("#player_postalcode").val()
var city = $("#player_city").val()
var address = street + ", " + postalcode + ", " + city
var lat
var lng
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.hb
lng = results[0].geometry.location.ib
$("#player_lat").val(lat)
$("#player_lng").val(lng)
$(#the_form_id).unbind('submit').submit();
} else {
return false
alert("Dein Player konnte nicht eingetragen werden, bitte probiere es noch einmal.");
}
});
return false;
})
為了防止該方法提交,我添加了ev.preventDefault()並在用$(“#new_player”)。unbind('submit')。submit()設置值后恢復該方法。
$("#new_player").submit( function(ev) {
ev.preventDefault();
geocoder = new google.maps.Geocoder();
var street = $("#player_street").val()
var postalcode = $("#player_postalcode").val()
var city = $("#player_city").val()
var address = street + ", " + postalcode + ", " + city
var lat
var lng
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.hb
lng = results[0].geometry.location.ib
$("#player_lat:hidden").val(lat)
$("#player_lng:hidden").val(lng)
$("#new_player").unbind('submit').submit()
} else {
alert("Dein Player konnte nicht eingetragen werden, bitte probiere es noch einmal.")
return false
}
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.