web-dev-qa-db-ja.com

入力がプログラムで変更されたときに、変更時の解決策は機能しません

私はすでに読んでいます なぜonchangeはうまくいかないのですか? そして今、私はそれを知っています。

Onchangeイベントは、ユーザーが入力の値を変更した場合にのみ発生します。 入力がプログラム的に変更された場合は発火することはありません

しかし、私はユーザーがウェブサイト内のGoogle Mapウィジェットによる場所をユーザーに変更するときに自動的に埋められる入力フィールドを持っています。それが起こると、その自動充填値を取得し、別の入力を提出する別の入力を埋めます。 入力がプログラムで変更されたときに機能を検出または発射する方法はありますか?

入力のvalueプロパティの設定機能を上書きすることでこれを達成できます。だから誰でもvalueプログラムであなたのオーバーライデンのセッターがトリガされます。

const input = document.getElementById('input');

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');

Object.defineProperty(input, 'value', {
    set: function(t) {
        console.log('Input value was changed programmatically');
        return descriptor.set.apply(this, arguments);
    },
    get: function() {
      return descriptor.get.apply(this);
    }
});

function changeInput() {
  input.value += '1';
} _
<input id="input">
<button onclick="changeInput()">Change</button> _
1
Kirill Simonov

イベントをプログラムでトリガするには、イベントAPIを使用できます. https://developer.mozilla.org/fr/docs/web/api/eventtarget/dispatchevent

全例:

let input = document.getElementById('a')

// Listen the event
input.addEventListener('change', function (evt) {
   console.log('onchange event listener')
});

input.onchange = () => {
console.log('onchange callback')
}

setTimeout(() => {
input.value = "myvalue"

// Trigger the event
var event = new Event('change');
input.dispatchEvent(event);

}, 1000) _
<input id="a"> _
0
Alex83690

ユーザーがGoogle Mapウィジェットでロケーションを変更したときの問題の解決策として、PROGRATECTLLYを設定してから入力変更イベントを起動します。$("#field-id").trigger("change");を呼び出して手動で起動します。

たとえば、Googleマップコードがこのようなものである場合関数のコードを確認してくださいmarkerLocation

HTML:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
          #map{ width:700px; height: 500px; }
        </style>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <title>Save Marker Example</title>
    </head>
    <body>
        <h1>Select a location!</h1>
        <p>Click on a location on the map to select it. Drag the marker to change location.</p>

        <!--map div-->
        <div id="map"></div>

        <!--our form-->
        <h2>Chosen Location</h2>
        <form method="post">
            <input type="text" id="lat" ><br>
            <input type="text" id="lng" >
        </form>

        <script type="text/javascript" src="map.js"></script>
    </body>
</html>
 _

JS:

//map.js

//Set up some of our variables.
var map; //Will contain map object.
var marker = false; ////Has the user plotted their location marker? 

//Function called to initialize / create the map.
//This is called when the page has loaded.
function initMap() {

    //The center location of our map.
    var centerOfMap = new google.maps.LatLng(52.357971, -6.516758);

    //Map options.
    var options = {
      center: centerOfMap, //Set center.
      zoom: 7 //The zoom value.
    };

    //Create the map object.
    map = new google.maps.Map(document.getElementById('map'), options);

    //Listen for any clicks on the map.
    google.maps.event.addListener(map, 'click', function(event) {                
        //Get the location that the user clicked.
        var clickedLocation = event.latLng;
        //If the marker hasn't been added.
        if(marker === false){
            //Create the marker.
            marker = new google.maps.Marker({
                position: clickedLocation,
                map: map,
                draggable: true //make it draggable
            });
            //Listen for drag events!
            google.maps.event.addListener(marker, 'dragend', function(event){
                markerLocation();
            });
        } else{
            //Marker has already been added, so just change its location.
            marker.setPosition(clickedLocation);
        }
        //Get the marker's location.
        markerLocation();
    });
}

//This function will get the marker's current location and then add the lat/long
//values to our textfields so that we can save the location.
function markerLocation(){
    //Get location.
    var currentLocation = marker.getPosition();
    //Add lat and lng values to a field that we can save.
    $("#lat").value = currentLocation.lat(); //latitude
    //fire the change event of the input lat field
    $("#lat").trigger("change");

    $("#lng").value = currentLocation.lng(); //longitude
    //fire the change event of the input lng field
    $("#lng").trigger("change");
}


//Load the map when the page has finished loading.
google.maps.event.addDomListener(window, 'load', initMap);
 _

入力タグの値をプログラムで変更するために、triggersを使用することができます。

$(document).on('mytrigger keyup', '#input_num', function() {
  var value = $('#input_num').val();
  //alert(value);
  $('#result').val(value)
})

function external_modifier(){
  setTimeout(function(){
    var intValue = parseInt($('#input_num').val(), 10);
    $('#input_num').val(intValue+1).trigger("mytrigger");
    //alert(intValue);
    external_modifier();
  }, 3000);
}

external_modifier(); _
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<lable> Input: </lable><input id='input_num' type=text value=1 />

<br><br>

<lable> Result: </lable><input id='result' type=text disabled /> _
0
Rohit