2016-02-26 52 views
0

我想從JS腳本中保存一個HTML字段(用於表單)。Javascript賦值給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保存到文本字段,以便在提交表單時可以獲得該信息。

+0

'js'的哪個部分不返回預期的結果? – guest271314

+0

我對js知之甚少,但在fillInAddress()函數中,第二行應該修改id爲client_address的HTML字段,或者至少這就是我想在那裏做的事情。 –

+0

on('loaded.bs.modal')變量中的上下文是否已初始化? – muuk

回答

0

顯然,出於某種原因,如果我搜查ID它不是節約領域的信息化的元素。如果我正在按級別搜索:

function fillInAddress() { 
    var place = autocomplete.getPlace(); 

    $(".client-address").val(place.formatted_address); 
} 

它按預期工作。

0

如果您允許使用它們,聽起來像是一個很好的cookie選擇:http://www.w3schools.com/js/js_cookies.asp。另一個想法是在查詢字符串中傳遞它。這不是PII或類似的東西。在該輸入上嘗試一個事件代碼。我不喜歡打「輸入」!

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

我正在查看cookie,但我不明白該怎麼做。表單提交後如何使用它。 –

+0

所以,如果你設置一個cookie值,像這樣:'setCookie(「client_address」,document.getElementById(「client_address」)value,30);''''''''''''var caddress = getCookie(「client_address」 );'30是直到該值過期的天數。我通常使用720,這給了我2年。 – WWPTV

+0

謝謝,但我需要做相反的事情,使「client_address」.value成爲我從autocomplete.GetPlace()獲得的內容。formatted_address –

0

處理表單提交事件:

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