More Properties of Dropdown options - javascript

I've got a dropdown setup going on in which the user enters an input value, chooses a calculation to perform on that number from a dropdown, then a function displays the result.
What I would like is to add more 'values' to the dropdown, so when an option is selected from the list, it can also, say, display some text stored in the list, or some other information. Right now I can return the selected option's value (.value) and use the option's name (.text) to perform functions, but is there any more data I can add to each selection to be used later?
<html>
<head>
<script language="JavaScript">
function myfunction(form)
{
var i = parseFloat(form.Input.value, 10);
var e = document.getElementById("calculationList");
var strUser = e.options[e.selectedIndex].value;
form.Output.value = strUser*i;
}
</script>
</head>
<body>
<form>
Input Number:
<INPUT NAME="Input" SIZE=15>
Make a selection:
<select id="calculationList" onchange="myfunction(form)">
<option></option>
<option value="2">Double It</option>
<option value="3">Triple It</option>
<option value="10">Multiply It By ten</option>
</select>
Output Number:
<INPUT NAME="Output" SIZE=15>
</FORM>
</body>
</html>

Basically you may attach data attribute to your options like that:
<select id="calculationList">
<option></option>
<option value="2" data-aaa="10">Double It</option>
<option value="3" data-aaa="20">Triple It</option>
<option value="10" data-aaa="30">Multiply It By ten</option>
</select>
And later get the content of the attribute:
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
jsfiddle -> http://jsfiddle.net/pzKrr/
Edit:
If you want to implement my solution remove onchange="myfunction(form)" from the select tag. After that add the following code just after that myfunction
window.onload = function() {
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
};

Related

How to set default value in input datalist and still have the drop down?

I am using the datalist HTML property to get a drop down inout box:
<input list="orderTypes" value="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The problem is that now I have to clear the input box to view all the drop down values. Is there a way to have a default value but still view all the values in the datalist when the drop down icon is clicked?
I have the same problem.
I just simple added placeholder with the default data.
In your example:
<input list="orderTypes" name="orderType" id="orderType" placeholder="Book" />
I listen submit event. If the input value is empty, I use Book as default value, otherwise I use the given value...
$("#mySubmitButton").click(() => {
// use event prevent here if need...
const orderType = $("#orderType").val() || "Book";
console.log(orderType);
});
I know of no way to do this natively. You could make a "helper" div to use when the input field has value. I couldn't hide the native drop down so I renamed the ID. Uses jQuery.
html
<input list="orderTypes" id="dlInput">
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
<datalist id="orderTypes" style="z-index:100;">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
script
$(function(){
// make a copy of datalist
var dl="";
$("#orderTypes option").each(function(){
dl+="<div class='dlOption'>"+$(this).val()+"</div>";
});
$("#helper").html(dl);
$("#helper").width( $("#dlInput").width() );
$(document).on("click","#dlInput",function(){
// display list if it has value
var lv=$("#dlInput").val();
if( lv.length ){
$("#orderTypes").attr("id","orderTypesHide");
$("#helper").show();
}
});
$(document).on("click",".dlOption",function(){
$("#dlInput").val( $(this).html() );
$("#helper").hide();
});
$(document).on("change","#dlInput",function(){
if( $(this).val()==="" ){
$("#orderTypesHide").attr("id","orderTypes");
$("#helper").hide();
}
});
});
jsFiddle
Is this what you trying to do?
var demoInput = document.getElementById('demoInput'); // give an id to your input and set it as variable
demoInput.value ='books'; // set default value instead of html attribute
demoInput.onfocus = function() { demoInput.value =''; }; // on focus - clear input
demoInput.onblur = function() { demoInput.value ='books'; }; // on leave restore it.
<legend>(double) click on the input to see options:</legend>
<input list="orderTypes" id="demoInput">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The only "problem" here is that in order to see the options the user have to click the input again so it's like "double-click the input to see options".
Hope that helps.
I would use input's placeholder attribute along with a Javascript code that'll make sure that the field isn't empty upon submission.
Obviously this is just an example, you'll have to modify the submission event.
document.getElementById('submitButton').addEventListener('click', function() {
let inputElement = document.getElementById('myInput');
if (!inputElement.value) {
inputElement.value = 'Book';
}
});
<input id="myInput" list="orderTypes" placeholder="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
<input id="submitButton" type="submit">
I've menaged to get what You described with just <select> + <option> tags instead of <input> + <datalist>:
<select name="sortBY">
<option value="Book">Book</option>
<option value="Copy">Copy</option>
<option value="Page">Page</option>
</select>
Putting it all inside <form></form> tags will send it eg. with POST method with $_POST['sortBY'] value.
If this helps at all:
$('#grouptext').val($('#grouplist option#48').attr('value'));
where '#grouptext' is your text input to which your datalist '#grouplist' is attached, and #48 is the ID you're looking to "pre-select".
here's what my data list looks like, for clarity
worked for me.
In Chrome's console it shows up like this with "option#115", which corresponds to the correct text in the datalist for that "id" (being 115)
set id for your input and with js set default value
<script>
setTimeout(() => {
document.getElementById('orderTypes').value = "Book";
}, 100);
</script>

jquery get selected values of multiple select boxes

i have this form ..
<form method="post" action=''>
<select class="first">
<option value="0">choose ...</option>
<option value="1">Hello</option>
<option value="3">It's</option>
</select>
<select class="second">
<option value="0">choose ...</option>
<option value="2">World</option>
<option value="4">me</option>
</select>
<input type="text" class="dest" value="" />
</form>
and would like to dynamically gather selected informations with jQuery, because I need to decide on the selected values ...
When you select specific combination of OPTION values (lets say Hello + World) it should add some value to INPUT.dest and lock it (disable from editing) ...
But I can't make it work ... What I have, is that on each change of each select (separately only) i can map the actual value
$(document).ready(function () {
$(".first").change(function () {
var option = $(this).find("option:selected").val();
$(".dest").val(option);
});
$(".second").change(function () {
var option2 = $(this).find("option:selected").val();
$(".dest").val(option2);
});
});
Here is the live demo in fiddle
Do you know what am I missing? I know it will be just a little thing .. thank you
I would generalize it and use one event listener, and then gather the combination and do whatever:
$("select").change(function () {
var first = $(".first").find("option:selected").val();
var second = $(".second").find("option:selected").val();
if(first == 1 && second == 2)
$(".dest").val("Hello world").prop("disabled",true);
else
$(".dest").val("Something else").prop("disabled",false);
});
http://jsfiddle.net/cxx428af/3/

Button to add selected="selected" from outside form

I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.
Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>
For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>
Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.

How can a visitor add options to a menu through text fields?

I have the following drop down menu.
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
</select>
Is it possible for me to add two text input fields where the visitor can populate the menu options themselves?
For example, in text field one they input the url for the option, and text field two, they input the name of the option.
So...
Text field one: http://www.randomwebsite.com
Text field two: Random Website
Then an 'Add' button, which would result in this...
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
<option value="http://www.randomwebsite.com">Random Website</option>
</select>
This is the javascript for the current menu, if this helps.
<script type="text/javascript">
function newSrc() {
var e = document.getElementById("MySelectMenu");
var newSrc = e.options[e.selectedIndex].value;
document.getElementById("MyFrame").src=newSrc;
}
</script>
Thanks in advance.
Yes Create two textboxes and Add id's to them and also create a button with a onclick function "Add", Then use the following javascript which is nothing but creating the option and appending to selectbox
function Add()
{
var x = document.getElementById("MySelectMenu");
var opt = document.createElement("option");
opt.value= document.getElementById("url").value;
opt.innerHTML = document.getElementById("name").value; // whatever property it has
x.add(opt);
}
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
</select>
<input type="text" name="name" id="name">
<input type="url" name="url" id="url">
<button onclick="Add()">ADD</button>
Try below code
var url=$("#txtUrl").val();
var textValue = $("#txtDisplay").val();
$('#MySelectMenu').append("<option value='"+url+"'>"+textValue+"</option>);
use this code on OnClick event of Add button.

Creating a text and dropdown list search functionality

I've written a piece of code that allows a Sharepoint list user to select a search criteria from a drop down list. By default, next to this, I'd like a textbox to be present. Besides the text box on the page is a Search button and a Reset button. This looks like this:
Ideally, what I'd like is that if the user selects a specific option in the search criteria drop down list (say, Field 3), the text box will change to a drop down list, which they choose their option from and then search for as usual.
This is what I have so far:
<script type="text/javascript">
function RedirectUrl() {
var sField = document.getElementById("searchField").value;
if (sField == "Field3") {
var search = document.getElementById("dropdownSearch").value;
} else {
var search = document.getElementById("textSearch").value;
}
var url = "";
if (search != "") {
url = "FilterName=" + sField + "&FilterMultiValue=*" + search + "*";
window.location.href = //Url of our site
}
else {
return false;
}
}
function ClearUrl() {
//Refresh page
}
</script>
Search Field: <select id="searchField">
<option selected value="Field1" >Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>
if (searchField == "Field3") {
Search text: <select id="dropdownSearch" />
<option selected value="One" >One</option>
<option value="Two">Two</option>
</select>
} else {
Search text: <input type="text" id="textSearch" />
}
</script>
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Reset Filters" onclick="return ClearUrl();" />
The functionality of this code works. If the user selects "Field3" from the search field drop down list, whatever is selected in the drop down list is shown. If the user selects any other option from the search field drop down list, the text in the "search text" field is shown.
However, due to the if statement contained within, it looks like this:
Questions:
How can I get the code to automatically display either the text box or the drop down list depending on the user's selection in the Search Field?
How can I hide the if statement logic?
As can probably be guessed from the code I have almost zero experience in Javascript (and absolutely zero experience in JQuery, if any answers tend that way) - although I have tagged JQuery as from what little I do know I feel it might be better(?) suited for it.
Edit: My not-working code after ZiNNED's help:
Search Field:
<select id="searchField">
<option selected value="Field1">Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>Search Text:
<select id="dropdownSearch" style="display: none;">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<input id="textSearch" />
<input type="button" id="btnSearch" value="Search" />
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js">
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
You should do a couple of things.
First: remove the if-statement from the code and hide the dropdownSearch select by default:
HTML
Search Field: <select id="searchField">
<option selected value="Field1" >Field 1</option>
<option value="Field2">Field 2</option>
<option value="Field3">Field 3</option>
<option value="Field4">Field 4</option>
</select>
Search text:
<select id="dropdownSearch" style="display: none;" />
// All options and their values
</select>"
<input type="text" id="textSearch" />
Second, add a reference to jQuery and the following JavaScript to your document:
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
This adds an event to the searchField dropdown that triggers when its value is changed. If the value equals Field3 the dropdownSearch is shown; otherwise the textSearch.
See this FIDDLE.
EDIT: After your edit, try changing the following:
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js">
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
to:
<script type="text/javascript" src="link-to-Sharepoint/SiteAssets/jquery-1.11.1.js"></script>
<script>
$(document).ready(function () {
$(document).on("change", "#searchField", function () {
var show = $(this).val() == "Field3";
$("#dropdownSearch").toggle(show);
$("#textSearch").toggle(!show);
});
});
</script>
You shouldn't add JavaScript to script tags when you're also referring to an external file in it.

Categories