javascript selectIndex right value - javascript

I have two possible dropdown list that I'm working with. The first one looks like:
<select id="drop1" name="drop1">
<option value="">Select</option>
<option value="1">January</option>
<option value="2">February</option>
...
</select>
<input type="text" value="1" onclick="set(this.value);" />
and the second one looks like
<select id="drop2" name="drop2">
<option value="1">January</option>
<option value="2">February</option>
...
</select>
<input type="text" value="1" onclick="set(this.value);" />
How can I make sure that if the value chosen in set(this.value) is = 1 (January) for instance, I will end up selecting January and not -- neither Feb.

Your'll need to iterate over the options of your <select> until you find one whose value is 1:
function selectOptionWithValue(select, value) {
value = "" + value;
var options = select.options;
for (var i = 0, len = options.length; i < len; ++i) {
if (options[i].value == value) {
select.selectedIndex = i;
return;
}
}
}
<input type="text" value="1"
onclick="selectOptionWithValue(document.getElementById('drop1'), this.value);">

Related

Pushing data values of a multiple select Only pushes the first clicked option multiple times

I came accross a problem while using Javascript . I have a multiple select who I want to get all the data-type selected then push it to an array . But I got stuck in the first step of getting the data selected. It only Gets the first option selected then when i click on the other one it pushes again the same first value.
Here is my code :
<select multiple id="boox" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>
My Javascript Code :
var options = [];
$('#box').change(function() {
options.push($('#box').find("option:selected").data("type"));
console.log(options);
});
For example if I select item 2 it returns in the console :
22
Then If I click on item 3 , it returns :
22,22
I Hope someone could clarify what I am doing wrong.I will appreciate it !
Basically you need to loop through all the selected options and push the value to your options array. In below code I use jQuery each() function to loop through all the selected options and store their value in options array:
var options =[];
$('#box').change(function(){
options =[];
$('#box').find("option:selected").each(function(){
options.push($(this).data("type"));
})
console.log(options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="box" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>
Do it like this. Use change event and then access value.
var optVal = [];
var tempVal = [];
$(".box").change(function() {
$(".box option").each(function() {
var val = $(this).val();
var tempVal = $(".box").val();
if(tempVal.indexOf(val) >= 0 && optVal.indexOf(val) < 0) {
optVal.push(val);
console.log("Opt: " + optVal);
} else if(tempVal.indexOf(val) < 0 && optVal.indexOf(val) >= 0) {
optVal.splice(optVal.indexOf(val) , 1);
console.log("Opt: " + optVal);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select multiple class="box" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>

How to get value from select box in html table

I'm trying to retrieve a value from a select box in my HTML table. How can I select the selected value?
What I've tried so far:
this.cells[14].innerHTML;
this.cells[14].children[0].innerhtml;
this.cells[14].children[0].innerText;
The last one .innerText returns all the items in my select box......
var table2 = document.getElementById('table_items_program');
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function () {
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("select").value = this.cells[14].children[0].innerText;
}
}
<td><select class="selectpicker" multiple>
<?php while ($row9 = mysqli_fetch_assoc($result9)):; ?>
<option value="<?php echo $row9['id']; ?>"><?php echo $row9['id'];?>
</option>
<?php endwhile; ?>
</select></td>
<input style="display: inline" id="id" name="id">
<input style="display: inline" id="select" name="select">
The selected value from my selection box in my HTML table
How can I select the selected value?
You can get the selected index with the method HTMLSelect​Element​.selected​Index
But if I understand your trouble. You try to get the current values of your select. So you need to get the value of your selected options.
You can do it like:
document.getElementById('mySelect').onchange = function() {
let options = this && this.options;
let selectedValues = []
for (var i = options.length; i--;) {
let opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
console.log(selectedValues)
}
<select id="mySelect" multiple>
<option value="a"> a </option>
<option value="b"> b </option>
<option value="c"> c </option>
</select>
Implementation into your code example
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function() {
document.getElementById("id").value = this.cells[0].innerHTML;
var options = this && this.cells[14].children[0].options;
var selectedValues = []
for (var i = options.length; i--;) {
var opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
document.getElementById("select").value = JSON.stringify(selectedValues);
}
}
so simple...
ShowSelected.onclick = function()
{
console.clear()
document.querySelectorAll('.selectpicker option:checked').forEach(opt=>console.log(opt.value))
}
.selectpicker {
vertical-align: text-top;
}
choose one or more :
<select class="selectpicker" multiple size=6 >
<option value="a"> A element</option>
<option value="b"> B element</option>
<option value="c"> C element</option>
<option value="d"> D element</option>
<option value="e"> E element</option>
<option value="f"> F element</option>
</select>
<button id="ShowSelected"> Show Selected</button>
Welcome to Stack Overflow!
So, your <select> has the class selectpicker. We can use this to select your <select>!
Try the following to get your value:
document.querySelector(".selectpicker").value;
Or, if you have multiple <select>'s, you can use
[...document.querySelectorAll(".selectpicker")].forEach(opt => {
console.log(opt.value)
});
Hope that clears things up a little.

How to manipulate selected option's value to be the same as option text with JavaScript

I have this dynamic HTML / JavaScript form that is working great, but I found that when I click submit it is bringing over the value of the option as its index and not as the text within the option.
I have tried altering the JavaScript code but can not seem to figure out how to resolve this.
HTML
<!-- Category -->
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
JavaScript
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
var decision = new Option(decisions[i], i);
reasonsList.options.add(decision);
// console.log('decision', decision);
}
}
}
When I select the first Category option 'Order Inquiry' and console.log:
console.log('decision', decision);
I see the following in the Console for the Sub Categories:
<option value="0">Order Status</option>
<option value="1">Order Issue</option>
<option value="2">X</option>
Ideally I want to see this is the Console for the Sub Categories:
<option value="Order Status">Order Status</option>
<option value="Order Issue">Order Issue</option>
<option value="X">X</option>
You need to pass decisions[i] as second parameter in Option.
Syntax:new Option(text, value, defaultSelected, selected); More details Option
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var reason = document.getElementById('reason');
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
//This line is changed
var decision = new Option(decisions[i], decisions[i]);
reasonsList.options.add(decision);
console.log('decision', decision);
}
}
}
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
option HTML element has a value and text attribute.
var options = document.getElementById("dropdown").children;
for (var i = 0; i < options.length; i++) {
options[i].value = options[i].text;
}
<select id="dropdown">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select>

JavaScript - how to remove `options` by its `value`

I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)

How to select multiple value from a listbox

I have a below code where if I select one value, it works fine, but now I need such that when I select multiple values from the listbox, i have to get the value of selected values. How do i go about it?
Here is the code,
HTML Code:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple"
onchange="getUniqueValues(value)">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
JavaScript:
function getUniqueValues(value){
alert(value);
}
For instance:
If I select Apple, then I get alert saying apple, now if I select apple & mango, I have to get the alert having apple & mango values. Facing problem here.
Here is the code: http://jsfiddle.net/5VtE3/2/
Thanks in advance,
Here is an example on how to do it -
HTML -
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
​
JS -
window.onload = function () {
var listbox = document.getElementById('attributeNames');
listbox.onchange = function () {
for(var index = 0; index < this.children.length; index++) {
if (this.children[index].selected) {
console.log(this.children[index].value);
}
}
}​;
};
Live Demo.
If you dont mind using jquery, -
function getUniqueValues(){
var k=0;
var selected_list = {};
$('#attributeNames option').is(':selected').each(function(){
selected_list[k++] = $(this).val();
});
alert(selected_list);
}
OR
function getrUniqueValues(){
$('#attributeNames option').is(':selected').each(function(){
alert($(this).val());
});
}
You might want to try checkboxes
<input type="checkbox" name="fruit" value="apple">Apple<br/>
<input type="checkbox" name="fruit" value="banana">Banana
Or you should just try to make:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple" onChange="getUniqueValues()" >
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
</select>
function getUniqueValues(){
var values = this;
}
Try this:
<select id="attributeNames" onchange="getUniqueValues.call(this)" name="attributeNames" size="5" multiple="multiple">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
function getUniqueValues(){
for(var i = 0; i < this.options.length; i++){
if(this.options[i].selected)
alert(this.options[i].value);
}
}
jsfiddle: http://jsfiddle.net/5VtE3/7/
function getValue(id) {
var retval = "";
var lstdatabase = document.getElementById(id);
for (var i = 0; i < lstdatabase.options.length; i++) {
if (lstdatabase.options[i].selected) {
if (retval == "") {
retval = lstdatabase.options[i].value;
}
else {
retval = retval + ',' + lstdatabase.options[i].value;
}
}
}
return retval;
}

Categories

Resources