jquery binding to select changes - javascript

I have a hidden select which should be automatically selected via a visible select, my jquery is:
$(document).ready(function() {
var selected_val = $('#id_foo option:selected').val();
$('#id_bar').val(selected_val);
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
$('#id_bar').val(selected_val);
});
});
This works fine, but the page I am working on has the option to add a value to the (visible) select on the fly. How do I bind to this event and add this to the hidden list before updating the selected value?

The best way to tackle this is to update the hidden select with the new values when you update the visible one.
Or, as per my comment, you could populate the hidden select when the visible one is changed:
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
//clear and re-populate all of hidden select here
$('#id_bar').val(selected_val);
});

This should do the trick:
$(function () {
var $bar = $('#id_bar');
var $foo = $('#id_foo');
$bar.val($foo.val());
$foo.change(function () {
var newValue = $(this).val();
if ($bar.find('[value="' + newValue + '"]').length === 0) {
$bar.append($('<option/>').val(newValue));
}
$bar.val(newValue);
});
});
Before setting the new value, checks if the value is an option. If it's not, add as an option.

This snippet correctly identifies the event and succesfully copies the select options from foo to bar. However it does not seem to set :selected correctly on either id_foo or id_bar and using DOMSubtreeModified feels hackish
$('#id_foo').bind("DOMSubtreeModified", function(){
var high = 0;
$('#id_foo').children().each(
function(){
if ($(this).val() > high) {
high = $(this).val();
}
}
);
$('#id_foo').val(high);
var new_options = $('#id_foo').clone();
$('#id_bar').html('');
$('#id_bar').append(new_options.children());
});
So, for now the best I could come up with:
$('#id_foo').bind("DOMSubtreeModified", function(){
location.reload();
});

Related

How to get onclick event for jQuery Chosen drodpown listbox?

Hi I am developing one jquery application. I ghave one dropdownbox with jquery choosen.
$(function () {
$(".limitedNumbSelect").chosen();
});
This is my dropdown and binding values from database.
<b>Awarded To:</b> <asp:ListBox ID="ddlvendorss" runat="server" SelectionMode="Multiple" class="limitedNumbSelect"></asp:ListBox>
I am trying to get click event for the above dropdown. As soon as i click on the dropodwn i want to fire a alert before loading any options.
$('#ddlvendorss').click(function (e) {
alert("I am going crazy");
});
In the below code checkedValues arrays contains some values(values present in dropdownlistbox). As soon as i click on the drodpown i ant to hide those values. But below code doesnt work.
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
$(".limitedNumbSelect option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
Above code does not work. May I get some advise on this? Any help would be appreciated. Thank you.
Chosen hides the select element, thus you are not actually clicking the element. However you can use chosen:showing_dropdown event
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
alert('No need to go crazy');;
});
Fiddle
If you want to hide options, You can use
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
//Find options and hide
$(this).find('option:lt(3)').hide();
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
Fiddle
As per OP's code
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
//Get all options
var options = $(this).find('option');
//Show all
options.show();
//Hide based on condtion
options.filter(function () {
return checkedValues.indexOf($(this).val()) === -1;
});
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));

Input jQuery get old value before onchange and get value after on change

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 );
}
);

Filter results of dropdownlist per prior dropdownlist selection using jquery

I successfully used the jquery script TheSuperTramp posted here:
Jquery dependent drop down boxes populate- how
to remove any list items with a value less than the one selected. However, I need to remove only the value I had selected in the first pull down menu. I believe the following jquery script should accomplish this however it is not. Any suggestions to correct this would be greatly appreciated.
Thanks,
KS
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').filter(function () {
if (parseInt(this.value) == drop1selected)
{
$(this).remove();
};
});
});
What you actually need here is .each(), instead of .filter():
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').each(function () {
if (parseInt(this.value) === drop1selected)
{
$(this).remove();
};
});
});
As .filter() will remove the element from the result set of matching elements, but it will not remove them from the DOM. You may want to use it like this:
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').filter(function () {
return parseInt(this.value) === drop1selected;
}).remove();
});

Select one option from each combobox

I have 6 html selects on a form, each of which contains the same 8 options.
If an option has been chosen from one of the selects, then I'd like that option to be disabled in all other selects. I'd like the option to still be visible (i.e. it must not be removed).
Is there a jquery plugin or similar that can be used?
Try it here: http://jsfiddle.net/jbjkm/3/
$.fn.exclusiveSelectSet = function() {
var set = this, options = this.find('option');
return this.change(function() {
var selected = {};
set.each(function(){ selected[this.value] = true });
options.each(function() {
var sel = this.parentNode;
this.disabled = this.value && selected[this.value] &&
sel.options[sel.selectedIndex] != this;
});
}).change();
}
$('select.loves').exclusiveSelectSet();
$('#likes select').exclusiveSelectSet();
In English, whenever a select value is changed:
Find the values of all selected options.
Disable any option that has one of the selected values,
unless it doesn't have any value (value="") or it is the selected option in its <select>.
to disable/enable all other checkboxes with the same value add this Javascript:
$(document).ready(function(){
$('input[tpye="checkbox"]').change(function(){
if($(this).is(':checked'))
$('input[value="'.$(this).val().'"]').each(function(){
$(this).attr('disabled', true);
});
else
$('input[value="'.$(this).val().'"]').each(function(){
$(this).removeAttr('disabled');
});
});
});
if u use selects try this:
$(document).ready(function(){
$('select').change(function(){
$('option:disabled').each(function(){
$(this).removeAttr('disabled');
});
$('select').each(function(){
var v = $(this).val();
$('option[value="'+v+'"]').each(function(){
if($(this).parent() != $(this))
$(this).attr('disabled',true);
});
});
});
});
EDIT: ah, right, enable all option before disabling some (reset)

Changing value of custom select option - Javascript

I need assistance changing the value of a custom-select box. I cannot use JQuery because I already have a change() function hooked up to it.
How can I change the value of the select box in Javascript?
This is my custom select function:
$.fn.customSelect = function() {
if ( $(this).length ) {
$(this).find('select').attr('selectedIndex',-1).change(function() {
var optionText = $(this).find('option:selected').text();
$(this).siblings('label').text(optionText)
});
}
};
I have tried:
var field = document.getElementById('test5');
field.value = '2';
field.focus();
This will select the option, but it will not show up as the default option (hopefully you guys can understand this haha).
Any possible solutions?
I made a fiddle example of what trying to do here
You need to invoke the change event to run the plugin code, also name the change event:
$.fn.customSelect = function() {
if ( $(this).length ) {
$(this).find('select').attr('selectedIndex',-1).bind('change.customSelect', function() {
var optionText = $(this).find('option:selected').text();
$(this).siblings('label').text(optionText)
});
}
};
Trigger like this:
$('#select1').val('1').trigger('change.customSelect');

Categories