How To Get Selected Value When <select> </select> changed Using JS - javascript

I am stuck & want to get selected the select option.
<select class="form-control" data-live-search="true" id="itemb">
<option data-tokens="All">All</option>
#foreach (var item in ViewBag.brandCategories)
{
<option>#item.brandName</option>
}
</select>
//search by brand name..
$("#itemb").change(function () {
var typp = document.getElementById("typ").value;
var type = encodeURIComponent(typp);
var brand = this.value;
window.location.href = '/mobiles_tablets/item/?type=' + type + '&search=' + brand;
});
In the above code just i get list in #foreach through #viewBag .but now I want when it return to the view it should get selected value.
please write js code?
Thanks.

This snippet of code will help you to get the selected value of select element. You can modify/change it through codepen check out the below link.
https://codepen.io/uicreation/pen/KZmXbw
var el = document.getElementById('yourId');
el.onchange = function(){
console.log(this.selectedOptions[0].value);
}
<select id="yourId">
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>

or if you want to get selected option index use this.
var el = document.getElementById('yourId');
el.onchange = function(){
console.log(this.selectedIndex);
}

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>

Setting the first value as default in dropdown list

Jquery to create new row :
var selectVal = $(parent).children().first().find('select').find('option[selectedGivenTo="true"]').val();
var newSelect = $(parent).children().last().find('select');
newSelect.each(function() {
var cloned = null;
cloned = $(this).clone();
cloned.val(selectVal);
I am trying to select the first value of dropdownlist as default value using jQuery as above but no value is selected & just displaying list in dropdown.I saw many references in stackoverflow but its not working for me.
HTML:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
jQuery:
$(function(){
$("select option:first").attr('selected','selected');
var _select = $('select')[0],
_v = _select.options[_select.selectedIndex].value;
alert(_v);
});
Demo
If you want to select it by value, then use the code below:
$('select option[value="defaultValue"]').attr("selected",true);
If you want to select via text contains in option, use the following code:
$('select option:contains("I am defualt Value")').prop('selected',true);

Jquery select variable by id

I am trying to get the content of a select option which is specified by the selected options.
I can get the selected options to tell me the data-parent but I can't use that to get the text of the parent option.
<select id="addCatSelectCats" multiple="multiple">
<option id="Cat55" data-parent="5">Parent Cat</option>
<option id="Cat357" data-parent="55">Sub Cat</option>
</select>
$(document).on('change', '#addCatSelectCats',function() {
$("#addCatSelectCats option").each(function(){
if($(this).is(':selected')){
var dataparent = $(this).attr('data-parent');
if(dataparent > 0){
var parent = $('#Cat'+dataparent).text();
alert(parent);
}
}
});
});
Where am I going wrong?
You could do with a little less code
$(document).on('change', '#addCatSelectCats',function() {
var parent = $("#addCatSelectCats option:selected").text();
alert(parent);
});

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

Adding to a HTML text field by clicking items in a multiple select box

I'm wondering if it is possible that when I click on an item in a multiple select box in HTML that it goes into another form box? Basically, when I click on something I want that text to go into a form. I've tried searching, but nothing seems to have an answer.
<form name="input" method="post" action="#">
Display Tag:<input type="text" name="taginput">
<input type="submit" value="Go">
<select name="tags" multiple>
<option value="C#">C#</option>
<option value="Java">Java</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Android">Android</option>
<option value="jQuery">jQuery</option>
<option value="C++">C++</option>
<option value="Python">Python</option>
<option value="HTML">HTML</option>
<option value="MySQL">MySQL</option>
</form>
To give an example, when I click on the Java option, I want Java to go into the input box called taginput. If I then click on the Python option, I want Java Python. Is this possible?
This will work, with plain javascript:
var sel = document.getElementsByName ('tags')[0];
sel.onclick = function () {
document.getElementsByName ('taginput')[0].value = this.value;
}
Demo here
A second version avoiding duplicates:
var sel = document.getElementsByName('tags')[0];
var choosen = [];
sel.onclick = function () {
var is_there = !!~choosen.indexOf(this.value);
if(is_there){return false;};
choosen.push(this.value);
document.getElementsByName('taginput')[0].value += this.value + ' ';
}
Demo here
You can do this, it finds the selected options, creates an array of text, then adds it to the text input.
$("select[name=tags]").change(function() {
var arrSelected = $(this).find("option:selected").map(function() {
return $(this).text();
}).get();
$("input[name=taginput]").val(arrSelected);
});
Demo: http://jsfiddle.net/SyAN6/
You can see this fiddle :
http://jsfiddle.net/ppSv4/
$('select option').on('click',function(){
$('#texthere').val( $(this).attr('value') );
});
You can do this using jquery, simply by checking for a change in the multi select box and then adding the newly changed data to the input field.
You can also the jsFiddle http://jsfiddle.net/eUDRV/85/
$("#values").change(function () {
var selectedItem = $("#values option:selected");
$("#txtRight").val( $("#txtRight").val() + selectedItem.text());
});

Categories