javascript: changing "multiple" attribute of the "select" element does not work - javascript

Windows 7 64 bit, Chrome version 61.0.3163.100
I have a html page with a listbox:
<select id='lst' multiple>...</select>
I need to disable multiple items selection for this listbox.
I have a javascript function with this code:
lst = document.getElementById('lst');
lst.multipe = false;
I have checked in the debugger - the value changed to "false".
But in another function called "onclick", it is "true" again.
And multiple items could be selected with [shift] or [ctrl] pressed.

The multiple attribute is a boolean attribute, and, according to the HTML specification:
The presence of a boolean attribute on an element represents the true
value, and the absence of the attribute represents the false value.
Use removeAttribute() instead:
const element = document.getElementById('select');
element.removeAttribute('multiple');
<select id="select" multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>

lst = document.getElementById('lst');
lst.removeAttribute('multiple');
lst.setAttribute('multiple', true);
<select id='lst' multiple>
<option>1</option>
<option>2</option>
</select>
Multiple is based on presence, so you need to remove or set it if need from javascript.

Related

HTML make <option> invalid

I have the following piece of code in a contact form for a site I am designing:
<select id="Category" name="Category">
<option value="0" selected="selected" disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
I would like set the menu such that the user cannot leave category as the selected option. Is there any way to do this with HTML? If not, how would I do it with JavaScript?
Thank you
According to the HTML5 spec,
Constraint validation: If the element has its required attribute specified, and either none of the option elements in
the select element's list of options have their
selectedness set to true, or the only option element in
the select element's list of options with its
selectedness set to true is the placeholder label option,
then the element is suffering from being missing.
If a select element has a required attribute
specified, does not have a multiple attribute specified, and
has a display size of 1; and if the value of the first
option element in the select element's list of
options (if any) is the empty string, and that option
element's parent node is the select element (and not an
optgroup element), then that option is the select
element's placeholder label option.
Therefore, you can use
<select id="Category" name="Category" required>
<option value="" selected disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
When the user click on any option, he can´t return the first one back. But he can submit form without change, then you need to validate via JS.
It's quite simple,
function validate() {
var select = document.getElementById('Category');
return !select.value == 0;
}
And the form in HTML:
<form onsubmit="return validate()">...</form>
Will disabling select work for you?
<select id="Category" name="Category" disabled>
<option value="0" selected="selected">Category</option>
...
</select>
Or maybe disabling all but selected option will work for you (as shown here: https://stackoverflow.com/a/23428851/882073)
Ideally, you would simply remove the selected attribute from disabled options on the server side when generating the HTML document to begin with.
Otherwise, if you are using JQuery, this can be done fairly easily with:
$('#Category').find('option:not([disabled])').first().prop('selected', true);
Add this to your ondomready event handler. This will force the first non-disabled option to be selected for this select element regardless of its options' selected attributes. The disadvantage of this method is that it will prevent the selected attribute from being able to be used at all with this select element.
On the other hand, if you are trying to create category headers within a select element, you should consider using an optgroup element instead, since that is the correct semantic markup for this:
<select id="Category" name="Category">
<optgroup label="Category">
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</optgroup>
</select>

Multiple Select bug in Firefox

I have a specific problem with multiple select values.
<form id="form-to-submit">
<select multiple="true" name="sel" id="sel">
<option id="0_1" value="0">Bacon</option>
<option value="1">Pickles</option>
<option id="0_3" value="2">Mushrooms</option>
<option value="3">Cheese</option>
</select>
</form>
<button id="setValues">Set Values</button>
JS:
$("#setValues").click(function() {
$("#sel").find("option").removeAttr("selected");
$("#0_1").attr("selected","selected");
$("#0_3").attr("selected","selected");
});
I've crated a JSfiddle which shows the problem:
When you click on Set Values button, it clears all options selected attribute, then sets it to selected for first and third options.
PROBLEM: In Firefox after second click on Set Values button, it clears the selection values.
In other browsers it works well.
Any ideas?
Instant solution!!!!
$("#0_1").prop("selected", true);
$("#0_3").prop("selected", true);
Some explanation ?!!?
So, what's the difference between .attr() and .prop()!!!
Basically, properties are of DOM elements whereas attributes are for HTML elements which are later parsed into DOM tree using browsers parser.
Because of some inconsistent behaviour amongst different browsers it's preferred to use .prop() instead of .attr().
Quoted from jQuery API Documentation :
"To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."
There are lot's of reasons you want to switch to .prop(). Here's a great thread that helped me to dive into more of .attr() and .prop() ;)
.prop() vs .attr()
Two things:
To set the selected state, use prop, not attr.
In CSS selectors, and id cannot start with a digit, so #0_1 and #0_3 are invalid selectors. (They happen to work because of an optimization in jQuery where something that's obviously an id selector on its own ends up going to getElementById instead of a CSS selector parser like querySelectorAll or Sizzle's own parser, but it's not something you should rely on. For instance, if you had an element with id="123" and an element inside it with class foo, $("#123 foo") would throw an error.)
Fixes:
<form id="form-to-submit">
<select multiple="true" name="sel" id="sel">
<option id="x0_1" value="0">Bacon</option>
<option value="1">Pickles</option>
<option id="x0_3" value="2">Mushrooms</option>
<option value="3">Cheese</option>
</select>
</form>
<button id="setValues">Set Values</button>
$("#setValues").click(function() {
$("#sel").find("option").removeAttr("selected");
$("#x0_1").prop("selected",true);
$("#x0_3").prop("selected",true);
});
Updated fiddle

jquery :selected always picks first element if none are selected

I have a select element
<select id='bill_to'>
<option value='a634jhj2'>test#c.com</option>
<option value='agfd4ghj2'>test2#c.com</option>
<option value='asdf634jhj2'>tes3#c.com</option>
<option value='agf2342d4ghj2'>test4#c.com</option>
</select>
If I do
$('#bill_to').find(':selected')
it returns the first option even though it is not selected.
If an option is selected
$('#bill_to').find(':selected')
works as expected and returns the correct option
What am I doing wrong? Is this a bug. This is driving me crazy.
I just want it to return [] if there is nothing selected
If there are no select option with selected attribute, first option will be the selected option by default. You can try adding another option to top that contains default value as follow.
<select id='bill_to'>
<option value='-1'>Select<option>
<option value='a634jhj2'>test#c.com<option>
<option value='agfd4ghj2'>test2#c.com<option>
<option value='asdf634jhj2'>tes3#c.com<option>
<option value='agf2342d4ghj2'>test4#c.com<option>
</select>
If nothing is selected you will get -1 and then you can proceed.
e.g. http://jsfiddle.net/fZv5t/
I have add closing tag of option "", without this I am having an empty option get inserted after each option in the dropdown. Issue can be seen in this Fiddle.
And the working example is on this Fiddle.
Try to add an empty option tag:
<select id='bill_to'>
<option></option>
<option value='a634jhj2'>test#c.com</option>
<option value='agfd4ghj2'>test2#c.com</option>
<option value='asdf634jhj2'>tes3#c.com</option>
<option value='agf2342d4ghj2'>test4#c.com</option>
</select>
Here you will get empty string, like this:
$('#bill_to').find(':selected').val();
If you can't or don't want to add a dummy first <option>, as an alternative you can grab and test the selected attribute of the element returned by :selected, for example:
var selection = $('#bill_to').find(':selected');
var really = (selection.attr('selected') != null);
var selval = really ? selection.val() : ""; /* or null or whatever */

Make the <select> Field Required? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I apply the required attribute to <select> fields in HTML5?
I'm using the html5 contact form from here but I'm having issues trying to make the <select> field required. Everything else works fine, just having trouble with this and the dev hasnt responded when I asked about the field. this is what I have
<select name="package" id="package" title="Please choose a package" class="required">
<option value="">------------------</option>
<option value="basic">Basic</option>
<option value="plus">Plus</option>
<option value="premium">Premium</option>
</select>
What am I missing to get this working correctly?
I believe that the top answer to this question is what you're looking for.
To quote,
This works for me - Have the first value empty - required works on empty values.
<select required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
check this: http://www.w3.org/TR/html-markup/select.html
global attributes
Any attributes permitted globally.
name = string
The name part of the name/value pair associated with this element for the purposes of form submission.
disabled = "disabled" or "" (empty string) or empty
Specifies that the element represents a disabled control.
form = ID reference NEW
The value of the id attribute on the form with which to associate the element.
size = positive integer
The number of options to show to the user.
multiple = "multiple" or "" (empty string) or empty
If present, indicates that its select element represents a control for selecting zero or more options from a list of options.
If not present, indicates that its select element represents a control for selecting a single option from a list of options.
autofocus = "autofocus" or "" (empty string) or empty
Specifies that the element represents a control to which a UA is meant to give focus as soon as the document is loaded.
required = "required" or "" (empty string) or empty
Specifies that the element is a required part of form submission.
so you require a required = "required" attribute to your <select>
If you have a better browser, you can try this (like in this thread):
<select required>
<option value=""></option>
<option value="basic">Basic</option>
<option value="plus">Plus</option>
<option value="premium">Premium</option>
</select>
, but still you should use JavaScript because not a lot of people have browsers that support HTML5 required attribute. It's not supported by IE and Safari.

Can I apply the required attribute to <select> fields in HTML?

How can I check if a user has selected something from a <select> field in HTML?
I see <select> doesn't support the new required attribute... do I have to use JavaScript then? Or is there something I’m missing? :/
Mandatory: Have the first value empty - required works on empty values
Prerequisites: correct html5 DOCTYPE and a named input field
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
As per the documentation (the listing and bold is mine)
The required attribute is a boolean
attribute.
When specified, the user
will be required to select a value
before submitting the form.
If a select element
has a required attribute specified,
does not have a multiple attribute specified,
and has a display size of 1 (do not have SIZE=2 or more - omit it if not needed);
and if the value
of the first option element in the
select element's list of options (if
any) is the empty string (i.e. present as value=""),
and that
option element's parent node is the
select element (and not an optgroup
element),
then that option is the
select element's placeholder label
option.
The <select> element does support the required attribute, as per the spec:
http://dev.w3.org/html5/spec-author-view/the-select-element.html#the-select-element
Which browser doesn’t honour this?
(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)
Yes, it's working:
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
you have to keep first option blank.
You can use the selected attribute for the option element to select a choice by default. You can use the required attribute for the select element to ensure that the user selects something.
In Javascript, you can check the selectedIndex property to get the index of the selected option, or you can check the value property to get the value of the selected option.
According to the HTML5 spec, selectedIndex "returns the index of the first selected item, if any, or −1 if there is no selected item. And value "returns the value of the first selected item, if any, or the empty string if there is no selected item." So if selectedIndex = -1, then you know they haven't selected anything.
<button type="button" onclick="displaySelection()">What did I pick?</button>
<script>
function displaySelection()
{
var mySelect = document.getElementById("someSelectElement");
var mySelection = mySelect.selectedIndex;
alert(mySelection);
}
</script>
You need to set the value attribute of option to the empty string:
<select name="status" required>
<option selected disabled value="">what's your status?</option>
<option value="code">coding</option>
<option value="sleep">sleeping</option>
</select>
select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input -> raising the required message.
w3schools
The value attribute specifies the value to be sent to a server when a form is submitted.
Example
<form action="">
<select required>
<option selected disabled value="">choose</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
<option value="grey">grey</option>
</select>
<input type="submit">
</form>
try this, this gonna work, I have tried this and this works.
<!DOCTYPE html>
<html>
<body>
<form action="#">
<select required>
<option value="">None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
</body>
</html>
Make the value of first item of selection box to blank.
So when every you post the FORM you get blank value and using this way you would know that user hasn't selected anything from dropdown.
<select name="user_role" required>
<option value="">-Select-</option>
<option value="User">User</option>
<option value="Admin">Admin</option>
</select>
first you have to assign blank value in first option.
i.e. Select here.than only required will work.
Works perfectly fine if the first option's value is null. Explanation : The HTML5 will read a null value on button submit. If not null (value attribute), the selected value is assumed not to be null hence the validation would have worked i.e by checking if there's been data in the option tag. Therefore it will not produce the validation method. However, i guess the other side becomes clear, if the value attribute is set to null ie (value = "" ), HTML5 will detect an empty value on the first or rather the default selected option thus giving out the validation message. Thanks for asking. Happy to help. Glad to know if i did.
In html5 you can do using the full expression:
<select required="required">
I don't know why the short expression doesn't work, but try this one.
It will solve.
Try this
<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>
You can do it also dynamically with JQuery
Set required
$("#select1").attr('required', 'required');
Remove required
$("#select1").removeAttr('required');

Categories

Resources