Which event is fired prior to radio button value change? - javascript

$('input[type="radio"]').change(function() {
alert(this.value);
});
this.value here already contains new value. How can I get previous value (i.e. prior to change value)?

The change event has a eventData and an eventObject in the function. See here: http://api.jquery.com/change/ try playing with them. I think you can pass the old value in the eventData and retrieve it in the function through the eventObject.

Since there is no such event, I had to store prev value in data-original-value attribute:
$('input[type="radio"]').change(function() {
alert(this.name + ': ' + $(this).parents("div.control-group").attr('data-original-value') + ' -> ' + this.value);
$(this).parents("div.control-group").attr('data-original-value', this.value);
});

Related

How can we get val from keyup in jquery

i want give val from keyup in jquery
my code is :
var vartest;
$( ".target" ).keyup(function() {
vartest= this.value;
console.log('in func:' + vartest);
});
console.log('out of func:' + vartest);
but vartest is undefined
Your function triggers only once your Element receives an event.
At the time you were calling vartest (outside of your function) its value is still undefined because the event (that actually attaches a value) will trigger at a later time.
Create a function getTargetsValues and call that function when needed.
Instead of "keyup" you might eventually listen for the "input" event:
// Cache your elements
const $targets = $(".target");
// Use this function to get an Array of inputs .target values
function getTargetsValues () {
return $targets.get().map(el => el.value);
}
$targets.on("input", function() {
console.log('in func: ' + getTargetsValues());
});
console.log('out of func: ' + getTargetsValues());
<input class="target" type="text" value="1. target">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
I’m not sure if this is what you need, but if you want to get value of input where event happened, you should take it from event target:
$(‘.target’).keyup(e => {
vartest = e.target.value;
});

Checkbox trigger change event

I am verifying certain data then I am dynamically checking checkbox and I want to trigger change event of checkbox.
$("#chk").prop("checked", true).trigger("change");
Change event
$("#chk").change(function () {
if ($(this).is(':checked')) {
if (localStorage.getItem('A') == undefined && sessionStorage.getItem('A') == null) {
location.href = "/" + lang.split('-')[0] + "/login.aspx";
}
$("#dvClass").hide();
$("#dvPromoCode").hide();
$("#resultby").empty();
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
else {
$("#dvClass").show();
$("#dvPromoCode").show();
$("#resultby").empty();
$("#resultby").append('<option value="AirAvailability">' + Res.schedule + '</option>');
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
});
but it is not triggering the change event. But same if I execute from console than it works as expected. I want to know what can be issue.
The order of the function is important here.
You have place your change event before setting the checkbox values. Look at the below code.
$("#chk").prop("checked", "checked").trigger("change");
$("#chk").change(function() {
alert("triggered!");
});
The above won't work because when the jquery run for first line, it doesn't have any change event for the checkbox. You can check the same in this Fiddle
Now place your change event function before calling it like below.
$("#chk").change(function() {
alert("triggered!");
});
$("#chk").prop("checked", "checked").trigger("change");
Now you can get the expected result. You can check the same in this Fiddle
Always better to use the on event for the dynamic added elements like below.
$("#chk").on('change', function() {
alert("triggered!");
});
Be you sur you declared the change event before the prop change instr ; see updated answer :
$(function(){
$("#chk").on("change", function() {
console.log(this.checked)
});
$("#chk").prop("checked", true).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="chk" type="checkbox" />

Jquery get input value on input

I want to get the input value while I keep pressing keyboard keys.
Following updates the input if I click out of the input field.
$('create-text').onchange = function() {
console.log("whoo: " + this.value);
}
The .change event triggers when the value has been changed and the element loses focus, as in click outside of the element.
When releasing a pressed key:
$('create-text').keyup(function() {
console.log("whoo: " + this.value);
});
When pressing a released key and wanting to record modifier and not-printing keys:
$('create-text').keydown(function() {
console.log("whoo: " + this.value);
});
When pressing a released key and not needing the above:
$('create-text').keypress(function() {
console.log("whoo: " + this.value);
});
However, you would probably want to use a proper selector .create-text or #create-text to target your input element. You could also get more specific by using something like input[name="cr-text"]#create-text.
// On pressing key
$("input").keyup(function(){
console.log($(this).val())
});
// When focus lost
$("input").focusout(function(){
console.log($(this).val())
});

How to listen to event from jQuery plugin which uses val()

I'm using cropin jQuery plugin in my project and going to pull updates for it in future so I don't want to change it's code.
Inside the plugin it changes the value of <input> element using val() function but doesn't instantly trigger the change event which means that I cannot listen to event using code like this:
on("change", function(){
//do something;
})
*details can be found here: .val() doesn't trigger .change() in jquery
Question: is there any workaround for this? How can I listen to change event without modifying the plugin code if plugin:
uses val() to modify the elements value
doesn't trigger change event following the val() call?
You could decorate the jquery val function.
edit: I couldn't resist making the suggested changes as it's such a good solution.
// jQuery plugin to decorate .val
(function( $ ){
var __val = $.fn.val,
// save the previous values to a hash table
values = {};
$.fn.val = function( newVal ){
// create a unique key based on tag offset id & class
var hashId = this.prop('nodeName').toLowerCase() + '[' + this.index() + ']' + '#' + this.attr('id') + '.' + this.attr('class').replace(' ', '.');
console.log('hashId', hashId);
if( newVal && ( !values[ hashId ] || ( values[ hashId ] !== newVal ) )) {
values[ hashId ] = newVal;
var ret = __val.apply(this, arguments);
this.trigger('change');
return ret;
}
console.log('no change');
return __val.apply(this, arguments);
}
})( jQuery );
var $input = $('#input'),
$changer = $('#changer');
$input.on('change', function(e){
console.log('changed: ' + this.value );
});
$changer.click(function(){
$input.val('something');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<input id='input' class="some-input" type='text'>
<button id="changer">change</button>
I don't know if it works because I have never done it. However, according to: redefining-a-jquery-function
you could redefine jQuery's val function to trigger a change event.
In this way you won't have to touch the plugin and calling val() will fire an event every time it is called.
Sample code is included in the link provided.
EDIT: Answers to similar questions state that it is bad practice as sometimes doing so leads to an unpredictable behavior of jQuery.
See this http://jsfiddle.net/cqz2u8x8/1/ fiddle for different change events. You might want to try the on('input') event. This seems to trigger every time a real change in value has occured.
$("#testinput").on('input', function(e) {
$("#valuetyped-input").html(e.target.value)
});

Get value of checkbox in dojo, with on() method

Using dojo 1.9, I'm trying to access the value of a checkbox not like in the example in the docs:
require(["dijit/form/CheckBox", "dojo/domReady!"], function(CheckBox){
var checkBox = new CheckBox({
name: "checkBox",
value: "agreed",
checked: false,
onChange: function(b){ alert('onChange called with parameter = ' + b + ', and widget value = ' + this.get('value') ); }
}, "checkBox");
});
but by moving onChange event to:
query('#checkBox').on('change', function(){
var value = query(this).attr('value');
});
or anything similar. I just want to access it from on() method. But I get the same value every time - checkbox is checked. Any ideas?
And again I made the same mistake - it should be
registry.byId('checkBox').on('change', function(){
var value = this.value;
});
dojo/query returns plain dom Nodes of the widgets, and therefore, we cannot attach the "on" event handler, directly to the query result. As you have said, we can use registry.byId(...)
In addition, let me give a suggestion, where the query would return more number of dom nodes.
array.forEach(dojo.query('.classname'),function(node){
dijit.getEnclosingWidget(node).on('change',function(){
var value = this.value;
console.info(value);
});
});
dijit.getEnclosingWidget(domNode) - will give the immediate parent widget node of the mentioned 'domNode'

Categories

Resources