jQquery Get dom modified attribute value - javascript

Let's say I modify an attribute value on click with a function like:
$('#dd ul.dropdown li a').click(function(e) {
var txt = $(e.target).html();
var langs = $(e.target).text();
$('#dd .currentlangs').html(txt);
langs = langs.trim().toLowerCase().replace(/\s+/g, "-");
$('.currentlangs').attr('data-lang', langs);
});
And then I want the current attribute value in a keyup function like:
var $input = $('#querysearch');
var dict = $('.currentlangs').attr('data-lang');
$input.on('keyup', function () {
alert(dict);
});
Needed value is "dict" variable but doing that I keep getting the initial value when DOM has been loaded. How can I get the current attribute when the keyup function is fired?
Thanks a lot

You're getting the value of the attribute as of when this line
var dict = $('.currentlangs').attr('data-lang');
runs. That's before the use clicks anything, so naturally you get the value as defined in the HTML. Move it into the keyup handler:
var $input = $('#querysearch');
$input.on('keyup', function () {
var dict = $('.currentlangs').attr('data-lang');
alert(dict);
});
...so that you get the value when the keyup event occurs.

Related

How to preserve old input text value after the change in Javascript? [duplicate]

I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.
What I tried:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.
Here is the same example using delegated events connected to document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change).
Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
I have found a solution that works even with "Select2" plugin:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
my solution is here
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
if you are looking for select droplist, and jquery code would like this:
var preValue ="";
//get value when click select list
$("#selectList").click(
function(){
preValue =$("#selectList").val();
}
);
$("#selectList").change(
function(){
var curentValue = $("#selectList").val();
var preValue = preValue;
console.log("current:"+curentValue );
console.log("old:"+preValue );
}
);

How to change order in select2 for multiple, with given order

I am new in select2 js so please help me for selecting value according to given order. Means when i have to store value according to user decided order.
data = [{id:1, name:xyz},{id:2, name:abc},{id:3, name:lmn}]
Suppose I want to show id [1,2] as selected but I am getting [2,1]
Add this code:
$('select').on('select2:select', function(e) {
var element = $(this).find('[value="' + e.params.data.id + '"]');
$(this).append(element);
$(this).trigger('change');
});
Or,
$("select").select2();
$("select").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
});

Get value of dom element in ready function

I want my textArea to resize when the page is fully loaded. I found that
$(document).ready(function() {
// Handler for .ready() called.
});
can help me, so I try to test it and put next code into that function:
$(document).ready(function() {
var element = $('#elementId');
alert(element.value);
});
But when the page is loading, alert shows undefined value of textArea, however there is text inside it.
How can I fetch those value inside ready function?
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
element isn't a DOM element but a jQuery wrapped object, it doesn't have any value property.
Use
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
or
$(document).ready(function() {
var element = document.getElementById('elementId');
alert(element.value);
});
or
$(document).ready(function() {
var element = $('#elementId');
alert(element.get(0).value);
});
You need to use DOM object to use value property and you have jQuery object you need to use val() on it.
$(document).ready(function() {
var element = $('#elementId');
alert(element[0].value);
//or
alert(element.val());
});

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Jquery dynamic dropdown event not firing

Hi i am trying to create dropdownlists dynamically and populating the contents via an ajax call, this sort of works in the sense that the drop down is created and populated as required but its 'change' event does not fire. I am posting the code below, if anyone can spot something obvious, can you please let me know
regards
$(document).ready(function () {
$("#positions select").change(function (e) {
alert("in");
var id = $("#category_id").val();
$.getJSON("/Category/GetSubCategories/" + id, function (data) {
if (data.length > 0) {
alert(data.length);
var position = document.getElementById('positions');
var tr = position.insertRow(7);
var td1 = tr.insertCell(-1);
var td = tr.insertCell(-1);
var sel = document.createElement("select");
sel.name = 'sel';
sel.id = 'sel';
sel.setAttribute('class', 'category');
td.appendChild(sel);
$.each(data, function (GetSubCatergories, category) {
$('#sel').append($("<option></option>").
attr("value", category.category_id).
text(category.name));
});
}
});
});
});
If your drop down is dynamically generated then you have to bind the change event using .live() handler. live() attaches a handler to the event for all elements which match the current selector, now or in the future.
$("positions select").live("change", function(){
});
Edit
To get the id
$(this).attr("id");
To get value
$(this).val();
To get class name
$(this).attr("class");
inside the change event handler.

Categories

Resources