Accessing the value of an HTMLSelectElement - javascript

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);
}

Related

display current alert when change select value

I have a select (dropdown) and an input. When I enter a number at input, select value change with that number:
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>
I want when change select value, display an alert:
document.getElementById('input').addEventListener('input', function (event){
let de = new Event('change');
document.getElementById('select').dispatchEvent(de);
document.getElementById('select').value = document.getElementById('input').value;
})
document.getElementById('select').addEventListener('change', function (event){
alert(document.getElementById('select').text + ' was selected.')
})
Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
How can I fix this problem?
I think this will help you.
//First Way
document.addEventListener('DOMContentLoaded', event => {
const target_input = document.querySelector('#input'),
target_select = document.querySelector('#select');
if (target_input != null) {
target_input.addEventListener('input', event => {
const { target } = event;
for (const node of [...target_select.childNodes]) {
if (node.nodeType == 1) {
if (node.value == target.value) {
node.selected = true;
alert(`${node.textContent} is selected`)
break;
}
}
}
})
}
});
// Second way
const {input, select} = {input: document.getElementById('input'), select: document.getElementById('select')};
input.addEventListener('input', function (event){
const selector = select.querySelector(`option[value="${input.value}"]`);
if (selector == null) {
alert('Does not exist!');
return '';
}
selector.selected = true;
select.dispatchEvent(new Event('change'));
})
select.addEventListener('change', function (event){
alert(select.value + ' was selected.')
})
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>
Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
Slightly confused, but-
Steps for detecting dropdown value change:
Get the element
Add an event listener for change
Detect the selected value
Code:
elem = document.getElementById("select")
elem.addEventListener("change", function(e) {
alert(elem.options[elem.selectedIndex].innerText + " was selected")
})

storing content of dom elements inside an object

I have this function client_choice() which returns the stored value of dom elements if conditions are met
it iterates over each key and value , the keys and values are the content of dom elements
I tried to declare them outside the function and insert this objects as arguments, which does not work, I tried an click event which does not fire
also inserting them inside the function did not work either
question is how do i pass the content of the dom elements to the function ?
let file1 = $('#select_updateFile option:selected').text();
let file2 = $('#select_updateFile option').eq(2).text();
let column = $('.column_select option:selected').text();
// condition
let condition = $('.condition_select option:selected').text();
let update_data = {file1: column};
let conditon_data = {file2: condition};
function client_choice() {
const keyCondtion_true = (currentValue) => currentValue !== "select column" && currentValue !== "";
const valueCondition_true= (currentValue) => currentValue !== "select column" && currentValue !== "";
// variables
let meta_data = {...update_data, ...conditon_data};
if (Object.keys(meta_data).every(keyCondtion_true) && Object.values(meta_data).every(valueCondition_true)) {
return {"update": update_data, "condition": conditon_data}
} else {
console.log("both wrong")
return false
}
}
html
<select name="selectFile" id="selectFile">
<option value="">choose File</option>
<option class="file1" value="col1.xlsx">file1.txt</option>
<option class="file2" value="col2.xlsx">file2.xlsx</option>
</select>
<select name="column_select" class="columselect">
<option value="">choose Columns</option>
<option class="column" value="column1">column1</option>
<option class="column" value="column2">column2</option>
<option class="column" value="column3">column3</option>
<option class="column" value="column4">column4</option>
</select>
<select name="condition_select" class="condition_select">
<option value="">choose condtiton</option>
<option class="condtiton" value="condtiton1">condtiton1</option>
<option class="condtiton" value="condtiton2">condtiton2</option>
<option class="condtiton" value="condtiton3">condtiton3</option>
<option class="condtiton" value="condtiton4">condtiton4</option>
</select>
<button type="button" id="button">click me !!!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

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 keep drop down menu variable by function

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>

How to disable drop down when selecting one in php

could someone help me fix my code?
My problem is how to disable another drop box when selected one?
I am using PHP and JavaScript programming language.
I hope that anyone can help me because it is very important.
Here's my code:
<head>
<script type = "text/javascript">
function disableDrop(){
if(frmMain.sltMain.options[1].selected){
frmMain.sltSecondary.disabled = true;
}
else{
frmMain.sltSecondary.disabled = false;
}
}
</script>
</head>
<form ID = "frmMain">
<select ID = "sltMain" onchange = "disableDrop();">
<option value = "onetime" selected>One-Time</option>
<option value = "recurring">Recurring</option>
</select>
<select ID = "sltMain" onchange = "disableDrop();">
<option value = "onetime">One-Time</option>
<option value = "recurring" selected>Recurring</option>
</select>
</form>
Try This : Demo
HTML CODING :
<select ID = "sltMain" onchange = "disableDrop(this);">
<option value = "onetime" selected>One-Time</option>
<option value = "recurring">Recurring</option>
</select>
<select ID = "sltSecondary" onchange = "disableDrop1(this);">
<option value = "onetime">One-Time</option>
<option value = "recurring" selected>Recurring</option>
</select>
</form>
JAVASCRIPT:
function disableDrop(elem) {
if(elem.value == 'recurring'){
document.getElementById('sltSecondary').disabled = true;
}
else{
document.getElementById('sltSecondary').disabled = false;
}
}
function disableDrop1(elem) {
if(elem.value == 'onetime'){
document.getElementById('sltMain').disabled = true;
}
else{
document.getElementById('sltMain').disabled = false;
}
}
whre is the "sltSecondary" ID ??
the second item has the same id i think you mean
<form ID = "frmMain">
<select ID = "sltMain" onchange = "disableDrop();">
<option value = "onetime" selected>One-Time</option>
<option value = "recurring">Recurring</option>
</select>
<select ID = "sltSecondary" onchange = "disableDrop();">
<option value = "onetime">One-Time</option>
<option value = "recurring" selected>Recurring</option>
</select>
</form>

Categories