Static text in a select - javascript

I want my select to always show the same text, but "keep" the selected option value.
So e.g. my select always shows text "Language", but when I get the value of it in JS, it will return the value of selected option.
How do I achieve this? If there's no possibility for pure HTML + CSS, vanilla JS will do.
Edit: I want this because when i choose a value, I have a list of input boxes which get filled by this. They are then changeable; this select is only used to set the "base" of these inputs. I want this select to always show the same
text because I don't want to end up in a situation where select shows different text than actually the text in inputs that will be used.
Answer:
<select id="mySelect">
<option value="" hidden>Language</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
document.getElementById('mySelect').addEventListener('change', showSameValue)
function showSameValue() {
let select = document.getElementById('mySelect')
let firstOption = select.querySelector('option')
firstOption.value = select.value
select.selectedIndex = 0
}

Using the change event, you can capture the selected value then simply set the first option as selected and set its value to the selected value.
select = document.querySelector("select");
first = select.querySelector("option");
select.addEventListener("change",function(el){
first.value = el.target.value;
el.target.querySelector("option").setAttribute("selected",false)
el.target.selectedIndex = 0;
console.log(first.value);
});
<select>
<option value="">Language</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

This is a weird behavior but it can be done by
adding a hidden input element next to select
add the event listener to select (onchange) that would change the value of the hidden element and reset select to desired value 'Languages'
The key would be to have proper fields names, so when submitting the form select could be omitted and hidden would prevail.

You can store the selected value in a variable to meet your requirement and then use it wherever you need.
<select name="select" onchange="func(this.value);">
<option value="value1">Display always</option>
<option value="value2">Random Value</option>
</select>
And here's the Js function
var selected = "";
function func(selectedValue) {
document.getElementById( "select").selectedIndex = "0";
selected = selectedValue; // Use this after final selection
}

There are a few ways to achieve this, but using just a <select> would not be possible, I would not advise this on an accessibility UX principal.
One option would be to use a <span> or <div> that when clicked shows the options.

Related

Getting the value of a select button html/js

So I am trying to get the user input(value) of this select option button. Everything I look at online dosen't really tell me how to get this button value so I can use it and manipulate it, please help
You need a click event listener for this.
This code snippet demonstrate what you need to do:
// Get Select List
var favAnimal = document.getElementById("favAnimal");
// Add event Listener for any change in the selection
favAnimal.addEventListener("change", function() {
if (favAnimal != undefined && favAnimal.value != "Choose"){
//Do actions on selected option
console.log(favAnimal.value)
}
});
<select id="favAnimal">
<option value="Choose">choose</option>
<option value="Lion">Lion</option>
<option value="Shark">Shark</option>
<option value="Eagle">Eagle</option>
</select>
Given a select with some options
<select id="favAnimal">
<option value="Choose">Choose</option>
<option value="lion">Lion</option>
...
</select>
To get the value of the select you do it like this
var favAnimal = document.getElementById("favAnimal");
console.log(favAnimal.value);

Get Value of Select-Option In Loop with Jquery

I am trying to make an Asp.Net Mvc Ajax project.I have to take the value of select-option in a loop with jquery.All select's ids are same , names are same when I try it takes the first select's value.btw I have tried all things in this title: jQuery Get Selected Option From Dropdown. Can you help me please?
#foreach (var item in Model)
{
<select id="selSaat">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
}
Heres some JS code that will give you the selections value if there is only 1 select element on your page and the options within it contain values on them:
document.getElementsByTagName('select')[0].onchange = function(){
alert(this.value);
};
Heres a working demo for ya:
http://codepen.io/nicholasabrams/pen/OVOPYK
Targeting a <select> with native browser javascript with the onchange method will return the value selected when it occurs via user interaction.
http://www.w3schools.com/jsref/event_onchange.asp

How to update select text with matched option value text

I would like to update the select text with the selected option text after page load.
Im redirecting on click of a option and after page load getting url from browser and checking which option has that value and wants to replace that matched option's text inside select text.
<div class="sorting-option">
<select id="selectdropdown" class="dropdown-select">
<option value="">Recommended Items</option>
<option value="?sort1desc=F&sort1=Item_NAME">Name (A-Z)</option>
<option value="?sort1desc=T&sort1=Item_NAME">Name (Z-A)</option>
<option value=".f?sort1desc=F&sort1=Item_ONLINECUSTOMERPRICE">Price
(Low-High)
</option>
<option value=".f?sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE">Price
(High Low)
</option>
</select>
</div>
This is what i have tried
$(document).ready( function() {
$('#selectdropdown').bind('change', function () {
location.href = $(this).val();
});
var brwsr_url=document.URL;
var subSting = brwsr_url.substring(brwsr_url.indexOf('?')); //here im getting substring of url to match with option value
$('#selectdropdown').find('option[value="subSting"]').text(); // here im trying to replace the select text with option text which has that url substring
});
You're not concatenating properly. Also you're using getter of text. Instead, use the setter. Also from your comment, I suppose you need
$('#selectdropdown').val(subSting);
Try this mate>I think u are trying to select the option from the selectbox
$('#selectdropdown').find("option[value='"+subSting+"']").attr("selected","selected");

how do i add or increase a numeric value in an input text field?

i'm using this jquery calculation plugin: http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
i'm using the sum example.
in my version, i'm dynamically inserting values into fields and recalculating and all works well, but so far i have just been inserting new values into empty fields.
now in a separate action i want to increase the value of one of the fields that has been previously filled by a value and then recalculate again.
i setup a fiddle with what i'm trying to do.
http://jsfiddle.net/rEQnY/1/
there's a dropdown with options. each option has a numeric value.
now as an example lets just pick a field at random. lets say that 3rd field that has a number "1" in it.
when i select one of the dropdown values, i want that 3rd field with a number 1 in it to increase by that much, and then the total sum box should also increase by that much.
in the javascript i started with listening to a change in the dropdown box, but what do i insert in between there?
maybe i can grab the selected value like this:
$('#numbers').val();
but then how do i add it to the other field?
update:
how do i fix this new version?
http://jsfiddle.net/rEQnY/8/
i want 2 different fields to add value to another field.
if dropdown 1 (by itself) adds 2 to 3rd input text box, 3rd input text box should become 3.
if dropdown 2 (by itself) adds 2 to 3rd input text box, 3rd input text box should become 3.
if 2 is selected in both dropdowns, then 4 should be added to 3rd input text box and become 5.
if either dropdown 1 or dropdown 2 is reset, meaning "pick one" is selected, then the 3rd input text box should be subtracted by 2, making it 3.
as you can see in my example, only one dropdown adds to the field. can be either or, but not both. i want both to be able to add to it and take away from it when the default "pick one" is selected.
$('#otherField').val(Number($('#numbers').val())+1);
Update
HTML
<p>
<select id="numbers" name="numbers" class="numbers">
<option value="">pick one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</p>
<p>
<select id="morenumbers" name="morenumbers" class="numbers">
<option value="">pick one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</p>
jQuery
$(".numbers").change(function() {
//grab selected value and add it to the 3rd text field
//so if 2 is selected, the field with 1 becomes 3 and the total sum becomes 12
var first;
var second;
var initial = 1;
if($('#morenumbers').val() == '')
first = 0;
else
first = Number($('#morenumbers').val());
if($('#numbers').val() == '')
second = 0;
else
second = Number($('#numbers').val());
$('#third').val(first+second+initial);
$("input[name^=sum]").sum("keyup", "#totalSum");
});
Fiddle
http://jsfiddle.net/rEQnY/9/
Simply do this:
// On selected option change...
$("#numbers").change(function() {
var
// Get the selected value as an integer
value = +$(this).val(),
// Get the third input field
$thirdInput = $('input[name^="sum"]:nth-child(3)')
;
// Increase the third input field's value by the selected option value
$thirdInput.val(+$thirdInput.val() + value);
// Recalculate the sum
$("input[name^=sum]").sum("keyup", "#totalSum");
});
Working JSFiddle demo.
Here we're using a unary + to convert the value of the inputs and the drop down to an integer.
Edit: Further requirement made in comments:
if the dropdown is changed from a numbered value to the "pick one" option, i need the addition to be retracted and go back to it's previous state.
For this we can declare a new global variable which is set to the initial value of the third text field:
var thirdSumValue = 1;
Then use this in our drop down's change event:
$thirdInput.val(thirdSumValue + value);
Updated JSFiddle demo.
Alternatively instead of hard coding its default value you can simply set it to the value of the text field on load:
var thirdSumValue = +$('input[name^="sum"]:nth-child(3)').val();
This will reflect any default HTML values prior to the JavaScript being loaded.
Final JSFiddle demo.

select value of dropdownlist item jquery

HTML
<select id="selectDepartment">
<option value="1">120</option>
<option value="2">20</option>
<option value="3">140</option>
<option value="4">4120</option>
<option value="5">560</option>
<option value="6">451</option>
<option value="7">310</option>
<option value="8">656</option>
<option value="9">444</option>
<option value="10">555</option>
<option value="11">2560</option>
<option value="12">450</option>
</select>
jQuery
$("#selectDepartment").change( function() {
alert($("select option:selected").val());
});
the above function always shows value 1 on alert, when I select any one of the options
Your method of finding the selection option is vague. You're saying "Grab all <select>s". You then go on to grab the :selected option from each of them (of all <select>s on the page). Continued, .val() takes the first value off the top.
Simply put, you're always fetching the selected value of the first <select> found on the page. Assuming #selectDepartment isn't the first <select>, your value will never change.
Try to keep the scope to within the current <Select> using this:
$('#selectDepartment').change(function(){
var selopt = $('option:selected',this);
});
Note that I specify the scope to within the <select> that triggered the .change(). Also note this really isn't necessary as val() works just as easily:
var selopt = $(this).val();
Let jQuery do the heavy lifting. You really only need option:selected if you want control over styling that specific element, or you're working with a multi-select and want more control.
You can do something like this:
$("#selectDepartment").change( function() {
var selected = $(this).find(":selected");
});

Categories