Get Default Value From select field Javascript - javascript

I have a select field that have have present options and I have a php script check a mysql database and add a select tag to the one currently being used.
I need to find a way to know if the user have changed the select field or not before submitting it.
var Access = document.forms[UIDF]["Access"].value;
var DAccess = document.forms[UIDF]["Access"].defaultIndex; <--- This is my problem. I just need to know how to get the selected option value as this keep changing with every user
<select name="Access">
<option value="0" selected='selected'>Employee</option>
<option value="1">Team Leader</option>
<option value="2">Admin</option>
</select>

The Option tag has a javascript attribute defaultSelected that's set to true if the option had a selected value on page load. Note that this is the option tag and not the select one, so you'll have to loop through the options and check for the attribute.
Something like
var DAccess;
var AccessSelect = document.forms[UIDF]["Access"];
for (var i = 0 ; i<AccessSelect.length ; i++)
{
if (AccessSelect[i].defaultSelected)
DAccess = AccessSelect[i].value;
}
Or, more to the point:
var AccessHasChanged = false;
var AccessSelect = document.forms[UIDF]["Access"];
for (var i = 0 ; i<AccessSelect.length ; i++)
{
if (AccessSelect[i].defaultSelected &&
AccessSelect.value != AccessSelect[i].value)
AccessHasChanged = true;
}

Related

Get value of Dynamically created select

I create a select box dynamically via an eventlistener.
<select name="s" id="s"></select>
becomes
<select name="s" id="s"><option value=1>1</option><option value=2>2</option>
<option value=3 selected="true">3</option></select>
I then call a js function to get the selected value. However it fails, the selectedOptions htmlcollection length is 0. But when I expand the collection I can see the selected value 0:<option value=3 selected=true> If i try to grab the value it fails e.selectedOptions[0].value If I make the dropdown static. I am able to retrieve the value.
e = document.querySelector('#s');
console.log(e.selectedOptions)
I created the same scenario regarding your prob, you can check this out by simply using the document.getElementById
const form = document.getElementById("form");
const selectField = document.createElement("select");
selectField.setAttribute("id", "s");
// iterate the option/s
for(let i= 1; i <= 3; i++){
const option = document.createElement("option");
option.setAttribute("value", i);
option.innerText = i;
selectField.append(option);
}
// append the dynamic select field into div form as an example parent
form.append(selectField);
// this get the values from your dynamic select field
document.getElementById("s").onchange = function(e){
console.log("value", e.target.value)
}
example:
Input: select option 2
Output: "2"
my source:
https://jsfiddle.net/d4q7mugh/12

Is there a way to show the selected option value in the select menu after turbolinks.visit(url)

I have select menu with bunch of options having "url's" as their value. Once user click on the option , it will take them to particular url. I want the selected option to be shown on select menu when taken to the particular url.
Code:
Html:
<div data-controller="dropdown">
<select id="abcMenu" data-action="dropdown#abc">
<option value="/abc">A</option>
<option value="/xyz">B</option>
<option value="/def">C</option>
</select>
</div>
Javscript
abc(){
var elt = document.getElementById('abcMenu');
elt.options[elt.selectedIndex].setAttribute('selected','selected');
var option = elt.options[elt.selectedIndex].value;
Turbolinks.visit(option);
}
Turbolinks will take to next path whereas dropdown option gets preselected to first option. Can anyone please let me know how to fix this.
You can use window.location.pathname to get the path and then set the corresponding option from the select:
function selectOptionByValue(element, value){
for(var i=0; i < element.options.length; i++) {
if(element.options[i].value == value) {
element.selectedIndex = i;
}
}
}
Where element is the select element and value is the path that you want to check.

Why does dropdown list selection from a location hash work on Chrome, but not Firefox, IE, or Safari?

Complete JS novice. I want a "Request A Quote" button to auto-populate a dropdown menu on a new page based on the product and url. Each product quote button links to the same form but with a different hash value in the url which matches an option in the dropdown menu.
Example:
User clicks "Request A Quote" for 'Product A'
User is sent to www.example.com/request-a-quote/#Product A
Product dropdown menu (id=product-select) on form already reads "Product A"
This code works on Chrome, but not for anything else. What am I doing wrong?
//Get select object
var objSelect = document.getElementById("product-select");
var val = window.location.hash.substr(1);
//Set selected
setSelectedValue(objSelect, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
I found that applying decodeURIComponent() cleaned up my val variable.
Also, building links as www.example.com/request-a-quote/#Product A is important. If the forward slash is not before the hash, mobile Safari will ignore everything after the hash and it won't work.
Below is my final solution:
//Get select object
var objSelect = document.getElementById("product-select");
var val = decodeURIComponent(window.location.hash.substr(1));
//Set selected
setSelectedValue(objSelect, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Without seeing more code.... The option tag officially supports the value attribute vs text which is the user readable name. We use value as an identifier:
selectObj.options[i].value == valueToSelect;
You will also need to change the select.options markup to use the value attribute rather then text.
UPDATE more info as requested:
The purpose of text is to provide a user readable option. We use value to identify the selection to the server and in your case the URL hash. By using the value attribute, you can use URL safe values and user readable text.
The fix you posted in your answer is really bad practice and will become problematic as the complexity of your code increases.
This example will work in all browsers and is the proper way to implement.
//Simulate hash
window.location.hash = '2'
var val = window.location.hash.substr(1);
var selectEle = document.getElementById('select')
setSelectedValue(selectEle, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
var selection = selectObj.options[i]
if (selection.value == valueToSet) {
selection.selected = true;
}
}
}
<select name="selections" id="select">
<option value="1">Product A</option>
<option value="2">Product B</option>
<option value="3">Product C</option>
</select>

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories