how to add same onchange events to different select boxes - javascript

I want to add 'change' events to 4 select boxes. I have done it using bind().
But I want to call different functions on change of each select box.
Say function1() on change event of SelectBox1...
How should I do it?
I am new to javascript & jquery, so please help.
Thank you

Suppose your HTML like this:
HTML
<select id="selectBox1">
</select>
<select id="selectBox2">
</select>
<select id="selectBox3">
</select>
<select id="selectBox4">
</select>
jQuery
$('select[id^=selectBox]').on('change', function() {
// to get the id of current selectBox
var selectId = this.id;
if(selectId == 'selectBox1') {
function1();
} else if(selecId == 'selectBox2') {
function2();
}
// and so on
});
Some more
$('select[id^=selectBox]').on('change', function() {
// to get the selected value
var value = $.trim( this.value ); // $.trim() used to remove space
// from beginning and end
// you may not use
// to get selected option text
var optText = $('option:selected', this).text()
// to get the selectedIndex
var selIndex = this.selectedIndex;
// OR
var selIndex = $(this).prop('selectedIndex');
});
Note
Here, select[id^=selectBox] get select boxes, whose id start with selectBox. You may have something different id.
.change() used for bind the event to those select box.
Read more about
jQuery selectors
jQuery Events
$.trim()
.prop()

you can set an specific attribute for each select so:
<select id="selectBox1" val='1'>
</select>
<select id="selectBox2" val='2'>
</select>
<select id="selectBox3" val='3'>
</select>
<select id="selectBox4" val='4'>
</select>
and then bind onchange event like this:
$("select").change(function(){
var val = $(this).attr("val");
if (val == '1')
{
//logic for first select change
}
else if (val == '2')
{
//logic for second select change
}
else if (val == '3')
{
//logic for third select change
}
// and so on...
});
hope that helps.

Related

JQuery get the value of the newly selected/unselected element of a select [duplicate]

I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
}); ​
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

jquery variable doesn't change on update

This my problem's semplification. I want to append some text after an input field (on update of the same field), only when the value of a select element is IT.
That's the fields:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva">
this is the script:
jQuery(document).ready(function () {
var $country_select = jQuery('#billing_country');
// When country change
$country_select.change(function () {
var $country = jQuery('#billing_country option:selected');
$country.each(function() {
FieldCheck(jQuery(this).val());
})
});
function FieldCheck($country) {
var $element = jQuery('#woocommerce_cf_piva');
if ($country == 'IT') {
$element.change(function () {
$element.after($country);
});
}
}
});
You can see this also on jsFiddle
Why it append country name also if i select FR?
It's difficult to understand what you're trying to do with your code.
You want the text input to change its value only if the select box has "IT" selected?
Why are you setting a change handler on the text input?
Why iterate through a select box's options if it's a single select? Just set the text input with the selected option's value, e.g.,
$(function() {
var $billingCountry = $('#billing_country');
$billingCountry.change(function() {
var $country = $('#billing_country option:selected');
fieldCheck($country.val());
});
function fieldCheck(country) {
var $element = $('#woocommerce_cf_piva');
if ($country !== 'IT') {
return;
}
$element.val(country);
}
});
https://jsfiddle.net/davelnewton/w5deffvk/
Edits
Naming conventions changed to reflect typical JS
Non-constructor function names start with lower-case
Non-JQ element vars don't get a leading $
Country value used as guard clause rather than nesting logic
This code is trivial, but nesting can make things harder to reason about
I would add a span and put the text in there so on subsequent change you can fix it:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva" /><span id="afterit"></span>
Note that this is still pretty verbose:
jQuery(document).ready(function() {
var $country_select = jQuery('#billing_country');
var $element = jQuery('#woocommerce_cf_piva');
// When country change
$country_select.on('change', function() {
var $country = jQuery(this).find('option:selected')[0].value;
var d = ($country == 'IT') ? $country : "";
$element.data('selectedcountry', d);
});
$element.on('change', function() {
var ct = $(this).data('selectedcountry');
//as you have it: $(this).after(ct);// append
// put it in the span to remove/blank out on subsequent changes
$('#afterit').text(ct);
});
});
Here is the total less-verbose version:
$('#woocommerce_cf_piva').on('change', function() {
var v = $('#billing_country').find('option:selected')[0].value;
$('#afterit').text((v == 'IT') ? v : "");
});
You have two problems:
input tag does not have onchange event; you should use onkeydown instead;
you should assign events before if conditions.
If I understand the problem correctly, you want to update input field with the value entered only when drop down selection is "IT". If that is the case, you need to watch input field event and invoke FieldCheck function from with in input field events.

jQuery: If user changes select to specific option then change different input value

I have a select box like so:
<select id="update_type_picker" name="update_type_picker">
<option value="play">Played</option>
<option value="play">playing</option>
<option value="want">Want</option>
<option value="rating">Rate</option>
</select>
And an input like this:
<input id="playing" name="playing" type="hidden">
And I'm trying to make this jquery work:
$(document).ready(function () {
$("select#update_type_picker").change( function() {
var text = this.text;
if (text = "playing") {
$("input#playing").attr('value', '1');
} else {
$("input#playing").attr('value', '');
}
});
});
I need to use text (not value) because two of the values are the same. With the jquery above the input value changes to 1 regardless of which option I choose. How can I make this work they way I need it to? Thanks!
You have to use:
var text = $(this).find("option:selected").text();
And as mentioned in a comment, you have to use == or === to compare strings in the if, not =.

Jquery Javascript HTML selects

So I've got a standard select dropdown. One of the options in the select(the last one) I've got as a text string- var abc.
<select id="exampleselect">
<option>123</option>
<option>xyz</option>
<option>ABC</option>
</select>
var abc = "ABC";
What I'm trying to do is search through the select, find a match against var abc then change the match of var abc to being the selected option.
What I've tried:
//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text();
//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
{
//work out how to get the index/eq of the matched element
//put matched element as selected value
$('#exampleselect').val(matchedelementindex);
}
Live example.
As you don't use the value attribute, you can use this code:
var myVar = 'xyz';
$('#exampleselect option').each(function(e) {
var $this = $(this);
if ($this.text() === myVar) {
$this.prop('selected', true);
return false; // stops the iteration
}
});
You could also do it in one line by using the :contains() selector. But this would may not work if you have an option with text "ABC" and another with "ABCD":
$('#exampleselect option:contains('+myVar+')').prop('selected', true);
Although, I would recommend that you add a value attribute to your option elements:
<select id="exampleselect">
<option value="123">123</option>
<option value="xyz">xyz</option>
<option value="ABC">ABC</option>
</select>
this way you can do:
$('#exampleselect').val(myVar);
Try this:
var abc = "ABC";
$("#exampleselect option").each(function() {
if ($(this).text() == abc) {
$(this).attr("selected", true);
return false; // exit each loop
}
})
Or this, although this is slightly less readable:
var abc = "ABC";
$("#exampleselect option").each(function() {
$(this).attr("selected", $(this).text() == abc);
})
This fiddle may help you .
You can achieve this by CSS Selectors which are supported by jQuery
var searched="abc";
$('select option['+searched+']').attr("selected","selected");
http://jsfiddle.net/7EzqU/
// iterate all select options using jquery .each method
$('#exampleselect option').each(function () {
// check if current option text is equal to 'ABC'
if ($(this).text() == 'ABC') {
// get index of option
var index = $('#exampleselect').index($(this))
// set selectedIndex property to change to this option
$('#exampleselect').prop('selectedIndex', index);
}
})
this should do the trick:
http://jsfiddle.net/xXEVw/

Categories