Pass HTML dropdown menu values to JavaScript function & onclick function call - javascript

I know that this question has been asked in several ways, but they have not helped me, and I'm getting an "undefined" error when I try to debug this.
It's simple: I have an HTML dropdown menu with several different metric units on it, and I have given each a value. I want to pass the selected value to a JavaScript function that will check the metric unit type and then convert it to a corresponding English unit.
The dropdown HTML:
e<p><span><label for="metric-unit">Select metric unit</label></span>
<select name="metric" id="metric">
<option value="cel">Celsius</option>
<option value="cm">Centimeters</option>
<option value="kg">Kilograms</option>
<option value="ml">Milliliters</option>
</select>
</p>
My JavaScript function attempt to pass the value:
metricUnit = document.getElementById("metric").value;
My second question is on calling the conversion function. I want to do that once the metric unit is selected, and a number entered into a text field, and then the user clicks a submission button. Should I call the function with or without arguments, especially if I use getElementById to get the value of the metric unit and the number before any math occurs?
Would it be
onlick ="convertMeasure()"
or
onclick = "convertMeasure(metric, numVal)"

Assuming the id of submission buttons and text field are sub and txt respectively, and you've a default <option> like "choose unit" with value = 0:
var button= document.getElementById("sub");
button.onclick= function(){
var select= document.getElementById("metric");
metricUnit = select[select.selectedIndex].value; //value selected in select
val = document.getElementById("txt").value; // value entered in text field
if(metricUnit!=0 && !isNaN(val)){ // make sure selected item is not default and the text in textbox is a number
convertMeasure(metricUnit, val); // call your function
}
}

It seems like you're putting your click binding somewhere in the html like this
<div onclick='callThisFunction()'> Click on this div </div>
Then in your javascript, you can have that function. In it, you can get the selected value of the drop down list and do whatever logic you need.
<script>
function callThisFunction() {
var dropdown = document.getElementById("metric");
var unit = dropdown.options[dropdown.selectedIndex].value;
var nameOfUnit = dropdown.options[dropdown.selectedIndex].text;
if (unit == "cm") {
// do stuff
} else if (unit == "ml") {
// do stuff
}
// etc.
}
</script>

First get your select element
var select = document.getElementById("metric");
and then you can go read the value from options with the selected index
var metric = select.options[select.selectedIndex].value;
As for how to call the convertMeasure() method I would suggest the first one if you are going to get values from multiple elements on the fly.
Here is a jsfiddle to play with http://jsfiddle.net/zEncN/

Related

How to return the length and value of a selection in a datalist?

I would like to fabricate some code, that tracks the amount of unfiltered options in a datalist. So how could I keep track of this?
Secondly when there is only one option left in the list I want to access the value of this option.
Here is a link to the w3c spec: https://www.w3.org/TR/html5/forms.html#the-datalist-element
Note: I want to use the datalist, so I don't want to create my own filter on the datalist and get the values from there.
I came up with this code so far:
Fiddle: https://jsfiddle.net/6usf7j9g/
html
<h3>Anything you'd like?</h3>
<input id="your-favourite" list="choices"/>
<datalist id="choices">
<option value="Laphroaig"></option>
<option value="Jameson"></option>
<option value="Talisker"></option>
<option value="Oban"></option>
<option value="Dalwhinnie"></option>
<option value="Glennfidich"></option>
<option value="Glenlivet"></option>
</datalist>
jQuery/js
var selectedChoices = null; //in this variable I need to know how many items are left in the list after filtering. If you type "Glen" it should be two, if you type "Glenn", "J", etc. it should give a value of 1. It only needs to work on google chrome.
$("#your-favourite").on("keyup", function(){
selectedChoices = null; //PART OF THE ISSUE: Should change the value of the variable here, depending on the options that are showing.
if(selectedChoices === 1){
let finalOption = "unknown"; //PART OF THE ISSUE: Should load the value of the remaining option
// validate success
alert("There is only one value left in the list! It is called: " + finalOption);
selectedChoices = null; // reset value to 0.
}
// log the datalist and input elements, it might have some info that helps finding a solution.
console.log($("#your-favourite"));
console.log($("#choices"));
}); // end on keyup

datalist get selected value and custom attribute (without events)

I have a datalist with options and a custom attribute.
<input list="selectedItems" class="selectedItemsList"></input>
<datalist id="selectedItems">
<option value="test11" oldvalue="f1"></option>
<option value="test12" oldvalue="f2"></option>
</datalist>
It is displayed on a popup. When a popup closes the value and custom attribute value must be used in a function...
I tried:
alert($("#selectedItems option:selected").val());
alert($("#selectedItems option:selected").attr("oldvalue"));
$('.selectedItemsList option').each(function() {
if($(this).is(':selected')){
alert($(this).val());
}
});
for (var i=0; i<document.getElementById('selectedItemsList').options.length; i++)
{
if (document.getElementById('selectedItemsList').options[i].value == document.getElementsByName("selectedItems")[0].value)
{
alert(document.getElementById('selectedItemsList').options[i].value);
break;
}
}
Nothing works.
I can get the values using on-event but that is not an option for me.
$('.selectedItemsList').on('input', function() { ...
alert($(this).val());
$(function(){$("input[name=selectedItems]").on('input', function(){// selects which array raw is edited
for (var i=0; i<dList.length; i++) if(dList[i].ItemName===$(this).val()) { num = i;
$(".selectedItems option[value="+dList[num].ItemName+"]").val($(this).val());
dList[num].ItemName=$(this).val();
});
});
So, I use datalist oninput event to get the selected value. Then, I edit a raw of an array of values that represents the datalist values.
var dList=[];num=0;
dList.push({ItemName: $(this).attr('value'), ViV: vs[0], NU: vs[1], ItemKey: $(this).attr('key')});
Essentially, I believe the problem is related to your selector use. I'm making the assumption that you're trying to get the old value from the datalist. On closing your popup, you should get the value of the input first
var inputval= $(".selectedItemsList").val();
alert(inputval);
then grab the associated oldvalue based on the value of the input.
var oldval= $('datalist#selectedDevices option[value='+inputval+']').attr('oldvalue');
if (oldval)
alert(oldval);
I created a jsfiddle for you here to play around with.
http://jsfiddle.net/jornjjt6/

form element index in javascript for use in jquery .change function

I need to get an index of a form element that is passed in to a .change statement.
example HTML form code
<tr><td>Question1</td><td><select class=list1 id=l[1] name=l[1]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[1] id=x[1]></select></td></tr>
<tr><td>Question2</td><td><select class=list1 id=l[1] name=l[2]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[2] id=x[2]></select></td></tr>
<tr><td>Question3</td><td><select class=list1 id=l[3] name=l[3]><option value=1>1<option value=2> 2 <option value=3> 3 </select></td><td><select class=hideme name=x[3] id=x[3]></select></td></tr>
Now the user will select 1, 2 or 3 from the first pulldown. based on that selection the second pulldown will be loaded with content.
example javascipt jquery function
$('.list1').change (function ()
{
// here is where I need to pick up the index ie: the [1] [2] or [3] as var id
var selected = $("#l[id] option:selected");
var pdata = 'subjectareaid='+selected.val();
$.ajax({
type : "POST",
cache : false,
url : "subcat.php",
data : pdata,
success: function(data) {
$('#x[id]').html(data);
$('#x[id]').removeClass('hideme');
}
});
});
This will allow me to populate the second pulldown with the options that were returned by the ajax call based on the selection from the first pulldown.
The table has 54 pulldowns that all have to have this action taken against them (this is to populate a mysql table upon form submission) the pulldowns are (l[id]) primary category (x[id]) sub-category. The subcat selection is hidden until after the main cat is picked and then the select statement is populated.
First of all add double qoutes arround your attributes ", this is best practice and will prevent errors if you use spaces in your values. Also make sure your html is valid. You didn't close the <option> tags with a </option>.
You can use a simple regex to get the index of your select element.
$('.list1').change (function () {
var id = $(this).attr('id');
var matches = id.match(/^l\[([0-9]{1,})\]/);
if (matches) {
var index = matches[1];
}
});
You can get the select element changed at the moment with $(this) instead of var selected = $("#l[id] option:selected");
You can reach the index of the changing select by reaching index of parent tr element of that select element by using closest() selector of jQuery.
Finally the code block you need, should be like that:
var selected = $(this);
var selectedIndex = selected.closest("tr").index();
var pdata = 'subjectareaid='+selected.val()+"&index="+selectedIndex;

how to Target an option from pull down with js to apply more code

a friend asked me to help him with a form, a client of his wants to make a form a bit more dynamic...my javascript is minimal at best since i just started learning.
He asked me something along the lines of " how can i make a form show another pull down ONLY WHEN a certain option is selected "
in the example he gave me, by default when page loads,he has a pull down menu which has 2 options, MANHATTAN and option two is BROOKLYN.
If Manhattan is chose, that reveals another pull down with zips for manhattan, if Brooklyn is chosen the same for BK.
in sample html, something along the lines like this:
<div>
<form>
<select name="boro" id="boro">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
i want to target/capture the option chosen by the user above on the pull down menu, to then activate this function(below).
according to his request what i guess id do is,(as a newbie), then as far as the .js goes (pseudo code):
<script type="text/javascript">
function valBoro (){
if( brook is chosen){ document.getElementById('empty2fill').innerHTML=" new dropdown code here")
}
}
</script>
aside from not knowing, my main problem is i dont know how to target the option chosen in the menu to thereafter, apply the function (which will be written later)
any ideas, tips etc are greately appreciated.
thanks in advance
Another option is to create the two dropdown lists and set the style display to "none". Then you can catch the onChange event and set display to "" based on the value of the select element.
function showZip() {
var boro = document.getElementById("boro");
if (boro.value == "manhattan") {
var zipManhattan = document.getElementById("zipManhattan");
zipManhattan.style.display = "";
}
}
And in the html
<div>
<select name="boro" id="boro" onchange="javascript:showZip();">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<br/>
<select name="zipManhattan" id="zipManhattan" style="display:none;">
<option value="zip1" id="zip1">1111</option>
<option value="zip2" id="zip2">2222</option>
</select>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Here is a link to a jsfiddle showing example code.
http://jsfiddle.net/WKqth/
Example markup:
<div>
<form>
<select name="boro" id="boro">
<option value="" id="none">Select a boro.</option>
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Example js
// include this js below the form in the body, or wrap it in a function and assign that to window.onload, or use a library that provides onDomReady (in jQuery, $(document).ready(function () ... });
var selectElement = document.getElementById('boro');
var showBoroSelect = function () {
// find the selected element
var selectedOption = selectElement.options[selectElement.selectedIndex].id,
// find the element that will contain the new drop down
containerElement = document.getElementById('empty2fill'),
// define the html for the manhattan drop down
manhSelectInnerHTML = '<select name="secondary"><option value="derp">manh derp?</option><option value="herp!">manh herp!</option></select>',
// define the html for the brooklyn drown down
brookSelectInnerHTML = '<select name="secondary"><option value="derp">brook derp?</option><option value="herp!">brook herp!</option></select>',
newInnerHTML;
// determine which html to use based on the selection
if (selectedOption === 'manh') {
newInnerHTML = manhSelectInnerHTML;
} else if (selectedOption === 'brook') {
newInnerHTML = brookSelectInnerHTML;
} else {
// no boro was selected, hide the menu
newInnerHTML = '';
}
// set the container to the new innerHTML
containerElement.innerHTML = newInnerHTML;
};
// when the boro select changes, show the new menu
selectElement.onchange = function () {
showBoroSelect();
};
// if you select a boro and reload the page, the boro may already be selected (for example, firefox might do this)
// this will set the boro menu initially before the user changes it
showBoroSelect();
You want to handle the change event of your "boro" select element.
I've put a plain-JS example solution on jsfiddle at http://jsfiddle.net/FHArd/1/
This creates three select lists - one is your "boro" and the other two are the zip code lists, but they are hidden via CSS until a selection is made.
The change event handler simply adds and/or removes classes from the zip code select elements; the CSS hides or shows the lists based on the class "active" that is attached to the zip code select list.
Note - being there in jsfiddle the way you start things up is a little different than normal. You'd really run your setup function at the onload or ondomready event.
This should do it.
<select name="boro" id="boro" onchange="valBoro(this)">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<script type="text/javascript">
function valBoro(dropDown) {
if (dropDown.options.[dropDown.selectedIndex].value.equals("manhattan")) document.getElementById('empty2fill').innerHTML = "newHTMLCode";
//change "manhattan" to whatever option you want to use
}
</script>

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