Jquery, read data attribute from all divs that match proper pattern - javascript

I have html code that looks like this:
<select id="invoice_line_items_attributes_0_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="34" data-price="123.0">asdsad</option>
<option value="35" data-price="123213.0">asd</option>
</select>
<select id="invoice_line_items_attributes_1_product_id" class="select required form-control" name="invoice[line_items_attributes][0][product_id]">
<option value=""></option>
<option value="31" data-price="1223.0">asdsad</option>
<option value="32" data-price="12333213.0">asd</option>
</select>
And now I want to iterate through all this selects and when one of this change this value alert this date-price attribute. I trying to do this with the following code:
$('[id*="product"]').each ->
$(this).change ->
alert $(this).attr("data-price")
But It gaves me undefined instead of this data-price value.

Three things:
1) You do not need to iterate over select element individually and then bind the even. Selector will do that on its own for matched elements.
2) You need to find selected option and then get data price value.
3) use .data() instead of using .attr() to get data attribute values.
Use:
$('[id*="product"]').change(function(){
alert($(this).find('option:selected').data('price'));
});
Working Demo

That is because your select doesn't have data-attr, I think you want the selected options data-attr.
And to get data-attributes jquery provides .data function.
do like bellow.
$('[id*="product"]').change(function(){
alert($(this).find(':selected').data('price'));
});
DEMO

Related

vJS or jQuery -- set / get simplified selected option

I'm having trouble getting and setting the "simplified" selected value of a select using jquery or vanilla js. i.e. <option value="foo" selected> vs. <option value="foo" selected="selected">.
Below only works if the option is selected like below, but all the programmatic ways to set the value of a select option I have tried result in <option value="value" selected="selected">. I need to set and get the simplified selected.
const sortBySelect = document.getElementById('sortBy');
let currVal = sortBySelect[sortBySelect.selectedIndex].value;
console.log(currVal);
<select id="sortBy">
<option value="title" selected>Title</option>
<option value="date">Date</option>
<option value="name">Name</option>
</select>
I've tried these and all the permutations I could find on Stack:
$(`#sortBy option[value='${storageValue}']`).attr('selected', true);
$(`#sortBy option[value='${storageValue}']`).prop('selected', "selected");
Instead of using attr() or prop() functions, just directly set the select value by using the val() function
$('#sortBy').val('${storageValue}');

Set all selects lists by class

I have several input type="select" with the same class. All with the same option values. I'm iterating through an array and checking if the option value is in it. If it is then I want all those relevant option values to be selected. I tried with this JQuery but it doesn't update the select dropdown with the selected values:
JS
$(".contacts option").each(function() {
var x = $(this);
if($.inArray(x.val(), selected_values)!= -1){
x.prop('selected', true);
}
});
HTML
<select class="form-control contacts" name="publicPermissions" id="publicPermissions" multiple="multiple">
<option value="share">Share</option>
<option value="private">Private</option>
<option value="user">User Config</option>
<option value="work">Work</option>
</select>
I have several of these selects how can I update them all so they all have the relevent option values selected?
You just need to use .val() method. No need to use loop.
$(".contacts").val(selected_values);
DEMO
After you put some values in selected_values array, it should work. Here is a fiddle

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>

How to set dropdownlist to multiple values?

The syntax to set a dropdownlist to multiple values is as following:
$("#multiple").val(["Multiple2", "Multiple3"]);
My problem is that I don't know how many values I have. So how do I set a dropdownlist dynamicaly to multiple values with values from an array?
Your code should work as seen in this live demo.
Markup:
<select multiple="multiple" id="multiple">
<option value="1">item 1</option>
<option value="2">item 2</option>
</select>
Script:
$('#multiple').val(['1', '2']);
Result:
​
do a check to know if the array has more values:
if (array[i]) { //DO WHAT YOU NEED}
It's not clear to me what you're trying to achieve.
You can use an array as argument of val() and this is the result:
> Passing an array of element values allows matching <input
> type="checkbox">, <input type="radio"> and <option>s inside of n
> <select multiple="multiple"> to be selected. In the case of <input
> type="radio">s that are part of a radio group and <select
> multiple="multiple"> the other elements will be deselected.
That means that will affect in your case only a select with muptiple choice enabled (and not a simple dropdown list).
If, on the contrary by 'set to multiple values' means adding options to an existing select, val() is not built to do that (for this you can have a look here)

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