How can I determine what option is selected on a dropdown? [duplicate] - javascript

This question already has answers here:
Get selected value of a dropdown's item using jQuery
(31 answers)
Closed 7 years ago.
I have a dropdown menu of values:
<select class="notifications-dropdown">
<option value="val1">Val4</option>
<option value="val2">Val3</option>
<option value="val3">Val2</option>
<option value="val4">Val1</option>
</select>
I want to make it so when a user selects one of the options from the dropdown, that option has a 'selected' attribute toggled on. For example, if a user clicks the dropdown and selects Val3 then the DOM should change as follows:
<select class="notifications-dropdown">
<option value="val1">Val4</option>
<option value="val2" selected>Val3</option>
<option value="val3">Val2</option>
<option value="val4">Val1</option>
</select>
I am not sure what jQuery event to listen for to know when a user selects an option though. I tried listening for a change event on the .notifications-dropdown but the generated event object does not give me any indication about which option was selected. How can I determine what option is selected on a dropdown?

Just use .val() on your select list.
$('.notifications-dropdown').change(function() {
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="notifications-dropdown">
<option value="val1">Val4</option>
<option value="val2">Val3</option>
<option value="val3">Val2</option>
<option value="val4">Val1</option>
</select>
this when used inside of a jQuery callback is the element which the event occurred on.

You seem to be on the right track with the change event. But that is the thing, the change event just tells you that the field/option selected has changed, it, and any other event listener, will not provide a value.
To get the value, you will need to reference jQuery like so:
$('.notifications-dropdown option:selected').text();
or to get the value of the option selected, you can reference it like so:
$('.notifications-dropdown option:selected').val();

You were on the right track:
// on Dom-ready
$(function() {
// bind the 'change' event
$('.notifications-dropdown').change(function() {
// $(this).val() will have the selected value
alert($(this).val());
}).change(); // fire it once on page-load if you need to do anything based on the current value
});
The user's action of selecting a new option will modify the DOM element's selected attribute -- you don't need to do that programmatically.

Use below code on a jquery change event. Assume, select tag has id="selectId"
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();

Use .val() method
Get the current value of the first element in the set of matched elements or set the value of every matched element.
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
$('.notifications-dropdown').change(function() {
alert($(this).val());
});

Related

get selector value after selection?

I'm curious as to if it is possible to get this selector value after the user selects a value?
<select>
<option>test1</option>
<option>test2</option>
</select>
//Idea of what i'm trying to accomplish
select.addEventListener('select',()=>{
console.log(select.value);
})
I'm trying to use this value data to determine which item to load and view before you submit the form.
First of all, you have to locate your select element in the script. To do this, you need to provide it with a specific id.
<select id="test_selector">
<option>test1</option>
<option>test2</option>
</select>
Then you can use this id to access that selector in the JS. In order to get the updated value, chain it with the change event listener. Its callback receives the event parameter which contains the info you need.
document.getElementById('test_selector').addEventListener('change', event => {
console.log(event.target.value);
});
Another option is to do it on jquery if you feel more comfy with it
Give your select an id
<select id="id_selector">
<option>test1</option>
<option>test2</option>
</select>
Use a jquery .change function to get the value of the selected option
$('#id_selector').change(function(){
console.log($('#id_selector').val());
//or console.log($(this).val()); to make the code shorter
});
Try this
select.addEventListener('select',(e)=>{
console.log(e.target.value);
})

Reset Select Menu to default in the on change event

hello i'm trying to reset the select menu to the defaul option immediatly after new item is selected. I never want the select menu to show the selected item. I have this select menu:
<select name="new-effect" id="new-effect">
<option selected value="add">Add New Effect</option>
<option value="waves">Waves</option>
<option value="spiral">Spiral</option>
</select>
which is handled by
$( function() {
$( "#new-effect" ).selectmenu({
change: function( event, data ){
add_new_effect(data.item.value);
}
});
});
It gets the value, but i can't get it to reset. I've tried the following:
$("#new-effect").val("");
$("#new-effect").val("add");
$("#new-effect").prop('selectedIndex',0);
None of them work and they all result in selected item being shown
If you're just trying to reset the select element back to a default value, there's a couple ways to do it. Here's is one way that will work:
https://jsfiddle.net/mswilson4040/gnLkyexa/5/
<select placeholder="Select a value..." id="new-effect">
<option selected value="add" class="default-selection">Add New Effect</option>
<option value="waves">Waves</option>
<option value="spiral">Spiral</option>
</select>
const defaultOption = $('#new-effect').find('.default-selection');
$('#new-effect').change(e => {
const value = $('#new-effect').val();
console.log(value);
$('#new-effect').val(defaultOption.val());
});
Basically, you need to capture the default value that you want to reset everytime. Once you have that, in your change event, obtain the selected value and do what you need to with it. After that is done, you can then just set the select dropdown back to the value you need it to.
The selected attribute in the HTML is fine to have for the initial render, but that will go away once someone changes the value (which is why you can't rely on it for everything).
Add this to your CSS
option:checked {
display:none;
}
If you only need this to happen for a specific list, then change the selector to #new-effect option:checked.
Now for your JS, do this
$("#new-effect").change(function(e) {
e.target.value = 'add';
});
If you have more than one list, you'll want to programatically select the default option instead of hardcoding it like I did here.

jQuery trigger click (or select) on chosen dropdown option

I'm trying to trigger a click function on page load with jQuery on chosen's dropdown option so that the follow-up action can take place but haven't been able to get it work.
I've tried:
jQuery("document").ready(function() {
setTimeout(function() {
jQuery("customlist_chzn_o_2").trigger('click');
},10);
or
jQuery("document").ready(function() {
jQuery('#customlist').val(9).trigger("chosen:updated")
});
or
jQuery("document").ready(function() {
jQuery('#customlist_chzn_o_2').trigger("chosen:updated")
});
None of them are working, please note that my select's id is #customlist the id of dropdown element in chosen which I need to click is #customlist_chzn_o_2 and the value of the select option is 9
If I understand you correctly, you need to trigger the change event on the original select, not on the custom or his options.
When working with form fields, you often want to perform some behavior after a value has been selected or deselected. Whenever a user selects a field in Chosen, it triggers a "change" event on the original form field
But when you change the original select value, than you should trigger chosen:updated.
If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.
https://harvesthq.github.io/chosen/#change-update-events
var sel1 = $('#sel1').chosen({width: '150px'}).change(function(){
console.log($(this).val());
});
sel1.trigger('change');
var sel2 = $('#custom_field').chosen({width: '150px'});
//$('button').click(function() {
$(document).ready(function() {
sel2.val('9');
// Than you should trigger the "chosen:updated"
sel2.trigger('chosen:updated');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.min.css" rel="stylesheet"/>
<select id="sel1">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
<hr />
<select id="custom_field">
<option>option 1</option>
<option>option 2</option>
<option>9</option>
</select>
<button>Set custom_field's value to "9"</button>
chosen doesn't have a direct trigger for click/select. We have to take the underlying select element's selected value and explicitly run the contents of chosen's .on('change',..) .
// Original trigger function thru chosen.js
$('#custSelect').on('change', function(evt,params) {
var custID = params.selected;
//that gives us the VALUE of the selected option
// below are the executive actions being done
if(custID) chooseOne(custID);
});
// Programmatically changing the selected option
var e = document.getElementById('custSelect');
e.selectedIndex +=1 ; // selecting next option in the dropdown list
$('#custSelect').trigger('chosen:updated'); // this is only COSMETIC.
// updates the view to match underlying select element
// but doesn't trigger chosen's on-change event
// now we retrieve the newly selected option's value:
var custID = e[e.selectedIndex].value; // analogous to params.selected above
// ...and do the execution ourselves.
if(custID) chooseOne(custID);
Alternatively, don't rely on chosen's on-change at all, and make one for the original <select> html element instead. I won't go into that here.
To actually "trigger" the click event as if it was made by a user, I had to combine multiple answers as follows:
$('#sel1')[0].selectedIndex = 0; // make selection
$('#sel1')[0].focus(); // set the focus
$('#sel1').trigger('change'); // actually trigger click event for listeners

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

How to select an <option> within a dropdown by value and assign the "selected" attribute to it?

For a dropdown list (<select>), at some point I need to find the option with a given value and assign the selected attribute to it.
e.g.:
<select id="font-size">
<option value="12">12px</option>
<option value="13">13px</option>
<option value="14">14px</option>
</select>
In the example above, how would I add the "selected='selected'" attribute to the option with the value 14?
This would do it:
$('#font-size').val(14);
NB: this sets the selected property on the required <option> element - the attribute represents the initital value of the dropdown when the page is first loaded.
If you need this to set the initial value when the page is loaded then use,
$(document).ready(function() {
$('#font-size').val(14);
});
or else if you want it the value of which user has selected after the loading use this,
$(document).ready(function() {
$('#font-size').change(function() {
alert($(this).val());
});
});
document.getElementById("font-size").value = "14";

Categories

Resources