Get data attribute for selected dropdown options - javascript

I'm trying to post a custom data attribute on a select box option to a hidden form field.
Here's my html:
<select id="sampleorder" multiple="multiple">
<option value='xxx' data-amount='5'>Name</OPTION>
<option value='xxx' data-amount='15'>Name</OPTION>
<option value='xxx' data-amount='2'>Name</OPTION>
</select>
And jQuery
$('#submit_btn').click(function() {
var options = $('select#sampleorder');
var samplesSelected = options.val();
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
I'm guessing that my variable "sampleAmount" should look somewhat like this
var sampleAmount = options.val().data("amount");
But it's not giving me the expected results.
What would be a good approach to get the data attribute value per item?
Thanks!

why use jQuery? Just use event.target.options[event.target.selectedIndex].dataset.amount

Try this:
$('#submit_btn').click(function() {
var samplesSelected = $('#sampleorder').val(),
sampleAmount = $('#sampleorder option:selected').data("amount");
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});

In pure vanilla javascript you can use :
var sampleAmount = this.selectedOptions[0].getAttribute('data-amount'));
Example:
function SelectChange(event) {
console.log(event.selectedOptions[0].getAttribute('data-amount'));
}
<select onchange="SelectChange(this)">
<option data-amount="1">one</option>
<option data-amount="2">two</option>
<option data-amount="3">three</option>
</select>

Try this,
HTML
Add id attribute to your select drop down
like
<select id="sampleorder" >
....
SCRIPT
var sampleAmount = $('select#sampleorder option:selected').data("amount");
Fiddle http://fiddle.jshell.net/3gCKH/

Another vanilla JS answer:
var selectContainer = document.getElementById('sampleorder')
var selectedOption = selectContainer.selectedOptions.item()
var amount = selectedOption.getAttribute('data-amount')

I forgot to mention it has to be a multi select box, sorry.
With your help and a brief look into the jQuery documentation I've managed to solve it:
$("select#sampleorderm").change(function () {
var samplesSelected = options.val().join("::");
var samplesAmount = "";
$("select#sampleorderm option:selected").each(function () {
samplesAmount += $(this).data("amount") + " ";
});
$('input[name=sampleorder]').val(samplesSelected);
$('input[name=sampleorderquantity]').val(samplesAmount);
});

Related

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

append value in textarea from selected dropdown without removing previous value

Hello I'm developing web app using php I'm facing an issue in appending value from the dropdown to the textarea. It displays appended in html but not in textarea.
If I edit html in inspect element then the changes get affected.
Here is my code:
JS:
$('#txtfieldname').on('change',function() {
console.log($(this).val());
var fieldName = $(this).val();
$('#txttext2tpeechmessage').append('{{ '+fieldName+' }}');
});
HTML:
<select name="txtfieldname" id="txtfieldname" class="form-control">
<option value="">--Select--</option>
</select>
Any help will be appreciated..
Thank you in advance..
Try below code,
$('#txtfieldname').on('change',function() {
console.log($(this).val());
var fieldName = $(this).val();
$('#textarea').val($('#textarea').val() +fieldName)
});
Try This....
$('#txtfieldname').on('change',function() {
var fieldName = $(this).val();
var text = $('textarea').val();
$('textarea').val(text.concat(fieldName));});

How do I find a dropdown value from a dropdown label

Suppose I have a dropdown as
<select name="Countries" id="Countries">
<option value="USA">United States of America</option>
<option value="AUS">Australia</option>
</select>
Suppose on load of a page I get a sample text as "Australia" then I want to get its respective value as "AUS"
I want to get dropdown value from its label.
Would be something like this:
var e = document.getElementById("Countries");
var str = e.options[e.selectedIndex].value;
Thanks to everyone who helped me here.
Below is the solution to get label from the selected value of a droddown.
var e = document.getElementById("Countries");
var str = e.options[e.selectedIndex].innerHTML;
http://jsfiddle.net/mm18qrwd/1/
I think you don't have index of selected element,
hence,
var value = "";
Array.prototype.slice.
call(document.
getElementById("Countries").
options).
forEach(function(option){
if(option.text == "Australia") {
value = option.getAttribute("value")
}
})
alert(value);
if you are using JQuery, this code $('#Countries').val() will return what you want.

Displaying option selected from dropdownlist

Trying something that sounds simple but not working:
Allow a user to select an option from a dropdownlist and then have this displayed as an alert each time the user changes it. Here's what I've got so far:
<select name="pickSort" id="chooseSort" onchange="changedOption">
<option value="lowHigh" id="lowHigh">Price Low-High</option>
<option value="highLow" id="lowHigh">Price High-Low</option>
</select>
<script>
function changedOption() {
var sel = document.getElementsByName('pickSort');
var sv = sel.value;
alert(sv);
}
</script>
A better way of doing this without the inline stuff:
document.getElementById("chooseSort").onchange = function() {
alert(this.value);
};
jsFiddle here.
You need to call the function with parentheses changedOption()
<select name="pickSort" id="chooseSort" onchange="changedOption()">

Using div value like php variable

I have a script like this
<script type="text/javascript">
function showSelected(val){
document.getElementById
('selectedResult').innerHTML = "The selected number is - "
+ val;
}
</script>
<div id='selectedResult'></div>
<select name='test' onChange='showSelected(this.value)'>
<option value='1'>one</option>
<option value='2'>two</option>
</select>
The output is shown with
<div id='selectedResult'></div>
So, I want to use this a variable
Actually, I want to get drop down box value with out submit. This script make it, but I can use another suggestions
Thanks
I'm not sure I really understand the question, but if you want to get what's stored in the DIV, use:
var stuff = document.getElementById('selectedResult').innherHTML;
I can suggest you another alternative i think is more useful and you can use it in different way # your project.
In this example you click the options you one and insert them to option list, you can send them from your select name=test if you want, you just need to change it.
DEMO
This is the script you can catch item,links,images,attributes and add them to select box:
$(document).ready(function(){
$('li').on('click',function(){
$('#theSelect').append('<option SELECTED>'+$(this).find('img').attr('value')+'</option>');
var seen = {};
$('option').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
});
})
$('#del').click(function() {
var $list = $('#theSelect option');
var d = $list.length;
var b=($list.length-1);
$('#theSelect option:eq('+b+')').remove();
});

Categories