How to keep drop down menu variable by function - javascript

i have a function with 3 cases depending on the date. Now i want to display it in a drop down menu.
function get_data_date(i) {
var string;
if (i == 0) {
if(d.getUTCHours() < 3 ) {
.
.
.
.
.
string=d_date.getUTCFullYear()+""+addZero1(d_date.getUTCMonth()+1)+""+d_date.getUTCDate()+"_"+addZero1(d_date.getUTCHours());
return string;
}
I do not know how to call the function in an Option tag. Please note that the function is not complete displayed.
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>

Don't use eval, as it offers too many opportunities for Bad Things.
Instead, inspect the selected option and invoke the appropriate function. With the markup as you've presented it, it would look something like this
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
var id = e.options[e.selectedIndex].id;
// Invoke `get_data_date` with appropriate argument, based on
// the selected option. NOTE: This is not a good solution--see below for
// a better one
if (id === 'run1') {
get_data_date(0);
} else if (id === 'run2') {
get_data_date(1);
} else if (id === 'run3') {
get_data_date(2);
}
}
var selectControl = document.querySelector('select[name="run"]');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>
However, if you have control of your markup, you should consider refactoring to put the value you care about in the value attribute of your options. Then, you can directly access that value and pass it as an argument to your function.
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
// TODO: Error handling
var val = e.options[e.selectedIndex].value;
get_data_date(val);
}
var selectControl = document.getElementById('date-run-select');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select id="date-run-select" name="run" size="1">
<option id="run1" value="0"> get_data_date(0)</option>
<option id="run2" value="1"> get_data_date(1) </option>
<option id="run3" value="2"> get_data_date(2)</option>
</select>
</form>

Related

Accessing the value of an HTMLSelectElement

I am creating a form where my users select some options from checkboxes and dropdown lists.
The intended outcome is a text that is generated dynamically as the users change their choices.
It works but I keep getting “[object HTMLSelectElement]” instead of the value of the selected choice from the dropdown box. How do I get the actual value?
<!DOCTYPE html>
<html lang="en" >
<body>
<div class="container">
<select name = "birthyear" id = "from" size="3" >
<option value="1980" >1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
</select>
<select name = "month" id = "month" size="3" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="day" id="day" size="3" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a id="search-btn" href="#">Search</a>
</div>
</body>
</html>
let searchButton = document.getElementById("search-btn");
let searchInput = document.getElementById("from");
let searchInput1= document.getElementById("month");
let searchInput2 = document.getElementById("day");
let summary = document.getElementById("summary");
searchButton.addEventListener("click", findWeatherDetails);
searchInput.addEventListener("keyup", enterPressed);
searchInput1.addEventListener("keyup", enterPressed1);
searchInput2.addEventListener("keyup", enterPressed2);
function enterPressed(event) {
if (event.key === "Enter") {
findDetails();
}
}
function enterPressed1(event) {
if (event.key === "Enter") {
findDetails();
}
}
function enterPressed2(event) {
if (event.key === "Enter") {
findDetails();
}
}
function findDetails() {
let searchLink = "https://www.geniecontents.com/fortune/internal/v1/yearly?birthYear="+searchInput+"&targetYear=2019&targetMonth"
+searchInput1+"&targetDay="+searchInput2;
httpRequestAsync(searchLink, theResponse);
}
function theResponse(response) {
let jsonObject = JSON.parse(response);
summary.innerHTML = jsonObject.summary;
}
function httpRequestAsync(url, callback)
{
console.log("hello");
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
This is the result of the HTTP GET
GET https://www.geniecontents.com/fortune/internal/v1/yearly?birthYear=[object%20HTMLSelectElement]&targetYear=2019&targetMonth[object%20HTMLSelectElement]&targetDay=[object%20HTMLSelectElement] => 500
You need to use .value eg. searchInput1.value
So your search link in findDetails() should be created this way:
let searchLink = "https://www.geniecontents.com/fortune/internal/v1/yearly?birthYear=" +
searchInput.value +
"&targetYear=2019&targetMonth" +
searchInput1.value +
"&targetDay=" +
searchInput2.value;
You are actually getting [HTMLElement Object] because document.getElementById returns the element itself (so a HTMLElement object), and the element, when converted to string, is represented in that format.
In order to get the value of your inputs (<input>, <select>, <textarea>), you have to pass through their value property.
Check the example below:
// Getting HTMLElement objects here.
const select = document.getElementById('mySelect'),
textInput = document.getElementById('myInputText'),
numberInput = document.getElementById('myInputNumber'),
textarea = document.getElementById('myTextarea');
// Getting their value here (XXX.value).
select.addEventListener('change', () => (console.log(select.value)));
textInput.addEventListener('keyup', () => (console.log(textInput.value)));
numberInput.addEventListener('keyup', () => (console.log(numberInput.value)));
textarea.addEventListener('keyup', () => (console.log(textarea.value)));
<select id="mySelect">
<option value="firstOption">1</option>
<option value="secondOption">2</option>
</select>
<input type="text" id="myInputText">
<input type="number" id="myInputNumber">
<textarea id="myTextarea"></textarea>
In your case, you will need to do the following:
function findDetails() {
let searchLink = "https://www.geniecontents.com/fortune/internal/v1/yearly?birthYear=" + searchInput.value + "&targetYear=2019&targetMonth"
+ searchInput1.value + "&targetDay=" + searchInput2.value;
httpRequestAsync(searchLink, theResponse);
}

How to change to default the selected dropdown [duplicate]

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

change dropdown list to its original state

i have two dropdownlists in my view. by changing the value on the first one i can change the value on the second one. in the first run it works fine using scrip below.
but when i change the first dropdownlist to something else it will not work. i believe if i can change the second dropdownlist value and text and .... rest to its original state it will be ok.
here is my code :
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
#foreach (var item in Model)
{
<option value="#item.DepartmentTitle">#item.DepartmentTitle</option>
}
</select>
</td>
</tr>
<tr>
<td>grade</td>
<td>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>
and here is my script :
$('#ddlDepartment')
.change(function() {
debugger;
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
});
}
});
i get the erro here:
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
You have to move getGrade() function outside. getGrade() function bind a change event handler for second select EVERYTIME you changed the first select.
Final Solution
$('#ddlgrade').change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $(this).val();
if(ddlDepartment){
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
}
else{
alert("Please select department first!");
}
});
Please take a look how works your code:
$('#ddlDepartment')
.change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
alert(ddlDepartment);
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
alert(grade);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
<option val="1">acb</option>
<option val="1">acfdb</option>
</select>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>

How to change options of a select using JavaScript

I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});

How to click on a button, and have the item in question go to the next list using javascript?

I have this problem. I have two lists. One with the items of my fridge (that's the assignment :) ) and other with the items of the shop. I want to be able to click on an item of the fridge, and have it show up on the list of the left. In javascript, that is.
If anyone knows how to do it, I'd be very glad to hear from you.
Daniel
Using JavaScript:
function get(id) {
return document.getElementById(id);
}
document.addEventListener('click', function(event) {
event = event || window.event;
if (event) {
var el = event.target,
ePa = el.parentNode,
htm = "";
if (String(ePa.id) === "list1") {
htm = el.parentNode.removeChild(el);
get("list2").appendChild(htm);
} else if (String(ePa.id) === "list2") {
htm = el.parentNode.removeChild(el);
get("list1").appendChild(htm);
}
}
}, false);
Example here: http://fiddle.jshell.net/Shaz/EEfhh/
I wrote this - before I saw the Homework tag.
Would have been nice to see what you had already done before I did your assignment for you
<script>
var shopItems = [];
function addShop(theForm) {
var sel = theForm.fridge;
if (sel.selectedIndex < 1) return;
var opt = sel.options[sel.selectedIndex]
if (shopItems[opt.text]) return
shopItems[opt.text]=opt.value;
theForm.shop.options[theForm.shop.options.length]=new Option(opt.text,opt.value);
theForm.shop.options[theForm.shop.options.length-1].selected=true;
}
</script>
<form>
<select name="fridge" >
<option value="">Please select</option>
<option value="cheese">Cheese</option>
<option value="butter">Butter</option>
</select>
<input type="button" onclick="addShop(this.form)" value=" >>> ">
<select name="shop" >
<option value="">Please select</option>
</select>
</form>

Categories