get the selected item in dropdown not working - javascript

I have a dropdown; I need to get the value of selected item; but it keeps saying undefined;
Here is the Jsfiddle
Am I doing something wrong?
<select class="ddl_status" id="status_ddl_20" style="display: none">
<option value="Active">Active</option>
<option value="InActive">InActive</option>
</select>
$(document).on('change', '.ddl_status', function() {
var parent= this.parent();
alert((parent option:selected).val());
});

Use this.value
$(document).on('change', '.ddl_status', function() {
alert(this.value);
});
There is no need to get the parent element and find the selected option again - the selected options value becomes the select value.

I updated your fiddle
$(document).on('change', '.ddl_status', function() {
alert($(this).val());
});

I'm guessing your fiddle was supposed to have something other than display:none?
Also, just use $(this).val(); (Hint: $ is jQuery)

Related

How to disable non selected options in select boxes using jQuery?

I have a model in Laravel that can be edited with dynamic form but i want to prevent changing the selected option in select box so when i open the edit page i should be able to see the select boxes with selected items but all other options should be disabled.
Maybe i could just select all select with jQuery and disable all non selected values?? How to do that?
I have tried this:
// disable non selected items
$('select').each(function(){
$('option').each(function() {
if(this.selected) {
this.attr('disabled', true);
}
});
});
But it doesn't work, i just need a little help
this is the select box and all others are the same:
<select name="car">
<option selected="selected" value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
just other values selected
Your code has two problems.
First: you should check if option isn't selected (!this.selected) then disable it.
Second: this.attr('disabled', true) doesn't work in jQuery. You should use $(this) instead.
$('select').each(function(){
$('option').each(function() {
if(!this.selected) {
$(this).attr('disabled', true);
}
});
});
$('select').each(function(){
$('option').each(function() {
if(!this.selected) {
$(this).attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="car">
<option selected="selected" value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Note that first .each() loop in you code is additional. The bottom code is enough.
$('option').each(function() {
!this.selected ? $(this).attr('disabled', true) : "";
});
$(function(){
var Obj=$('select').find('option');
$.each(Obj,function(){
$(this).is(":selected") ? "" :$(this).attr('disabled',true);
});
});
You can replace "this" by "$(this)" and add "!" in the if and it can work:
$('select').each(function(){
$('option').each(function() {
if(!$(this).selected) {
$(this).attr('disabled', true);
}
});
});
Ok I am not really sure what you want to do, but I can fix your first code snippet for you:
// disable non selected items
$('select').each(function(){
$('option').each(function() {
if(!this.selected) {
$(this).parent().attr('disabled', true);
}
});
});
This is just an update for others:
I have found (for me even better solution)
https://silviomoreto.github.io/bootstrap-select/examples/#disabled-select-box
with this plugin you can set the select box to disabled and then you can see what was previously selected and you can't change it.
Just load the plugin in your view and add class .selectpicker and set the select box to disabled and it looks like this:

Bootstrap selector for multiselect- select all option

So what i need is an select all option in multiple bootstrap selector as an option so i just create a select as
<select class="form-control selectpicker" multiple>
<option value="all">All</option>
<option value="1">Dog</option>
<option value="2">Cat</option>
<option value="3">Tiger</option>
</select>
And when i click All it will remove all other options except all, and if i click any other than All then it need to remove all options
What i tried is like
$(".selectpicker").change(function(event){
if ($( this ).find("option:first").is(':selected')) {
$( this ).find("option").prop('selected', false);
$( this ).find("option:first").prop('selected', true);
} else {
$( this ).find("option:first").prop('selected', false);
}
});
But once All clicked then always all is activated and nothing can be clicked, i even tried to get value on onclick event but due to bootstrap selectpicker i can able to get it?
Any tricks to made this possible? i can do this with static variable for one selecpicker but can't able accomplish with multiple selectpicker in a form.
New edit
Here is a working DEMO
$('.selectpicker').selectpicker();
var all = $('option[value=all]');
$('.selectpicker').change(function() {
var all = $('option[value=all]');
var thisVal = all.html();
if (all.is(':selected')) {
$('.selectpicker').selectpicker('deselectAll');
$('ul.dropdown-menu > li[rel=0]').addClass('selected');
$('span.filter-option').html(thisVal);
} else {
$('ul.dropdown-menu > li[rel=0]').removeClass('selected');
}
});
I think you can do something like
$("#multiple-select option").prop("selected", "selected");
$('#multiple-select').selectpicker('refresh');
Must use prop.

Using Jquery to show and hide elements based on an input

I have been trying to create a form which changes depending on the users entry. So far I have been successful in using a radio input to change which content is to be shown, but I am having trouble editing the JS to work with a drop down menu.
HTML
<div class="show-and-hide-content">
<select>
<option></option>
<option data-type="true">true</option>
<option data-type="false">false</option>
</select>
<div class="hidden content content-true">You have selected true.</div>
<div class="hidden content content-false">You have selected false.</div>
</div>
CSS
.hidden {
display:none;
}
Javascript
$(function () {
$('.show-and-hide-content').each(function (i) {
var $row = $(this);
var $selects = $row.find('select');
$selects.on('change', function () {
var type = $(this).attr('data-type');
$row
.find('.content').hide()
.filter('.content-' + type)
.show();
});
});
});
Working radio button JSFiddle
Non working drop down JSFiddle
I know that the JQuery is finding the right elements and is changing the display of them, but it never changes the display to make them visible. I think the problem may be that the JS isn't correctly getting the data-type variable from the option's.
I want the JQuery to work as intended and show the correct divs based on the users selection.
How can I amend the code to do this? Thanks for helping.
You now got:
var type = $(this).attr('data-type');
Since the function is called on the <select>, you select the data-type attribute of the <select> (which is defined), and not from the <option>.
So, you'll need to find the selected <option>:
var type = $(this).find('option:selected').attr('data-type');
Check the updated Fiddle.
[EDIT]
If you want to simplify your code, you could use this:
$(function () {
$('.show-and-hide-content select').on('change', function() {
$(this).parent().
find('.content').hide()
.filter('.content-' + $(this).find('option:selected').attr('data-type') ).show();
});
});
Demo.
Or change your select data-type to value and use
var type = $(this).val();
DEMO
Try this one
$(function () {
$('#select').on('change', function () {
var selctedval = $(this).val();
$('.content').hide();
$('.content-' + selctedval).show();
});
});
This will use whatever value you have in the "data-type" attribute and match it to the "content-" class that you have on the message. If there is no matching message then, no message will show.
$('.show-and-hide-content select').on('change', function(){
var selected = $(this).find('option:selected').data('type');
$('.content').addClass('hidden');
$('.content-' + selected).removeClass('hidden');
});
Here is a fiddle

How to get dynamically a value of a select tag?

I want to get dynamically the value of a select tag in my form.
I do this actually
<select name="media_types_id" id="type">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<script>
var option = $("#type option:selected").val();
console.log(option);
</script>
but this return the value of the option selected and it doesn't change when I change the option in my form. i select 1 and if I select 2 after it stays at value 1...
Bind change event to your <select> element and use its value:
$("#type").on("change", function() {
var option = this.value;
console.log(option);
});
Also note that event binding should be done when the DOM is loaded, so either place this code right before </body> or use $(function() { }); handler.
Try Following use change() event to get the selected value of a drop down list
$("#type").on("change",function(){
var Option = this.val();
console.log(Option);
});
but your code runs globally. so for the first time , when page loads 1 is the selected value.
try your code inside change event
i.e.
$('#type').on("change",function(){
var option = $("option:selected",this).val();
console.log(option);
});
You need to bind change event to your select list:
<script>
$(function() {
$("#type").change(function() {
console.log($(this).val());
});
});
</script>
Use event handlers.
Event handlers call a function every time something happens.
Pure JS
var option = document.getElementById("type").value;
document.getElementById("type").onchange = function(e) {
option = this.value;
}
Example: http://jsfiddle.net/howderek/FnT9T/3/

jQuery prevent change for select

I want to prevent a select box from being changed if a certain condition applies. Doing this doesn't seem to work:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
I'm guessing this is because by this point the selected option has already changed.
What are other ways of doing this?
Try this:
http://jsfiddle.net/qk2Pc/
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
In the event someone needs a generic version of mattsven's answer (as I did), here it is:
$('select').each(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
$('select').change(function() {
if(my_condition) {
$(this).data('lastSelected').attr('selected', true);
}
});
$('select').click(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:
var my_condition = true;
$("#my_select").mousedown(function(e){
if(my_condition)
{
e.preventDefault();
alert("Because my_condition is true, you cannot make this change.");
}
});
This will prevent any change event from ever occurring while my_condition is true.
Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:
//When select should be disabled:
{
$('#my_select').attr('disabled', 'disabled');
}
//When select should not be disabled
{
$('#my_select').removeAttr('disabled');
}
Update since your comment (if I understand the functionality you want):
$("#dropdown").change(function()
{
var answer = confirm("Are you sure you want to change your selection?")
{
if(answer)
{
//Update dropdown (Perform update logic)
}
else
{
//Allow Change (Do nothing - allow change)
}
}
});
Demo
None of the answers worked well for me. The easy solution in my case was:
$("#selectToNotAllow").focus(function(e) {
$("#someOtherTextfield").focus();
});
This accomplishes clicking or tabbing to the select drop down and simply moves the focus to a different field (a nearby text input that was set to readonly) when attempting to focus on the select. May sound like silly trickery, but very effective.
You can do this without jquery...
<select onchange="event.target.selectedIndex = 0">
...
</select>
or you can do a function to check your condition
<select onchange="check(event)">
...
</select>
<script>
function check(e){
if (my_condition){
event.target.selectedIndex = 0;
}
}
</script>
I was looking for "javascript prevent select change" on Google and this question comes at first result. At the end my solution was:
const $select = document.querySelector("#your_select_id");
let lastSelectedIndex = $select.selectedIndex;
// We save the last selected index on click
$select.addEventListener("click", function () {
lastSelectedIndex = $select.selectedIndex;
});
// And then, in the change, we select it if the user does not confirm
$select.addEventListener("change", function (e) {
if (!confirm("Some question or action")) {
$select.selectedIndex = lastSelectedIndex;
return;
}
// Here do whatever you want; the user has clicked "Yes" on the confirm
// ...
});
I hope it helps to someone who is looking for this and does not have jQuery :)
You might need to use the ".live" option in jQuery since the behavior will be evaluated in real-time based on the condition you've set.
$('#my_select').live('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
Implement custom readonly like eventHandler
<select id='country' data-changeable=false>
<option selected value="INDIA">India</option>
<option value="USA">United States</option>
<option value="UK">United Kingdom</option>
</select>
<script>
var lastSelected = $("#country option:selected");
$("#country").on("change", function() {
if(!$(this).data(changeable)) {
lastSelected.attr("selected", true);
}
});
$("#country").on("click", function() {
lastSelected = $("#country option:selected");
});
</script>
Demo : https://jsfiddle.net/0mvajuay/8/
This was the ONLY thing that worked for me (on Chrome Version 54.0.2840.27):
$('select').each(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select').click(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select[class*="select-with-confirm"]').change(function() {
if (!confirm("Do you really want to change?")) {
this.selectedIndex = $(this).data('lastSelectedIndex');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruits' class="select-with-confirm">
<option selected value="apples">Apples</option>
<option value="bananas">Bananas</option>
<option value="melons">Melons</option>
</select>
<select id='people'>
<option selected value="john">John</option>
<option value="jack">Jack</option>
<option value="jane">Jane</option>
</select>
This worked for me, no need to keep a lastSelected if you know the optionIndex to select.
var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;
$('#my_select').bind('mousedown', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
if anybody still interested, this solved the problem, using jQuery 3.3.1
jQuery('.class').each(function(i,v){
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
jQuery(v).on('change', function(){
if(!confirm('Are you sure?'))
{
var self = jQuery(this);
jQuery(this).find('option').each(function(key, value){
if(parseInt(jQuery(value).val()) === parseInt(self.data('lastSelected')))
{
jQuery(this).prop('selected', 'selected');
}
});
}
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
});
});
None of the other answers worked for me, here is what eventually did.
I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.
<body>
<select id="sel">
<option value="Apple">Apple</option> <!-- Must use the value attribute on the options in order for this to work. -->
<option value="Bannana">Bannana</option>
<option value="Cherry">Cherry</option>
</select>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>
<script>
$(document).ready()
{
//
// Register the necessary events.
$("#sel").on("click", sel_TrackLastChange);
$("#sel").on("keydown", sel_TrackLastChange);
$("#sel").on("change", sel_Change);
$("#sel").data("lastSelected", $("#sel").val());
}
//
// Track the previously selected value when the user either clicks on or uses the keyboard to change
// the option in the select box. Store it in the select box's data-* attribute.
function sel_TrackLastChange()
{
$("#sel").data("lastSelected", $("#sel").val());
}
//
// When the option changes on the select box, ask the user if they want to change it.
function sel_Change()
{
if(!confirm("Are you sure?"))
{
//
// If the user does not want to change the selection then use JQuery's .val() method to change
// the selection back to what it was previously.
$("#sel").val($("#sel").data("lastSelected"));
}
}
</script>
I hope this can help someone else who has the same problem as I did.

Categories

Resources