Jquery on Input not working on dynamically inserted value - javascript

I'm trying to alert a value using jquery when it is generated from a javascript code, the value is generated on the input box the problem is jquery cannot detect the changes, commands i tested are "change, input" but when i manually input a value jquery triggers
sample code:
value is dynamically generated on the javascript and pushed / inserted to the inputbox, the value is not manually generated
javascript:
document.getElementById("displayDID").value = DisplayName ;
html:
<input type="text" id="displayDID" />
jquery:
$('#displayDID').on("input" ,function() {
var work = $(this).val();
alert(work);
});
the value of the id="displayDID" changes but jquery cannot detect it after execution.
sample fiddle http://jsfiddle.net/SU7bU/1/

add trigger to it
$('#gen').on('click',function() {
$('#field').val('val').trigger("change");
});
$(document).on("change",'#field' ,function() {
var work = $(this).val();
alert(work);
});
http://jsfiddle.net/ytexj/

It is because you have added the script before input is ready.Due to which, event is not getting set on that element.write the code on document ready:
$(document).ready(function(){
$('#displayDID').on("input" ,function() {
var work = $(this).val();
alert(work);
});
})
or use event delegation:
$(document).on("input",'#displayDID' ,function() {
var work = $(this).val();
alert(work);
});

Ok I will propose you one answer and let's see if it solve your problem.
If you use keyup, and you insert 3350 value, you will display 4 alert, and I think you want to display only 1 alert.
$(document).ready(function() {
var interval;
$("#variazioneAnticipo").on("input", function() {
var variazioneAnticipo = $("#variazioneAnticipo").val();
clearInterval(interval);
interval = setTimeout(function(){ showValue(variazioneAnticipo) }, 1000);
});
});
function showValue(value) {
alert("ANTICIPO VARIATO: " + value);
}
<input id="variazioneAnticipo" class="rightAlligned form-control" style="width: 60%" type="number" step="0.01" min="0" value="3" />
I explain it, when you input anything into the input, will trigger a setTimeout in 1 sec, if you press another key under this time, we clear the timeOut and we triiger again, so you will only have 1 alert 1 sec after the last input insert.
I hope it helps you, and soyy for my english :D

Related

jquery event update input triggered on second click

I need to update input value from jquery ajax request and some other labels but the input is not updated only after the second click. I've searched for answer and i got that maybe the input lose foucs and when i click again the input is refocued again,but i can't figure out how to set foucs again on the input
Here is my code :
$(oe_website_sale).on('click', 'li.installment_term', function (ev) {
ev.preventDefault();
var term_id = $('li.installment_term.active').attr('id');
var $parent = $ul.closest('.js_product');
var price = $parent.find(".oe_price:first .oe_currency_value")[0].innerText;
var down_payment = $('input.down_payment');
ajax.jsonRpc('/calculate/term/load', 'call', {term_id, price})
.done(function (result) {
price_install.text(result.price_per_month);// This line is updating perfectly from the first click
down_payment.val(result.down_payment); // This line has now effect only after second click
down_payment.attr('min', result.down_payment);// This line is updating perfectly from the first click
});
});
and my html code :
<input type="number" name="down_payment" min="0" step="0.01"
class="form-control down_payment" value="0.00"/>

set value to a input and grab it on change or keyup

Check the html code bellow. The id foo input taking a text then cloning to another input id doo. As you can see in jquery code i am simply passing the value from foo to doo. But my problem is when i try to get value of doo on second part of code in jquery i dont get updated value of doo. Thing is that if i write input in foo then it virtually displays in doo but in real this not changing i think. So what i want is- when i pass input in foo it will also trigger in doo value. Since i am also updating doo from foo. Ask question if you want to know anything more. Thanks in advance
jsfiddle link
Jquery:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
});
$("#doo").on("change paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
Html:
<input type="text" id="foo" value=""><br>
<br>
<input type="text" id="doo" value=""><br>
The problem is that the functions are running at the same time and the value of doo hasn’t changed in time for the function. I would change your js code to this:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
$("#doo").on("paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
And then obviously run whatever you would run in both places where you have the var tryGetNewValue running
The change event does not get triggered because only input directly from the user into the element can set it off (see https://developer.mozilla.org/en-US/docs/Web/Events/change).
As for a way to allow this to work, you can use a function for each event like so:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
changeEvent();
});
$("#doo").on("change paste keyup", function () {
changeEvent()
});
function changeEvent(){
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
}
It's better use deligate function of jquery. Both function change both input values.
$(document).on("input paste keyup","#doo,#foo", function (e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});
You can even get same thing like below to
$( "body" ).delegate( "#doo, $foo", "input paste keyup", function(e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});

Detect if a field is updated with JavaScript or jQuery

I have a very extensive template, and there is a form that updates the value of a text field with JavaScript or jQuery, this function has not been able to locate it, and I need to detect when this field is updated, I have tried with all these functions, but it is not detecting when it is updated.
What is the reason why it is not detected when the field is updated from JavaScript but is detected when updated when I write and click outside the field?
Important: The value 90,000 "that is added dynamically, makes it a specific function, which I have not been able to find, and is to try to detect if the value changed with JavaScript.
$(function(){
// Automatic update, strange function
setTimeout(function(){
// Value updated automatically
$('#long').val("90.000");
}, 2000);
/**
* Detect if that field is updated
*/
$('input#long').on('change', function(){
alert("Updated");
});
$(':input').on('change', function(){
alert("Updated");
});
$('input#long').change(function(){
alert("Updated");
});
$(document).on('change', 'input#long', function(){
alert("Updated");
});
$(document).on('change', 'input', function(){
alert("Updated");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="long">
So, according to your edits/comments from other answers, you cannot trigger change manually.
A MutationObserver would be a good way to solve this, except they can't observe input value changes, as explained here.
Your only way out, as far as I can tell, is using setInterval to compare the current value with the old one every few milliseconds. A bit ugly and not optimal at all, but does the job. Here's a sample:
$(function() {
setTimeout(function() {
$('#long').val('90.000');
}, 1000);
$('#long').on('change', function() {
alert('changed');
});
// Store the current value
$('#long').data('oldVal', $('#long').val());
// Every 100ms, trigger `change` event whenever new value != old
setInterval(function() {
if ($('#long').val() !== $('#long').data('oldVal')) {
$('#long').trigger('change');
$('#long').data('oldVal', $('#long').val());
}
}, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="long">
You can use the change method from jquery to subscribe the event.
The html
<input class="target" type="text" value="Field 1">
and the script
$(".target").change(function() {
alert( "Handler for .change() called." );
});
See this codepen
See the jquery docs
DOM events won't be triggered by JS/jQuery calls. You can easily trigger the change event manually, like this:
$('#long').val('90.000').trigger('change')
Sample:
$(function(){
// Automatic update, strange function
setTimeout(function(){
// Value updated automatically
$('#long').val("90.000").trigger('change');
}, 2000);
/**
* Detect if that field is updated
*/
$('input#long').on('change', function(){
alert("Updated");
});
$(':input').on('change', function(){
alert("Updated");
});
$('input#long').change(function(){
alert("Updated");
});
$(document).on('change', 'input#long', function(){
alert("Updated");
});
$(document).on('change', 'input', function(){
alert("Updated");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="long">
Have you tried the keyup trigger wich fires straight when the key is released?
$(function(){
// Automatic update, strange function
setTimeout(function(){
// Value updated automatically
$('#long').val("90.000");
}, 2000);
/**
* Detect if that field is updated
*/
$( "#long" ).keyup(function() {
alert( "Handler for .keyup() called." );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="long">
Use keyup and paste instead of change. See keyup()
$(function(){
// Automatic update, strange function
setTimeout(function(){
// Value updated automatically
$('#long').val("90.000");
}, 2000);
/**
* Detect if that field is updated by key press or pasting text
*/
$(document).on('keyup paste', 'input', function(){
alert("Updated text field");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="long">
change()
The change event is sent to an element when its value changes. This
event is limited to input elements, textarea boxes and select
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse,
but for the other element types the event is deferred until the
element loses focus.

Re-run javascript code when the value changes

I have two files: a html file (with the code below) and a javascript file (it creates a value for the <span id="quantity">) The code works fine, but the word only changes if I refresh the whole page.
I want the word to change from 'articles' to 'article' or vice versa as soon as the 'quantity' changes. Is this possible? And if so, how?
<span id="quantity" class="simpleCart_quantity"></span>
<span id="quantityText"></span>
<script type="text/javascript">
$(window).load(function()
{
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
});
</script>
You might want to look into MVVC framework like Knockout JS. For example, you would set the contents of the #quantity <span></span> element to be an observable.
However, try reading this SO thread to find a solution similar to what you probably are hoping for. In summary, change events only occur from the browser on the blurring of form fields, so you'll need to implement a $("#quantity").trigger('change')
Once you have a trigger set-up after the DOM element has been loaded, you can do the following:
$('#myParentNode').on('change','#mynum', function() {
// Add your logic in here
$('#quantityText').text('articles') .... .. .. .....
});
Normally, the span element doesn't fire a change event, so you cannot subscribe to it, like you would normally do in an input element.
However, you can trigger such an event using jQuery in the same code, which changes the value of the span (I assume there is such code, because normally spans don't change value).
Here is an example which simulates this change every 10 seconds, and triggers the change event. It also includes a handler for that change event, which duplicates the value in the other span.
<span id="quantity" class="simpleCart_quantity">1</span>
<span id="quantityText"></span>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var quantity = $("#quantity"),
quantityText = $("#quantityText");
setInterval(function() {
var currentVal = parseInt(quantity.html());
if (currentVal >= 10) {
quantity.html(1);
}
else {
quantity.html(currentVal + 1);
}
quantity.trigger('change');
}, 10000);
quantity.on('change', function(sender, args) {
quantityText.html($(this).html());
});
});
</script>

Maintain focus on an input tag

I'm trying to keep focus on an input element with this code:
<input onblur="this.focus()" />
But it doesn't seem to work.
If we just call .focus() right on blur event, it will restore focus, but actually there will be no text cursor. To handle this we have to let element to lose focus and then return it in few milliseconds. We can use setTimeout() for this.
$('#inp').on('blur',function () {
var blurEl = $(this);
setTimeout(function() {
blurEl.focus()
}, 10);
});
Here's working example. Be careful - you can't leave text field after you enter it =)
EDIT I used jQuery, but it can be easily done without it.
EDIT2 Here's pure JS version fiddle
<input type="text" id="elemID" />
<script type="text/javascript">
document.getElementById('elemID').onblur = function (event) {
var blurEl = this;
setTimeout(function() {
blurEl.focus()
}, 10);
};
</script>

Categories