AJAX応答によって値が更新される非表示のテキストフィールドがあります。
<input type="hidden" value="" name="userid" id="useid" />
この値が変更されたときに、AJAXリクエストを発行したいと思います。誰でも変更を検出する方法についてアドバイスできますか?
次のコードがありますが、値を探す方法がわかりません。
$('#userid').change( function() {
alert('Change!');
})
AJAX応答によって値が更新される非表示のテキストフィールドがあります。
<input type="hidden" value="" name="userid" id="useid" />
この値が変更されたときに、AJAXリクエストを発行したいと思います。誰でも変更を検出する方法についてアドバイスできますか?
次のコードがありますが、値を探す方法がわかりません。
$('#userid').change( function() {
alert('Change!');
})
回答:
これはかなり遅いですが、このスレッドに出くわした人に役立つように、答えを見つけました。
非表示の要素の値が変更されても、.change()イベントは自動的に発生しません。したがって、その値を設定している場合はどこでも、jQueryにトリガーするように指示する必要があります。
function setUserID(myValue) {
$('#userid').val(myValue)
.trigger('change');
}
そうなれば、
$('#userid').change(function(){
//fire your ajax call
})
期待どおりに動作するはずです。
.trigger()だけで呼び出す以上使用することが一般的により良いですかchange()?
changeイベントと同じように動作させるには、コードを追加しsetUserID()て、値が実際に変更されているかどうかを確認する必要があります。if ($('#userid').val() != myVaule) { // set val() and trigger change }
非表示の入力は変更時に「変更」イベントをトリガーしないため、代わりにMutationObserverを使用してこれをトリガーします。
(非表示の入力値の変更は、変更できない他のスクリプトによって行われる場合があります)
これはIE10以下では機能しません
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var trackChange = function(element) {
var observer = new MutationObserver(function(mutations, observer) {
if(mutations[0].attributeName == "value") {
$(element).trigger("change");
}
});
observer.observe(element, {
attributes: true
});
}
// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );
input[type=hidden]
trigger('change')、私はCustomEventを作成しましたので、それを登録してから、私のために仕事をしませんでしたelement.dispatchEvent(myCustomEvent)
以下の関数を使用するだけで、type要素を変更することもできます。
$("input[type=hidden]").bind("change", function() {
alert($(this).val());
});
非表示要素の値が変更されても、.change()イベントは自動的に発生しません。したがって、その値を設定している場合はどこでも、jQueryにトリガーするように指示する必要があります。
HTML
<div id="message"></div>
<input type="hidden" id="testChange" value="0" />
ジャバスクリプト
var $message = $('#message');
var $testChange = $('#testChange');
var i = 1;
function updateChange() {
$message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');
}
$testChange.on('change', updateChange);
setInterval(function() {
$testChange.val(++i).trigger('change');;
console.log("value changed" +$testChange.val());
}, 3000);
updateChange();
期待どおりに動作するはずです。
$('#userid').change(function(){
//fire your ajax call
});
$('#userid').val(10).change();
Object.defineProperty()入力要素の「値」プロパティを再定義し、その変更中に何かを行うために使用できます。
Object.defineProperty() プロパティのゲッターとセッターを定義して、それを制御できるようにします。
replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) {
console.log("new value:", value)
});
function replaceWithWrapper(obj, property, callback) {
Object.defineProperty(obj, property, new function() {
var _value = obj[property];
return {
set: function(value) {
_value = value;
callback(obj, property, value)
},
get: function() {
return _value;
}
}
});
}
$("#hid1").val(4);
この例では、非表示のドラフトフィールドが値を変更するたびに、ドラフトフィールドの値を返します(Chromeブラウザー)。
var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];
observeDOM(h, 'n', function(draftValue){
console.log('dom changed draftValue:'+draftValue);
});
var observeDOM = (function(){
var MutationObserver = window.MutationObserver ||
window.WebKitMutationObserver;
return function(obj, thistime, callback){
if(typeof obj === 'undefined'){
console.log('obj is undefined');
return;
}
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){
callback('pass other observations back...');
}else if(mutations[0].attributeName == "value" ){
// use callback to pass back value of hidden form field
callback( obj.value );
}
});
// have the observer observe obj for changes in children
// note 'attributes:true' else we can't read the input attribute value
obs.observe( obj, { childList:true, subtree:true, attributes:true });
}
};
})();
オフ構築Viktarの答えは、ここであなたが入力要素の値が変更されるたびに、その後の変更イベントGETは解雇することを確実にするために与えられた隠されたinput要素の後に呼び出すことができます実装です:
/**
* Modifies the provided hidden input so value changes to trigger events.
*
* After this method is called, any changes to the 'value' property of the
* specified input will trigger a 'change' event, just like would happen
* if the input was a text field.
*
* As explained in the following SO post, hidden inputs don't normally
* trigger on-change events because the 'blur' event is responsible for
* triggering a change event, and hidden inputs aren't focusable by virtue
* of being hidden elements:
* https://stackoverflow.com/a/17695525/4342230
*
* @param {HTMLInputElement} inputElement
* The DOM element for the hidden input element.
*/
function setupHiddenInputChangeListener(inputElement) {
const propertyName = 'value';
const {get: originalGetter, set: originalSetter} =
findPropertyDescriptor(inputElement, propertyName);
// We wrap this in a function factory to bind the getter and setter values
// so later callbacks refer to the correct object, in case we use this
// method on more than one hidden input element.
const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
return {
set: function(value) {
const currentValue = originalGetter.call(inputElement);
// Delegate the call to the original property setter
_originalSetter.call(inputElement, value);
// Only fire change if the value actually changed.
if (currentValue !== value) {
inputElement.dispatchEvent(new Event('change'));
}
},
get: function() {
// Delegate the call to the original property getter
return _originalGetter.call(inputElement);
}
}
})(originalGetter, originalSetter);
Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};
/**
* Search the inheritance tree of an object for a property descriptor.
*
* The property descriptor defined nearest in the inheritance hierarchy to
* the class of the given object is returned first.
*
* Credit for this approach:
* https://stackoverflow.com/a/38802602/4342230
*
* @param {Object} object
* @param {String} propertyName
* The name of the property for which a descriptor is desired.
*
* @returns {PropertyDescriptor, null}
*/
function findPropertyDescriptor(object, propertyName) {
if (object === null) {
return null;
}
if (object.hasOwnProperty(propertyName)) {
return Object.getOwnPropertyDescriptor(object, propertyName);
}
else {
const parentClass = Object.getPrototypeOf(object);
return findPropertyDescriptor(parentClass, propertyName);
}
}
このように準備ができたドキュメントでこれを呼び出します:
$(document).ready(function() {
setupHiddenInputChangeListener($('myinput')[0]);
});
このスレッドは3年前のものですが、これが私の解決策です:
$(function ()
{
keep_fields_uptodate();
});
function keep_fields_uptodate()
{
// Keep all fields up to date!
var $inputDate = $("input[type='date']");
$inputDate.blur(function(event)
{
$("input").trigger("change");
});
}