i'm having a little trouble with disabling a "select" input.
I need to disable "cidade" whenever nothing is selected on "estado".
here's my code:
<select id="estado" class="select_customized">
<option></option>
<option value="sp">São Paulo</option>
<option value="mg">Minas Gerais</option>
<option value="rj">Rio de Janeiro</option>
</select>
<select id="cidade" class="select_customized">
<option></option>
<option value="sao-paulo">São Paulo</option>
<option value="minas-gerais">Minas Gerais</option>
<option value="rio-de-janeiro">Rio de Janeiro</option>
</select>
And here's the script i'm using:
$("#cidade").select2("enable", false);
$("#estado").on('change',function(){
var is_empty = $('#estado').is(":empty");
if(is_empty){
$("#cidade").select2("enable", false);
}
else {
$("#cidade").select2("enable", true);
}
});
this kinda works, but whenever i choose something on the "estado" input, and clear it again, "cidade" does not disable again... any suggestions?
You probably want to use the select2 call to check if the selection box is empty, instead of going into the original #estado box you created (since that is hidden by select2).
Your call:
var is_empty = $('#estado').is(":empty");
then can be changed to something like:
var is_empty = $('#estado').select2("val") == "";
and that did the job for me. Note that the actual comparison above will differ a bit depending on for example if you are using a multi-valued selection box.
I think is that you need actually. You just need to set the .on('change') to make it works, like this fiddle.
UPDATE: easier than I thought.
http://jsfiddle.net/fczo7tLq/2/
$("#cidade").prop('disabled', 'disabled');
$("#estado").on('change', function() {
var that = $("#estado option:selected").val();
if (that !== "empty") {
$("#cidade").prop('disabled', false);
} else {
$("#cidade").prop('disabled', 'disabled');
}
});
Related
Based on this useful topic Use jQuery to change a second select list based on the first select list option I try to adapt the code for my purposes.
My problem is that for some reasons I cannot have the exact same integer values in my 2 selection. I only can provide something close as:
<select name="select1" id="dropDown">
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW<option>
</select>
The js to be modified is:
$("#dropDown").change( function() {
if ( $(this).data('options') == undefined ) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data( 'options', $("#dropDown_2").find('option').clone() );
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$("#dropDown_2").html(options);
} );
I know that there are some js techniques to subtract substrings and similar stuff. But my skills are not so good to exactly say how. Is there anyone willing to help me? I need to filter the second options with its values based (but not identical) on the values of the first. Hope I explained myself sufficiently. Many many thanks!
EDIT
First of all sorry for not explaining myself sufficiently. I have to add that I cannot change the markUp!
So I inserted an each loop before the code that Shiran kindly delivered me to prepare it like so:
$("#dropDown_2").find('option').each( function() {
var $this = $(this);
var val = $this.val();
var myFilter = val.slice(0,-3)
$this.addClass( myFilter );
// $this.data('filter', myFilter ); does not work don’t know why
} );
Which seems to work at least in principle. Yet, for reasons that remain obscure for me sadly my attempt to attach data-filter to my option elements wasn’t accepted. So I had to go for classes which worked (at least for the loop).
I then tried to modify the code ending up with the following:
$("#dropDown").change(function() {
var filters = [];
if ($(this).attr('class') == "") {
$(this).find("option").each(function(index, option) {
if ($(option).attr('class') != "")
filters.push($(option).attr('class'));
} );
} else {
filters.push($(this).attr('class'));
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option." + value ).clone().appendTo($("#dropDown_2"));
} );
} );
But as you can guess this didn’t work. :-(
And I also noted that the values of my filter array are the class (would be analogue to the filter value in the original) of my select not of the options of it. But obviously Shorans code did work well. What did I wrong here?
Please help, I am getting grey hair with this!! Thanks so much in advance!
$(this).data("options") gets:
<select data-options="the data here"> ==> "the data here"
Here's a working version:
(notice how I used data-filter in the second select and in the last each loop in the javascript part)
$(document).ready(function() {
var $options = $("#dropDown_2").clone(); // this will save all initial options in the second dropdown
$("#dropDown").change(function() {
var filters = [];
if ($(this).val() == "") {
$(this).find("option").each(function(index, option) {
if ($(option).val() != "")
filters.push($(option).val());
});
} else {
filters.push($(this).val())
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option").each(function(optionIndex, option) { // a second loop that check if the option value starts with the filter value
if ($(option).val().startsWith(value))
$(option).clone().appendTo($("#dropDown_2"));
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="select1" id="dropDown">
<option value="">All</option>
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW
<option>
</select>
In the following select box:
var sval=1;
function foo(v) {
sval=Number(v);
}
...
<select name="sval" onchange="
if (confirm('...?')) foo(this.value); else $(this).val(sval);">
<option value="1">1
<option value="2">2
<option value="3">3
The idea is to confirm the selected item change. If not confirmed to change back to the old value.
if confirm returns true, all is working as expected
if confirm returns false, then the select always gets value 1, regardles of sval
Why changing the selected item does not work from inside the onchange handler?
EDIT: The following code based on ejay_francisco's answer does the proper job:
http://jsfiddle.net/4wCQh/33/
var vals = 1;
$("#svalue").change(function() {
if (confirm('...?'))
vals=Number(this.value);
else
$(this).val(vals);
});
but its not clear what is the reason that the inline code $(this).val(sval) resets the select to 1
I've modified your code and this is how i've done it
Working Fiddle :
Javascript :
$( "#svalue" ).change(function() {
if (confirm('...?')) {
vals =$('#svalue').val();
$('#svalue').val(this.options[this.selectedIndex].value);
}else{
$('#svalue').val(vals);
}
});
HTML :
<select id="svalue">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
EDITED :
here's how its done inline : working Fiddle
HTML:
<select name="sval" onchange="if (confirm('...?')) {foo(this.value);sval=(this.value);} else $(this).val(sval);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
Javascript :
var sval=1;
function foo(v) {
$('#svalue').val(v);
}
apparently you forgot to change the value of sval to whatever the user has previously clicked. the code is sval=(this.value); on the onchange part.
Try
I think else part is not neccessary
Change to
<select name="sval" onchange="
if (confirm('...?')) foo(this.value);">
Your approach is absolutely horrible.
When ever you inline JavaScript events on elements it just looks ugly.
Why are you wanting to set the select value to the value it has as the currently selected value?
Could you just skip this $(this).val(sval = this.value;); and only have this sval = this.value;
I'm just really a huge fan as to keeping the code and values to a bare minimum where variables are not needed and also where code is not needed.
Give this a shot.
<script type="text/javascript">
var sval = 1;
var foo = function () {
if(confirm('...?')) {
$(this).val(sval = this.value);
}
else
{
$(this).val(sval);
}
};
setTimeout(function () {
document.getElementById('sval').onchange = foo;
}, 100);
</script>
<select id="sval">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I have found the reason the code is not working.
It came out that there are differences between execution in fiddle and browser which made tracking the problem harder.
In the inline code of the onchange event a variable with the same name as name="sval" gets defined and because the name is the same with the integer variable from the global context, the code is not using the proper value to change select's value.
So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.
This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.
onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.
my html is:
<select onChange= "getDrop2()" id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
My Javascript is:
function getDrop2(){
var choice = $("#drop1").val()
alert(choice);
}
The output of the alert statement is just blank.
In jQuery, you're better off doing something like:
<select id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
With the following JavaScript:
$(function(){
$('#drop1').change(function() {
var choice = $(this).val();
alert(choice);
}
});
The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.
Although what others have selected is a better approach. My answer is just to tell you why your code is not working
Try this
var choice = $('#drop1 option:selected').val()
Instead of
var choice = $("#drop1").val()
I'm really new to this and working on a JavaScript code and I want to see if a dropdownlist has any choosen value. How do i do that?
I tried:
var selectObj = form.document.getElementById('myListId');
var selectInd = selectObj.selectedInd;
and tried:
if(selectInd == "")
to check if it was empty.
What do I need to change to make it work?
Thanks in advance!
A drop-down, by design, always has a value selected. If you just want to leave an empty value first to not choose something for the user, you can simply check if it's value is empty.
document.getElementById("validate").onclick = function() {
if (document.getElementById("foo").value == "")
alert("invalid");
else
alert("valid");
};
Live example
According to comments, this might not work in older versions of IE. Be sure to test it there if you need to support those browsers.
HTML
<select id="myListId">
<option value="">- Select an option-</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Javascript
function checkvalue(){
var selectObj = form.document.getElementById('myListId');
if (selectObj.value != "") {/* DO something */}
}
Now you can execute this function on change of the select box, or when you submit the form, it is up to you.
Try to read this example.
You are trying compare a number (selectObj.selectedIndex) with a string (""), you should write something like this:
var selectObj = document.getElementById('myListId'),
selectInd = selectObj.selectedIndex,
selectedVal = selectObj.options[selectInd].value;
if(selectedVal== "") {
/* do your stuff*/
}
Only to notice: This only would work (detect a value equal to "") with an html like this:
<select id="myListId">
<option value="" selected="selected">Empty value</option>
<option value="1">Non empty value</option>
</select>
Or when the user has been selected the option "Empty value".
EDIT:
Try with this demo. This demo also works in IE7.