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.
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>
I've looked around and I don't see this being asked before.
I have a select box, like so:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
I want to add another option...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value of the option.
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
I wanted to know what the best way to do this is with plain old javascript - I'll use jQuery if I have to.
Any ideas? An example would be great as well.
Take a look at this code. I think this is what you're trying to do:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom. Then after you choose a custom value, it will rewrite the value of that the custom option element to the value you just entered in the prompt. I logged the new value after assigning it to show you that it is working.
Here is a fiddle: https://jsfiddle.net/ng7xvy05/
Your onchange event is the appropriate way to handle this. This is mostly a matter of user interface (UX) design though. To do this in the prompt fashion you ought to use parseFloat:
change() {
var value = prompt('You\'ve chosen Other. Please enter a value', '60');
if(value) {
value = parseFloat(value);
// apply it to your model
} else {
// apply NULL to your model
}
}
From a UXD point of view I would use a typeahead input. It would autosearch known answers but also allow the user to input their own. This is not standard html so you would need to write this yourself or use jquery. But from a user interface design point of view, prompts suck.
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');
}
});
so i have a working feature that when a user selects any option on my select input, will change the selects class.
This works fine, but what i want is that if the user selects the first option again, then the class gets changed back.
the first option is set as a placeholder, i cant give it a value as i only want the information to be posted if any other options are selected.
I also cant set the input as disabled as i want the user to be able to reselect it after, incase they dont want to post that data.
its a long check list and i am posting the data as an array.
here is a jsfiddle to what i currently have:
http://jsfiddle.net/SD7cd/1/
Code:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected">Select an option...</option>
<option value="1">Option 1</option>
</select>
JS:
document.getElementById("sel1").onchange = function() {
if(this.value != null && this.value != undefined)
{
this.className = "selectoption-okay";
}
};
I'd use the .selectedIndex property over the value like this:
document.getElementById("sel1").onchange = function () {
this.className = (this.selectedIndex != 0) ? "selectoption-okay":"selectoption";
};
jsFiddle example
One problem when you used if(this.value != null && this.value != undefined) is that the first option will have a value even though you didn't explicitly assign it. An option element's value will default to its contents if no value is expressly given, no it won't ever be null or undefined.
Per MDN:
The textual content of this attribute represents the label explaining
the option. If it is not defined, its default value is the text
content of the element.
Can you try this, When you select the option Select an option..., if you have not assigned the value='' then Select an option... will be taken as a value.
So Added
<option selected="selected" value="">Select an option...</option>
^^^^^^^^
HTML:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected" value="">Select an option...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Javascript:
document.getElementById("sel1").onchange = function() {
this.className = "selectoption";
if(this.value != '' )
{
this.className = "selectoption-okay";
}
};
DEMO: http://jsfiddle.net/SD7cd/4/
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()