I am having jquery as follows,
$(document).on('click', '.save_button', function (e) {
var amount = $('.actual_pay').val();
});
Which means when a user clicks the button with class save_button, the script executes and sets the value of the var amount to the value of the field with class actual_pay.
Up to this no problems and it is working fine, but the input box with class name actual_pay is editable and any time the value can be changed, I have to detect the changed value of the input box, for which i have tried with
var amount = $('.actual_pay').val().change();
But it is showing error:
.change is not a function.
How to detect the change happening to the class actual_pay and to store the changed value to the amount variable?
You can attach an input event listener.
var amount;
$('.actual_pay').on("input", function(){
console.log("Something is changed in actual_pay");
amount = $(this).val(); // save val
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="actual_pay">
Actions which invoke input events are
Entering some text into an element.
Cutting, deleting or pasting some content.
Dropping some content into an element. (only in Google Chrome and Safari)
$('.actual_pay').val().change(); won't work because this is wrong approach. You can do by following method
$('.actual_pay').on('input',function(){
alert('Something Modified');
});
You can get value of that input box with this function:
$( "input.actual_pay" ).keyup(function() {
var amount = $(this).val();
});
If you are changing that input manually, you will use 'keyup', otherwise you should use
$( "input.actual_pay" ).change(function() {
var amount = $(this).val();
});
Related
I want to trigger a function when one of my field (textbox) changed. The problem is: the content of that textbox is filed automatically by an external script(That I don't have access to), therefore the onChange listener won't trigger.
I've tried a lot of code, but here's the two closest (I think?) result I have:
Here's the script and the field
<script async src="SomeNiceScriptHere.js"></script>
<input type="text" name="wt_embed_output" id="wt_embed_output" class="wt_embed_output"/>
Code 1:
function myFunction() {
var x = document.getElementById("wt_embed_output").value;
alert("The input value has changed. The new value is: " + x);
}
document.getElementById("wt_embed_output").addEventListener("change", myFunction);
Code 2:
$( "#wt_embed_output" ).change(function() {
alert( "Value has been changed" );
});
For now, it doesn't work when the value is updated with the script, it only works when the user manually changes the value.
Does anyone know a way to do it?
Try adding event listener in the input.
var el = document.getElementById('wt_embed_output');
el.value = 'New Value'
el.dispatchEvent(new Event('oninput'));
document.getElementById("wt_embed_output").addEventListener("oninput", myFunction());
function myFunction() {
var x = document.getElementById("wt_embed_output").value;
alert("The input value has changed. The new value is: " + x);
}
<input type="text" name="wt_embed_output" id="wt_embed_output" class="wt_embed_output" />
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
try using oninput event;
if that doesn't work you can use a solution that works for all cases: set up a timing event using setInterval()
This isn't a perfect solution, but it works. Since I wasn't able to fetch the text in the field right after the script execute, I did a little workaround with myFunction():
<script>
function myFunction() {
if(document.getElementsByClassName('wt_embed__message')[0].getElementsByClassName('main')[0].textContent != 'Upload completed!'){
setTimeout(myFunction, 500);
}
else{
var wt_output = document.getElementById("wt_embed_output").value;
//do something
}
}
window.addEventListener("load", myFunction);
</script>
-> When the page load, my function is called until the external scripts runs. Once I get a specified message, I know the script is done so I get out of the 'if' condition.
I have a series of dynamically generated inputs with the same class, eg:
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
<input class="addressitem" type="text"/>
After the user inputs data into each field I want to take that data and place it in the value field of a hidden input.
However, I am having trouble figuring out the best way to do this. So far I've tried:
$(".addressitem").focusout(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
and
$(".addressitem").change(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
But I cannot get anything to appear in console.
Could anyone point me in the right direction?
Both of your approaches should work as long as you define them inside the document.ready event and you do not have any other script errors in your page.
$(function(){
$(".addressitem").change(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
$(".addressitem").focusout(function() {
var addressinput = $(this).val();
console.log(addressinput);
});
});
You may use your browser console to verify the existence of other script errors in the page.
Also remember that, change event occurs on the text input fields when the focus is out. So you will see the console.log when user changes the focus from the textboxes. If you want instant updates, you should consider using keyUp event
Here is a working sample.
EDIT : As per the comment : I had the fields generated by a Jquery click function. I had to move my code within the click function for it to work.
No you don't need to. You can simply use the jQuery on delegation method. When you register an event handler with jQuery on, It will work for current and future elements(dynamically injected) in the DOM.
So your code will be
$(function(){
$(document).on("change",".addressitem",function() {
var addressinput = $(this).val();
console.log(addressinput);
});
});
This might be the best option, as you said they are dynamically generated inputs.
$(document).on("blur",".addressitem",function() {
var addressinput = $(this).val();
console.log(addressinput);
});
WORKING FIDDLE
Check your console
On focusout in HTML5 as following:
<input type="text" onfocusout="makeITUpperCase(this)">
And in javascript as following:
function makeITUpperCase(e) {
console.log(e.value);
e.value = e.value.toUpperCase();
}
The function takes 'this' object as e which can be used to get value or alter
I have a script that adds up data-attributes from checkboxes, I modified the script to be able to allow users to manually add their own entries into a text input that the keyup function copies into the data-cost="" and debt="" attributes, which a plugin recalculates the total into the blue div box on the right side in this Fiddle. This functionality works, as you can see in the fiddle
But I also want data that is copied into the data-attributes to also be copied into the value="". The plugin uses the value to display it in the yellow summary box on the right, but every time I modify the keyup script, the calculation stops working and the value does not show up in the summary.
Here is the Fiddle
This is the keyup script:
function calculateTotalFor(){
$('#jquery-order-form').data('jprice').onChange();
}
$(function () {
$(document).on('keyup blur paste', '.balance', function() { //Changed here
var $self = $(this),
$checkbox = $self.closest('li').find('input:checkbox');
setTimeout(function() {
var str = $self.val();
$checkbox.data('cost',str.replace(/^\$/, ''));
$checkbox.data('debt',str.replace(/^\$/, ''));
calculateTotalFor();
}, 0)
})
});
I added $checkbox.val(str.replace(/^\$/, '')); before calculateTotalFor(); and it seems to work.
i have an input field where i allow users to insert an integer.
Now when ever they insert a value into the input field i check with ajax if it is higher than a specefic amount for this purpose i need to get the "new" value of the input field
i have tried the following:
$('.wanted_amount').keydown(function () {
var value = $(this).val();
}
however this returns ""
Meaning that it doesnt register the value untill after keydown
So how i can i get the new value of the input field with javascript?
can you please try this,
$(function(){
$('.wanted_amount').keyup(function () {
var value = $(this).val(); // alert(value);
});
});
keydown is event, which helps to trigger event when detects a finger on a key
keyup is event, which helps to trigger event when the key is released
You have not closed function properly.
keydown() will be triggered when key is pressed and keyup() will be triggered after pressing the key. In your case, keyup() is more suitable.
Try this:
$('.wanted_amount').keyup(function () {
var value = $(this).val();
console.log(value);
});
Fiddle here.
Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on.
I need just trigger an action every time the text in the input changes, even if it's only one letter change.
There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:
jQuery keyboard events
Catch only keypresses that change input?
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Yes, compare it to the value it was before it changed.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
function checkChange($this){
var value = $this.val();
var sv=$this.data("stored");
if(value!=sv)
$this.trigger("simpleChange");
}
$(document).ready(function(){
$(this).data("stored",$(this).val());
$("input").bind("keyup",function(e){
checkChange($(this));
});
$("input").bind("simpleChange",function(e){
alert("the value is chaneged");
});
});
here is the fiddle http://jsfiddle.net/Q9PqT/1/
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
$(document).ready(function() {
$("#fieldId").bind("keyup keydown keypress change blur", function() {
if ($(this).val() != jQuery.data(this, "lastvalue") {
alert("changed");
}
jQuery.data(this, "lastvalue", $(this).val());
});
});
This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.
UPDATE: Added blur to the bind list.
I had to use this kind of code for a scanner that pasted stuff into the field
$(document).ready(function() {
var tId,oldVal;
$("#fieldId").focus(function() {
oldVal = $("#fieldId").val();
tId=setInterval(function() {
var newVal = $("#fieldId").val();
if (oldVal!=newVal) oldVal=newVal;
someaction() },100);
});
$("#fieldId").blur(function(){ clearInterval(tId)});
});
Not tested...
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/
Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
var inp = $('#input'),
val = saved = inp.val(),
tid = setInterval(function() {
val = inp.val();
if ( saved != val ) {
console.log('#input has changed');
saved = val;
},50);
You can also set this up using a jQuery special event.