Event listener inside a function - javascript

I have a select on my page:
<select id='cat'>
<option value='a'>A</option>
<option value='b'>B</option>
<option value='all'>all</option>
</select>
With a javascript function that handles which options have to be displayed:
function funcName(aList) {
// populates the options for the select tag
$("#cat").on("change", function(){
// some computation;
});
// uses aList to update some div data
}
What I'm trying to do is if the selected option is all, I have to display everything in aList, otherwise based on the selected option I have to display only the related options. Is my usage of onchange event correct?
Initially I thought of making aList global, but after some reading on globals in JS, I got to know it is not a very good practice.
Thanks in advance!
UPDATE: aList contains some string values.

$(function () {
$("#ddl").change(function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
var assignedRoleId = new Array();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
if(selectedValue== "all")
{
$("#ddl option").each(function()
{
if(this.value=="all")
{
assignedRoleId.push();
}
else
{
assignedRoleId.push(this.value);
assignedRoleId.push(" ");
$("#selected").html(assignedRoleId);
}
});
}
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Select something:
<select id="ddl">
<option value="">select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="all">all</option>
</select>
<div id="selected">
</div>

Related

Disabling select2 options based on selected value

I am trying to do something very similar to this fiddle, but rather than disable the other selections in the same group as which is selected, I want to disable all the options which are NOT in the same group as the one selected...therefore forcing the user to select another option from the same group.
However, even if I simply copy the code from the fiddle, it gives me an error:
https://jsfiddle.net/bindrid/hpkqxto6/
<select multiple style="width: 300px">
<option groupid="a" value="A_AK">Alaska</option>
<option groupId="b" value="B_HI">Hawaii</option>
<option groupid="c" value="C_CA">California</option>
<option groupid="a" value="D_NV">Nevada</option>
<option groupid="b" value="A_OR">Oregon</option>
<option groupid="c" value="B_WA">Washington</option>
<option groupid="a" value="C_AZ">Arizona</option>
<option groupid="b" value="D_CO">Colorado</option>
<option groupid="c" value="A_ID">Idaho</option>
<option groupid="a" value="B_MT">Montana</option>
<option groupid="b" value="C_NE">Nebraska</option>
<option groupid="c" value="D_NM">New Mexico</option>
<option groupid="a" value="A_ND">North Dakota</option>
<option groupid="b" value="B_UT">Utah</option>
<option groupid="c" value="C_WY">Wyoming</option>
</select>
$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"
});
//Select2 Event handler for selecting an item
$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});
// Select2 Event handler for unselecting an item
$('select').on("select2:unselecting", function(evt) {
disableSel2Group(evt, this, false);
});
});
// At some point during the select2 instantation it created the
// data object it needs with the source select option.
// This function, called by the events above to set the current status for the
// group for which the selected option belongs.
function disableSel2Group(evt, target, disabled) {
// Found a note in the Select2 formums on how to get the item to be selected
var selId = evt.params.args.data.id;
var group = $("option[value='" + selId + "']").attr("groupid");
var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var data = $(item).data("data");
var itemGroupId = $("option[value='" + data.id + "']").attr("groupid");
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The idea being that when an option is selected in a select2 dropdown, it then disables other options. However, even if I simply recreate this code, I get an error (cannot read property 'id' of undefined) which triggers on the line:
var group = $("option[value='" + selId + "']").attr("groupid");
Can anyone help fix the error, and then help me with my main intention of disabling all other groups? Thanks.
You can use evt.params.args.data.element this will give you option tag html then using this you can get the groupid value and compare it with all options attr if not same disabled that option.
Now , instead of unselecting use unselect because here you need to enable all options when select-box doesn't have any value selected . So , inside your function get select2('data').length and if length is 0 then only enabled all options.
Demo Code :
$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"
});
$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});
$('select').on("select2:unselect", function(evt) {
disableSel2Group(undefined, undefined, false);
});
})
function disableSel2Group(evt, target, disabled) {
//check if disabled true
if (disabled) {
//get option
var selId = evt.params.args.data.element;
var group = $(selId).attr('groupid') //groupid
var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var other_groups = $(item).attr("groupid"); //get option groupid
var data = $(item).data("select2-id"); //get option selct2id
//if not same
if (group != other_groups) {
$("select option[data-select2-id =" + data + "]").prop("disabled", true); //disable that option
}
})
} else {
var count = $('select').select2('data').length //checcking slected data count
console.log(count)
//if 0
if (count == 0) {
$("select option").prop("disabled", false); //enable all options
}
}
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select multiple style="width: 300px">
<option groupid="a" value="A_AK">Alaska</option>
<option groupid="b" value="B_HI">Hawaii</option>
<option groupid="c" value="C_CA">California</option>
<option groupid="a" value="D_NV">Nevada</option>
<option groupid="b" value="A_OR">Oregon</option>
<option groupid="c" value="B_WA">Washington</option>
<option groupid="a" value="C_AZ">Arizona</option>
<option groupid="b" value="D_CO">Colorado</option>
<option groupid="c" value="A_ID">Idaho</option>
<option groupid="a" value="B_MT">Montana</option>
<option groupid="b" value="C_NE">Nebraska</option>
<option groupid="c" value="D_NM">New Mexico</option>
<option groupid="a" value="A_ND">North Dakota</option>
<option groupid="b" value="B_UT">Utah</option>
<option groupid="c" value="C_WY">Wyoming</option>
</select>

Converting a JavaScript function to jQuery - Select option list

This is literally the first time I've worked with jQuery and I've read the entire chapter in my textbook but am finding a hard time wrapping my head around it. I'm attempting to convert a JavaScript function (a simple option selection drop-down list) to jQuery. I've attempted a few lines of code that I've gotten from the book or from w3schools and api.query but to no avail. I'll try to make this quick and simple, I just cannot understand jQuery for some reason.
What I've attempted usually doesn't work. Before my option list works fine, then I tried experimenting but I didn't get too far.
I also apolgize for the vagueness of the question, I'd appreciate any help!
Here's something I've tried:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js and index.html below it
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Through jQuery you can do it like below:-
Example:-
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Get an element by id:
var c = $('#countryChooser');
Get the value of this input/select element
var value = c.val();
Set the html of an element using the element id
$('#count').html('some html');
or set the text (html is not parsed this way)
$('#count').text('some html');
You can also handle the events with jQuery
$(document).ready(function() {
$('#countryChooser').on('change', function(event) {
// this is the DOM element with the id 'countryChooser'
// same as the native: var val = this.value;
var val = $(this).val();
// ...
});
});
I have bind the onchange() event of your select list inside the jQuery(document).ready() method. check this out-
// Updated code--
$(document).ready(function (){
$('#countryChooser').on('change' ,function () {
if(this.selectedIndex){
$('#count').html("Your country is: "+ this.options[this.selectedIndex].text);
}else{
$('#count').html("");
alert("Please select a country.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
$('#countryChooser').change(function(){
var selectedCountry = $(this).val();
if(selectedCountry == 'nothing'){
console.log('Select A country');
}
else{
$('#count').html('Your country is '+$('#countryChooser option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--JavaSript link -->
<select name="countrylist" id="countryChooser" >
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Please check the code might help you out
thanks

How to get selected values in SumoSelect dropdown?

I am using the SumoSelect dropdown for multiselect options. But i cannot get the selected values array.
Below the sample code :
<script type="text/javascript">
$(document).ready(function () {
window.testSelAll = $('.testSelAll').SumoSelect({okCancelInMulti:true, selectAll:true });
$('.btnOk').on('click', function(){
var obj = [];
$('option:selected').each(function () {
obj.push($(this).index());
alert("Selected Values=="+$(this).val());
});
for (var i = 0; i < obj.length; i++) {
$('.testSelAll')[0].sumo.unSelectItem(obj[i]);
}
});
});
</script>
<select multiple="multiple" placeholder="Share Your Friends" onchange="console.log($(this).children(':selected').length)" class="testSelAll">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="porsche">Porche</option>
<option value="ferrari">Ferrari</option>
<option value="mitsubishi">Mitsubishi</option>
</select>
If you want the selected values instead of the text, just change .text() to .val().
If you want to get the array, see below with working example at the bottom.
jQuery
$(document).ready(function() {
$('.testSelAll').SumoSelect({
okCancelInMulti: true,
selectAll: true
});
$('.btnOk').on('click', function() {
var obj = [],
items = '';
$('.testSelAll option:selected').each(function(i) {
obj.push($(this).val());
$('.testSelAll')[0].sumo.unSelectItem(i);
});
for (var i = 0; i < obj.length; i++) {
items += ' ' + obj[i]
};
alert(items);
});
});
HTML
<select multiple="multiple" class="testSelAll">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Working JSFIDDLE
You can get them from underlying hidden select element.
using jquery eg.
$('.select1 option:selected')
I think the cleanest way to do this. Is to take advantage of html5 select element underlying SumoSelect.
HTML
<select multiple="multiple" class="testSelAll" id="multi-select">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Javascript
var values = $('#multi-select').val();
This line will return a string list of the values selected.

Find previous value of drop down list on change event [duplicate]

This question already has answers here:
get previous selected dropdown item
(2 answers)
Closed 9 years ago.
I have drop down list declared like :
<asp:DropDownList ID="myDropDown" width="300" CssClass="textboxda"
AutoPostBack="True" runat="server" onmousewheel="return false;" />
Drop down list change method
myDropDown.Attributes.Add("OnChange", "return OnChange();");
function OnChange()
{
var $j = jQuery.noConflict();
var sel = $j(this).prevAll("#myDropDown:first"),
val = sel.val(),
text = sel.find(':selected').text();
alert(text);
}
I am populating this drop down dynamically.
I am fetching the last/previously selected text of the drop down, but this is not working.
Please suggest.
myDropDown.Attributes.Add("OnChange", "return OnChange(this);");
after that you can put another attribute for current selected item
myDropDown.Attributes.Add("previous", "your default selected value");
after that your function like this
function OnChange(args)
{
var previousVal=$(args).attr('previous');
var newVal=$(args).find(':selected');
alert(previousVal);
alert(newVal);
$(args).attr('previous',newVal);
}
<select id="countries">
<option value="">Select country</option>
<option value="68">Russia</option>
<option value="20">United States</option>
<option value="73">Albania</option>
<option value="143">Algeria</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('#countries').on('change', function() {
var $selected = $(this).find(':selected');
console.log('Prev = ', $selected.prev().text());
console.log('Next = ', $selected.next().text());
console.log('Last = ', $(this).find('option:last').text());
});
});
</script>
http://jsfiddle.net/S85rY/2/
try this
<select id="countries" previous="" onchange="countrychange(this)">
<option value="">Select country</option>
<option value="68">Russia</option>
<option value="20">United States</option>
<option value="73">Albania</option>
<option value="143">Algeria</option>
</select>
<script type="text/javascript">
function countrychange(args){
var previousVal=$(args).attr('previous');
var newVal=$(args).find(':selected');
alert(previousVal);
alert(newVal);
$(args).attr('previous',newVal);
}
</script>
You want jquery? DEMO http://jsfiddle.net/yeyene/3vRs9/
JQUERY
$(document).ready(function() {
$("#mySelect").on('change', function() {
alert('Changed selected: '+$('#mySelect option:selected').val());
});
});

Changing the selected option of an HTML Select element

In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';​​​​​​​​​​
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})

Categories

Resources