Javascript事件监听器 - 由Javascript设置的“更改”值

时间:2015-11-03 21:52:51

标签: javascript jquery

我有一个流程,旨在将用户输入的单独地址字段连接到一个隐藏字段,以供Google地图用于删除该位置上的图钉。

负责连接的事件监听器运行正常,但是当我尝试将监听器链接到隐藏字段以执行引脚放置时,不执行该功能。

以下是我正在使用的代码:

$(document).ready(function initMap() {

    ...

    function join_address() {
        var address = document.getElementById('id_form5-address1').value;
        var city = document.getElementById('id_form5-city').value;
        var state = document.getElementById('id_form5-state').value;
        var zip = document.getElementById('id_form5-zip').value;
        document.getElementById('id_jointAddress').value = address+", "+city+", "+state+", "+zip;
        }

    document.getElementById("id_form5-city").addEventListener("change", join_address);
    document.getElementById("id_form5-state").addEventListener("change", join_address);
    document.getElementById("id_form5-zip").addEventListener("change", join_address);

    function codeAddress() {
        console.log("function engaged")
        var address = document.getElementById("id_jointAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    document.getElementById("id_jointAddress").addEventListener("change", codeAddress);

    ...

}

“函数参与”从不打印到控制台,所以我假设它是构造错误的侦听器,或者是在错误的位置。有人可以帮忙吗?

编辑:这是有问题的html对象:

<input type="hidden" name="jointAddress" id="id_jointAddress">

如果我取消隐藏元素,并直接键入字段,则会触发侦听器。我认为“更改”监听器不响应通过Javascript进行的更改。有谁知道一个对我有用的解决方案?

2 个答案:

答案 0 :(得分:1)

问题是以编程方式设置value不会触发更改事件。你可以发射synthetic event on your own。见http://jsfiddle.net/mendesjuan/uct8bL9d/2/

如果您使用fireEvent function I linked to,则只需在代码中添加以下行

即可
var joint = document.getElementById('id_jointAddress');   
joint.value = address + ", " + city + ", " + state + ", " + zip;
fireEvent(joint, 'change');

这是问题的减少:

document.querySelector('input').addEventListener('change', function() {
    document.getElementById('output').innerHTML +='changed <br />'; 
});

document.querySelector('button').addEventListener('click', function() {
    var input =  document.querySelector('input');
    input.value = new Date();
    fireEvent(input, 'change')
});

/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9){
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

     if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;

            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;

            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);

        var bubbles = eventName == "change" ? false : true;
        event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else  if (node.fireEvent) {
        // IE-old school style
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};
<input />
<button>Set programatically</button>

<div id="output"> </div>

答案 1 :(得分:0)

问题是以编程方式设置值不会触发更改处理程序。如果您使用jQuery并调用val(),那么它将触发一个合成更改事件。尝试更新您的JavaScript以使用jQuery。

$(function(){
    function initMap() {
        ...
    }

    function join_address() {
        var address = $('#id_form5-address1').val();
        var city = $('#id_form5-city').val();
        var state = $('#id_form5-state').val();
        var zip = $('#id_form5-zip').val();
        $('#id_jointAddress').val(address+", "+city+", "+state+", "+zip);
    }

    $("#id_form5-city").on("change", join_address);
    $("#id_form5-state").on("change", join_address);
    $("#id_form5-zip").on("change", join_address);

    function codeAddress() {
        console.log("function engaged")
        var address = $("#id_jointAddress").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    $("#id_jointAddress").on("change", codeAddress);
});