Onchange of a input field changed by Javascript - javascript

I have a input field type="hidden" which is changed by javascript itself.
When this field changes i want an event/function to be triggered.
Tried this:
$(".product_id").on("change paste keyup input", function(event){alert('1');});
$(".product_id").blur(function(event){alert('1');});
$(".product_id").keypress(function(event){alert('1');});
But it does not seem to work as the value is changed by other JavaScript file itself.
I cannot change or add to the existing JavaScript.
I cannot add anything to the input field.

You can use jQuery's trigger method & change event.
Changes in value to hidden elements don't automatically fire the .change() event. So, as soon as you change the hidden inputs, you should tell jQuery to trigger it using .trigger('change') method.
You can do it like this:
$(function() {
$("#field").on('change', function(e) {
alert('hidden field changed!');
});
$("#btn").on('click', function(e) {
$("#field").val('hello!').trigger('change');
console.log('Hidden Filed Value: ' + $('#field').val());
});
console.log('Hidden Filed Value: ' + $('#field').val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="field" type="hidden" name="name">
<button id="btn">
Change Hidden Field Value
</button>
Hope this helps!

It's just a hack if you can't trigger change event from sources.
May not be a good solution with setInterval(). But helps in the cases where you can't trigger change event from sources which are changing the hidden input value.
$("#input")[0].oninput = function(){
$("#hidden").val($(this).val()); //setting hidden value
}
var oldVal = $("#hidden").val();
setInterval(function(){ //listening for changes
var newVal = $("#hidden").val();
if(newVal !== oldVal){
console.log(newVal);
oldVal = newVal;
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hidden">
<input type="text" id="input">

var element = $(".product_id");
element.on("change", function(){
alert('hey');
}).triggerHandler('change');
and we need to trigger it programmatically like:
$('.product_id').val('abcd').triggerHandler('change');

Related

What event is used when the input value is not blank

I need to enable/disable a button based on a input field. If the input field has a value, the button should be enabled. If the input field is empty, the button should be disabled. Now when the user selects a value from the input field cookie, How do I capture? I tried with "change" but it didn't work.
The tried the below code with "change" event:
<script>
$(function() {
$("#myInput").change(showSaveBtn);
var showSaveBtn = function() {
validateInput();
if (myInputEntered== true) {
$('#save').removeClass("disabled").prop(
'disabled', "disabled").removeAttr("disabled");
} else {
$('#save').addClass("disabled").prop(
'disabled', "disabled");
}
}
var validateInput= function() {
if ($.trim($("#myInput").val()) === '')
myInputEntered= false;
else
myInputEntered= true;
}
});
</script>
Based on #myInput value, I need to enable/ disable #save button.
Looking forward for the answers.
thanks,
Iswarya
$("#save").prop('disabled', true);
$("#myinput").on('change keydown paste input propertychange click keyup blur', function(){
$("#save").prop('disabled', $('#myinput').val().length>0? false:true);
})
<input type="text" id="myinput">
<button id="save">
save
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
you can write it like this too. hope this will help you. here is jsfiddle link
It is very likely that by the time you hook the event, the DOM element was not loaded. You need to wait until the DOM is loaded to hook the events.
$(document).ready(function(){
var inputChanged = function() {
var myInputEntered = validateInput();
console.log(myInputEntered);
if (!myInputEntered)
$('#save').hide()
else
$('#save').show();
}
var validateInput= function() {
return $.trim($("#myInput").val()) !== ''
}
$("#myInput").keyup(inputChanged);
inputChanged();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput">
<input type="button" value="save" id="save">

How to get the value of the text box using jQuery on keypress

I want a functionality that i will type some text on the textbox and the value will be picked up by the jquery and will be stored in some variable ,how to achieve that? i am using jquery bind function but it is not suiting my purpose .
This is my textbox
<aui:input inlineField="true" label="" name="interviewCC" id="interviewCC" size="45" value=""></aui:input>
and i am using this jQuery function
$("#interviewCC").bind("click", function () {
value = $("#interviewCC").val();
alert(value)
});
but it is not picking the value i want that when i will type something on the textbox that value will be picked up.Please somebody help.
The problem is that you listen to the 'click' event and not the 'keypress' event.
Try this:
$('#interviewCC').keypress( function(e) {
var value = $("#interviewCC").val();
alert(value)
});
Use
$("#interviewCC").keypress(function () {
value = $("#interviewCC").val();
alert(value);
});
You can use the jQuery function .keyup() which will figure out when a key has been pressed and then the press has finished.
$(document).ready(function() {
$('input#text').keyup(function() {
$('.output').text($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="text" type="text" />
<div class="output"></div>
.keyup() Documentation

Add an onchange event listener to an html input field

I would like to add an onchange event to those input fields without jquery:
<input type="text" id="cbid.wizard.1._latitude">
<input type="text" id="cbid.wizard.1._longitude">
I can already call the object with
<script type="text/javascript">
alert(document.getElementById('cbid.wizard.1._latitude').id);
</script>
In the end, I want to add this behaviour, that if you enter a pair of coordinates into the first input, I will spread the pair over the two input fields?
How do I add an onchange event with javascript?
Ummm, attach an event handler for the 'change' event?
pure JS
document.getElementById('element_id').onchange = function() {
// your logic
};
// or
document.getElementById('element_id').addEventListener(
'change',
callbackFunction,
false
);
jQuery
$('#element_id').change(function() {
// your logic
});
Note
Note, that change event on the text field will be fired after the blur event. It's possible that your looking for keypress event's or something like that.
document.getElementById('cbid.wizard.1._latitude').onchange = function(){
//do something
}
GlobalEventHandlers.onchange docs
or
document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
//do something
});
EventTarget.addEventListener docs
use addEventListener in your window.onload
window.onload=function(){
document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
//do something
});
};
addEventListener
Please try with the below code snippet.
<body>
<input type="text" id="cbid.wizard.1._latitude">
<input type="text" id="cbid.wizard.1._longitude">
<script type="text/javascript">
var txt1 = document.getElementById('cbid.wizard.1._latitude');
txt1.addEventListener('change', function () { alert('a'); }, false);
</script>
</body>

jQuery, how to capture when text input has changed as a result of another event

I have a text input that is updated as a result of a button event. I would like to detect when the value in the text input has changed. See the example below:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').bind("input change paste", function(){
console.log("text changed");
// do something
});
$('#click').click (function(){
$('#text').val('something');
});
});
</script>
<body>
<input id='text' type='text'>
<input id='click' type='button' value='click'>
</body>
Later on, that button will trigger a calender so the user select a date/time which will update the text input. Since the calender is part of a library we I don't want to change it. I would like to detect when the text field gets a new value.
thanks!
I think what you're referring to is
$("#text").on("change", function(){});
take a look at this post
Since the date/time picker library you are using doesn't raise any sort of change or input event, the only way to reliable tell if the value has changed is to watch with a timer and raise the change event yourself. The following is one way to do this:
// check for changes every 100 ms
setInterval(function() {
var lastVal = $('#text').data('last-value');
if (typeof lastVal === 'undefined') {
lastVal = $('#text').val();
$('#text').data('last-value', lastVal);
}
if (lastVal !== $('#text').val()) {
$('#text').change(); // trigger the change event
}
}, 100);
// setup your change handler
$('#text').on("input change paste", function() {
// before doing anything else, set the last-value data property
$('#text').data('last-value', $('#text').val());
// do something ...
console.log('changed!');
});
// now programmitically updating the $('#text') element will result
// in your change handler being triggered
$('#click').click (function(){
$('#text').val('something');
});

Proper handling of input change event

It may be a correct behavior of change event, but the below behavior is bit annoying. When the value is updated from the field history (see explanation below), the event is not triggered.
Please see example code below. the result input field is updated with the change in input field 'input1'. The form and submit button is not fully relevant, but needed to submit a form to make the browser keep the history of field values.
To test:
enter any input in the field (say ABC)
Submit the form
enter first character of input from 1 (A)
use the down arrow to select the previous value + Enter
or use the mouse to select the previous value from the history
No input change is detected.
Which event/ how should this code should modify so that an event is generated whenever the input value is changed.
thanks.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
Result:<input type="text" id="result" readonly></input>
<form method="post" action="">
<input type="text" id="input1" />
<button type=submit>Submit</button>
</form>
<script >
$(document).ready(function() {
$('#input1').change(
function(){
$('#result').val($('#input1').val());
});
});
</script>
</body>
</html>
I think this has nothing to do with jQuery.
A change event should be dispatched when the content of a control has changed and the control loses focus. In practice, the implementation of the change event is inconsistent in browsers, e.g. Firefox dispatches a change event when radio buttons are clicked on rather then when they lose focus. Also in IE, selecting a value from a list of previous values then causing a blur event doesn't fire a change event.
Note that for form controls to be successful, they must have a name attribute with a value. A simple test case is:
<form action="#">
<input type="text" name="input1" onchange="alert('changed');">
<input type="submit">
</form>
One solution is to use the blur event instead and compare the control's current value to its defaultValue - if they're different, perform whatever it is you were going to do for the change event. If the value may be changed a number of times, after the first time you need to compare with the last value onblur rather than the defaultValue.
Anyhow, here's a function that can be called onblur to see if a text input has changed. It needs a bit of work if you want to use it with other types of form control, but I don't think that's necessary.
<form action="#">
<input type="text" name="input1" onblur="
var changed = checkChanged(this);
if (changed[0]) {
alert('changed to: ' + changed[1]);
}
">
<input type="submit">
</form>
<script type="text/javascript">
// For text inputs only
var checkChanged = (function() {
var dataStore = [];
return function (el) {
var value = el.value,
oValue;
for (var i=0, iLen=dataStore.length; i<iLen; i+=2) {
// If element is in dataStore, compare current value to
// previous value
if (dataStore[i] == el) {
oValue = dataStore[++i];
// If value has changed...
if (value !== oValue) {
dataStore[i] = value;
return [true, value];
// Otherwise, return false
} else {
return [false, value];
}
}
}
// Otherwise, compare value to defaultValue and
// add it to dataStore
dataStore.push(el, value);
return [(el.defaultValue != value), value];
}
}());
</script>
Try the keyup event:
$(document).ready(function() {
$('#input1').keyup(
function(){
$('#result').val($('#input1').val());
});
});
http://jsfiddle.net/kaptZ/7/
It seems like it's definitely a browser bug. Not much you can do besides implement your own change handler with focus and blur. This example is not very reusable, but it solved the problem and can be used as inspiration for something reusable.
http://jsfiddle.net/kaptZ/9/
var startValue;
var input1 = $('#input1');
input1.focus(function(){
startValue = this.value;
});
input1.blur(function(){
if (this.value != startValue) {
$('#result').val(this.value);
}
});
A dirty alternative is to use autocomplete="off"
It looks like this bug which was supposed to be fixed in November 2009.
In modern browsers you can use the input event and update as you type. It can be bound either to the text input:
$('#input1').bind('input', function(){
$('#result').val($('#input1').val());
});
Or to the form:
$('#input1').closest('form').bind('input', function(){
$('#result').val($('#input1').val());
});

Categories

Resources