2012-01-12 22 views
1

我正在編寫一個工具,它接收用戶輸入的地址並將其轉換爲GoogleMaps'api的地理位置。使用jquery訪問表單中的值的問題

編輯:我確實想提交表單數據,但..我想。我不確定是否需要提交表單,但最終結果是它應該在包含title,addressgeo值的wordpress中生成一個帖子。

如果刪除<form></form>標籤,則由提交按鈕調用的方法將正常工作。如果<form>標籤位於表單的附近,該方法仍將被調用,但不會對任何內容進行地址解析。我錯誤地設置了我的表單嗎?

下面的形式:

$title = $_POST['title']; 
$address = $_POST['address']; 

$new_post = array(
    'post_title' => $title, 
    'post_content' => 'This is my post.', 
    'post_status' => 'publish', 
    'post_type' => 'post', 
    'address' => $address, 
    'geo' => $geo, 
); 

$post_id = wp_insert_post($new_post); 

update_post_meta($post_id, 'address', $address, true); 
update_post_meta($post_id, 'geo', $geo, true); 

?> 

<?php get_header()?> 

    <label>Event: </label><input id="title" type="text"/> 
    <label>Address: </label><input id="address" type="text"/> 
    <div id="map_canvas" style="width:500px; height:500px"></div><br/> 
    <label>latitude: </label><input id="latitude" type="text"/><br/> 
    <label>longitude: </label><input id="longitude" type="text"/><br/> 
    <input type="submit" id="compute" onClick="getCoordinates()" value="lets try it"> 

    <input type="hidden" name="action" value="new_post" /> 
    <?php wp_nonce_field('new-post'); ?> 


<?php get_footer()?> 

下面是相關功能:

function getCoordinates() { 
//variables are set up on page initialization 
    geocoder.geocode({ 'address': $('#address').val() }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 
     alert ('latitude: ' + results[0].geometry.location.lat() + ' longitude: ' + results[0].geometry.location.lng()); 
     $('#latitude').val(results[0].geometry.location.lat()) ; 
     $('#longitude').val(results[0].geometry.location.lng()) ; 
     $geo = results[0].geometry.location.lat() + "," + results[0].geometry.location.lng(); 
     var marker = new google.maps.Marker({ 
     map: map, 
     position: results[0].geometry.location 

     }); 
     } 
     }); 
} 

回答

0

變化從類型輸入按鈕=「提交」,鍵入=「按鈕」,並留下了形式的標籤關閉。當您想要實際提交表單時,您只能使用帶有提交按鈕的表單,而不是執行僅用於JavaScript的操作。

0

當使用元素時,最好將此地理編碼功能綁定到onsubmit event

<form onsubmit="getCoords()"> 
...fields... 
</form> 
<script> 
function getCoords(){ 

geocoder.makeALongRequest("some","params",function(result,data,xhr){ 
    alert("this is the request callback"); 
    }); 

//Always return false in the onsubmit event if you want to stop the browser from trying to POST anything 
return false; 
} 
+0

好吧,我不應該去洗手間中間答案顯然。好吧。 – winfred 2012-01-12 04:08:18