【问题标题】:Problems accessing values in forms with jquery使用 jquery 访问表单中的值的问题
【发布时间】:2012-01-12 03:36:04
【问题描述】:

我正在编写一个工具,它接受用户输入的地址并将其转换为 GoogleMaps api 的地理位置。

编辑:我确实想提交表单数据,但.. 我想。我不确定是否需要提交表单,但最终结果是它应该在 wordpress 中生成包含titleaddressgeo 值的帖子。

如果删除<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

      });
      }
      });
}

【问题讨论】:

    标签: jquery forms wordpress geocoding


    【解决方案1】:

    将输入按钮从 type="submit" 更改为 type="button" 并关闭表单标签。当您想要实际提交表单时,您只能使用带有提交按钮的表单,而不是执行仅 javascript 操作。

    【讨论】:

      【解决方案2】:

      在使用元素时,最好将此地理编码函数绑定到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;
      }
      

      【讨论】:

      • 好吧,我显然不应该在回答中途去洗手间。哦,好吧。
      猜你喜欢
      • 2017-10-26
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      相关资源
      最近更新 更多