How to retrieve empty OPTION value if it's empty? - javascript

Considering we have this HTML:
<select id="my_select">
<option value="1">Foo</option>
<option value="2">Bar</option>
<option value="">Bork</option>
<option value="3">Hey!</option>
</select>
The proper way to get the chosen value would be:
var oS = document.getElementById("my_select");
alert(oS.options[oS.selectedIndex].value);
But if the third option, Bork, is chosen, the alert() will show "Bork" and not "" (empty string).
How do I retrieve the empty string?

Firstly, it doesn't. For me, in Chrome and IE8, your example alerts an empty string (jsFiddle).
If, however, there is no value set at all (jsFiddle), Bork is alerted. This is, I think, the issue you're coming up against. This is correct behaviour. As the MDC page says,
If it is not defined, its default value is the text content of the element.
You could, however, use the getAttribute method, which gives null if no elements are selected (jsFiddle).
var oS = document.getElementById("my_select");
alert(oS.options[oS.selectedIndex].getAttribute('value'));

alert(document.getElementById("my_select").value)
returns the empty string, or any defined value of the selected option.
no need to specify options[selectedIndex]
If there is no default selected index, the first option value is returned.
If there is no value attribute for the selected option,
the option's text is returned in a script alert in most browsers,
and is sent to the server (if the select has a name and a form action) in all browsers.

Related

What is the value of a select when a disabled option is selected?

I'm using following html to get the selected-by-default disabled option "Select a town" as a kind of placeholder.
<select name="town">
<option selected disabled value="xx">-- Select a town --</option>
<option value="1">Paris</option>
<option value="2">London</option>
<option value="3">Budapest</option>
</select>
Now I'd like to test if any option has been selected by the user, or if it's still empty.
I thought testing the select value using jquery ( $('select[name="town"]').val(); ) would return the value "xx".
Instead of that, .val() returns null.
I found no trace of this behaviour in the doc (http://api.jquery.com/val/).
Can I rely on .val() returning null when a disabled option is selected? Is it documented anywhere?
Or do I have to check against both null and the actual value of the value attribute ("xx" in the above example)?
You can not select a disabled option, therefore the value (no matter what you set it as) will always return null. This is the intended behaviour.
While the docs doesn't specify about disabled options, it does say
if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null
This would also be expected of disabled options too. You can still test for it though!
We can check whether the value returns null by using an if statement. The following if statement will return true if the value isn't null
if ($('select[name="town"]').val() != null) {
console.log('Option selected.');
}
If you want to test for the other options, you can replace != null with == value.
In essence you could use this as a multiple if, else if, else statement.
Alternatively, you can get the value of the disabled selected option this way:
$('select[name="town"] option[disabled]:selected').val();
Thanks to this SO answer.

Can't change selected option in a select

I have a select and I want it's selected option to change but I can't make it happen for some reason. This is the code that I have.
$("#ID option[value=grpValue]").prop('selected', 'selected').change();
If instead of using "grpValue" I type in the value manually for example value "3" it does work. But I want it to use grpValue.
So this for example does work.
$("#ID option[value=3]").prop('selected', 'selected').change();
What am I doing wrong in the first line?
Would appreciate the help, thanks in advance.
EDIT: I've already tried using option[value='grpValue'], doesn't work.
$(document).ready(function(){
$("#sel option[value='c']").attr("selected",true);
$("#sel option[value='c']").prop("selected",true);
});
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
<body>
<form>
<select id="sel">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</form>
</body>
</html>
you can use any one from prop() or attr() method both of useful
Is grpValue a variable? If so
$("#ID option[value="+grpValue+"]").prop('selected', 'selected').change();
will make the attribute selector do the work.
BTW, I think
$obj.prop('selected', true);
is the correct expression for prop.
$('#id_of_select').val('value_of_option_here');
Edit: To explain why the above code works. The first part:
Is the jQuery we use the following method to select an element by it's id, we could also select an element by it's class by simply changing the '#' to a '.'.
$('#id_of_select')
The statement following it refers to the value attribute that is attached to every input, select, textarea and button. The value is the string that is passed through when a form is submitted. For inputs this is the typed text, for selects it's the value of the selected option.
When we click an option in a select field, what we are actually doing is grabbing the value of the option and setting it as the selects value also, selects know what value is selected via the value, it can then grab the option text associated with this value. The code below (with a parameter) will set the value of the select field, in the same way it would if you were to click the option.
Note .val must have a parameter otherwise you are just asking jQuery what the value of the selected field is. With a value will set, without a value will get.
.val('value_of_option_here');
Hope this is a little more useful than my original answer, I've tried to break it down as much as possible though if it's a little confusing let me know.
Working example :
$("#ID option[value='b']").prop('selected', 'selected').change();
// if value in variable just replace $("#ID option[value="+valueInVar+"]")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" >
<option value = "a">a</option>
<option value = "b">b</option>
<option value = "c">c</option>
</select>

jQuery: unselect option in select element

I faced with a strange behaviour of select element. So, I have a select element with several options. One of option is empty - it's required by plugin to output placeholder.
I needed functionality that would clear selected options and I wrote something like:
$(element).val('');
$(element).find("option:selected").removeAttr("selected");
The thing is that "selected" attribute is still here and it's on old option - you can see it in the code sample.
So, I have 2 questions:
1) Why .val() method of jQuery library do not update "selected" attribute in options list?
2) Why I can not update "selected" attribute in my case? If I switch these statements it's working:
$(element).find("option:selected").removeAttr("selected");
$(element).val('');
Code sample:
$(function(){
$("#unselect").click(function(){
$("#lang_type").val('');
$("#lang_type").find("option:selected").removeAttr("selected");
alert($("#lang_type").html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="lang_type">
<option value=""></option>
<option value="01">01 - Language of text</option>
<option value="02">02 - Original language of a translated text</option>
<option selected="selected" value="03">03 - Language of abstracts</option>
<option value="04">04 - Rights language</option>
<option value="05">05 - Rights-excluded language</option>
<option value="06">06 - Original language in a multilingual edition</option>
<option value="07">07 - Translated language in a multilingual edition</option>
<option value="08">08 - Language of audio track</option>
<option value="09">09 - Language of subtitles</option>
</select>
<button id="unselect">Unselect</button>
EDIT:
You can use prop(false) property like this
$(function(){
$("#unselect").click(function(){
$("#lang_type").val('');
$("#lang_type").find("option:selected").prop('selected',false);
});
});
Like #yezzz said, read this :
Note: Do not use removeProp() method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
If I'm not mistaken, a multi-select can be initially unselected, but once any option is selected, it can not be unselected any more. RFC 1866 states in section 8.1.3:
The initial state has the first option selected, unless a SELECTED attribute is present on any of the elements.
This lets me to believe that one option MUST always be selected. Obviously, different browsers interpret this differently...
But it does not seem to be a jQuery issue, rather a browser implementation issue.
The selected attribute reflects merely the initial state of the select input. You shouldn't really care about removing it, as it affects nothing once a different option is selected (either by the user or by a script on your page).
The current state of the input can be read or modified via the selectedIndex property, where a value of -1 means no option is selected (which never is the default, as there always is an option selected initially). However, you seem to want to select a particular "empty" option.
Setting the value on a select box results in the corresponding option being selected, which, in your case, is the very first one.
The code probably does exactly what you want. So don't mind checking the HTML, as the selected attribute - again - is unrelated to the current state of the input.
The :selected selector, however, matches the elements that are currently selected. Your first snippet selects an option, thus making it :selected, then attempts to remove a non-existent attribute from it. The second snippet of yours assumes that the selection remains on the option that was initially selected, and then removes the attribute from it. What follows is the "empty" option getting selected, and no more steps need to be taken, as that's all it takes to select an option.
To summarize: you can safely drop all the code that deals with the removal of the selected attribute, as it doesn't affect the current state of the element, the state being already tied to the correct option.

jQuery val() on dropdown returns value "Array"

I'm stumped. I have a dropdown menu where a user selects an item.
<select name="rep-name" type="text" id="rep-name" size="" value="" >
<option value></option>
<option value="alex">alex</option>
<option value="ben">ben</option>
...
</select>
The value is then retrieved...
$('#rep-name').val()
and sent to a database.
Usually it works fine but in some cases, it sends the value 'Array' to the database. Interestingly, in those cases, the serialize function on the form still gets the correct value of the item. So in other words:
$('#run-pma-form').serialize() // works fine
$('#rep-name').val() // fails
It works fine in ~95% of cases and unfortunately, I don't have info on what browsers are being used, etc when it incorrectly returns 'array.' I'm just wondering if anyone has run into this issue or has any clue why it might be happening.
$("#rep-name")[n].val() will get you the value of any given option, but it's not correct to think of a select menu as having a value—what you want is the value of the currently selected option.
http://api.jquery.com/selected-selector/
$("#rep-name option:selected").val() should work.

Is there a simple way to know the starting value of a select?

I'd like to do this simply without saving the starting value of the select in an object.
if i have (when i load the dom):
<select>
<option value='1' selected>one</option>
<option value='2' >Two</option>
and than i later change the selection so that another option is selected, is there some kind of property that stores the value of the option that was originally selected?
I think this sholud work:
$("select option[selected]").val()
fiddle: http://jsfiddle.net/4dCMd/
Tested this way in different browsers: seems to be broken in IE7/8, works in last Chrome, FF and IE9
You should use the defaultSelected property of the options object to test if it was selected by default.
http://www.javascriptkit.com/jsref/select.shtml
use this
$('select').find('option[selected]').val();
DEMO
$('select').each(function(){
$(this).data('originalValue',$(this).val());
});
You could do this on .ready. It'll store the default values of every select in it's data object.
Oh just re-read your question and you said that's exactly what you don't want.
Well, i don't think there's another efficient way to do it so i'll leave it here anyway.
simple to use filter to get any default selected options:
var def = $("select > option").filter(function () {
return this.defaultSelected;
});
DEMO
DefaultSelected
Reflects the value of the selected HTML attribute. which indicates whether the option is selected by default.

Categories