I have a slight issue. I have options with a “value” and a “data-name”.
<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>
I want the computer return a specific value if the selected option is a certain “data-name”
Say there are 2 “data-names”, X and Y.
How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?
I’m thinking something along the lines of this:
var data_name1 = e.options[e.selectedIndex].dataset.name1;
if (data_name1 == “X”) {
…
}
else if (data_name == “Y”) {
…
}
else {
…
}
Is this possible?
Thanks!
Full code---
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
You need to use the == operator to compare objects.
= is an assignment expression.
if (data_name1 == “X”) {
// Operations if data_name is equal to X
}
else if (data_name == “Y”) {
// Operations is data_name is equal to Y
}
else {
}
Related
I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)
I'm trying to get two values from different select elements and access those elements outside a function.
function firstValue(){
var e = document.getElementById("val-selec");
var strUser = e.options[e.selectedIndex].text;
return strUser;
}
function secondValue(){
var e1 = document.getElementById("val-selec1");
var strUser1 = e.options[e.selectedIndex].text;
return strUser1;
}
if(firstValue() == "val1" && secondValue() == "val2"){
//do something
}
when I log my function it just returns the first value it does not change when you select another option. What would be a way I can compare values and to a certain thing
https://jsfiddle.net/v50wdnL1/1/ I included a jsfiddle
Not quite sure why the #onchange events are calling function that only return values and dont do any meaningful operations. Instead make them both call a compare function and in that compare function call your other function which return the values. Example below:
HTML:
<select name="val-select" id="val-selec" onchange="compare();">
<option value="" disabled selected>Select your option</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
<br>
<select name="val-select1" id="val-selec1" onchange="compare();">
<option value="" disabled selected>Select your option</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
JavaScript:
function firstValue(){
var e = document.getElementById("val-selec");
return e.value;
}
function secondValue(){
var e1 = document.getElementById("val-selec1");
return e1.value
}
function compare(){
var value1 = firstValue();
var value2 = secondValue();
console.log(value1 === value2);
}
ok so, I think your code fails because you have a typo (depending where you want to put that if(condition){do_something()}, you are trying to access e when you should access e1 in the function secondValue()
I think you can get away without declaring those functions for the values like so:
function my_action(){
let firstValue = document.querySelector('#val-selec').value;
let secondValue = document.querySelector('#val-selec1').value;
if(firstValue == "val1" && secondValue == "val2"){
//do something
}
}
and then execute that func when u change the select:
<select name="val-select" id="val-selec" onchange="my_action();">
I hope is useful
I have input fields and selects. For different select options there are different equations. After calculating equations, I used .innerHTML to show results. I got first part of the code worked, but I am stuck at the last part. When I try to calculate average of outputs, It shows Nan. Can anyone help with this problem? Thanks in advance.
var container = document.getElementById('container');
var span1 = document.getElementById('span1');
var span2 = document.getElementById('span2');
var output = document.getElementById('output');
function average() {
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseFloat(document.getElementById('d').value);
if (document.getElementById('select1').value == '1') {
span1.innerHTML = ((a+b)/(a*b)).toFixed(2);
} else if (document.getElementById('select1').value == '2') {
span1.innerHTML = ((a*b)/(a+b)).toFixed(2)
} else {
span1.innerHTML = '';
}
if (isNaN(span1.innerHTML)) {
span1.innerHTML = '';
}
if (document.getElementById('select1').value == 'none1') {
span1.innerHTML = 'None'
}
if (document.getElementById('select2').value == '3') {
span2.innerHTML = ((c+d)*100/(c*d)).toFixed(2);
} else if (document.getElementById('select2').value == '4') {
span2.innerHTML = ((c*d)*100/(c+d)).toFixed(2)
} else {
span2.innerHTML = '';
}
if (isNaN(span2.innerHTML)) {
span2.innerHTML = '';
}
if (document.getElementById('select2').value == 'none2') {
span2.innerHTML = 'None'
}
var percent = document.getElementsByClassName('percent');
for (var i = 0; percent.length > i; i++) {
if (percent.length > 0) {
output.innerHTML = percent[i]/(percent.length);
}
}
}
container.addEventListener('change', average);
container.addEventListener('input', average);
<div id="container">
<input id="a" type="number">
<input id="b" type="number">
<select name="abc" id="select1">
<option value="Choose">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="none1">None</option>
</select>
<br>
<input id="c" type="number">
<input id="d" type="number">
<select name="abcd" id="select2">
<option value="Choose">Choose...</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="none2">None</option>
</select>
<span id="span1" class="percent"></span>
<span id="span2" class="percent"></span><br>
<span id="output"></span>
</div>
.innerHTML gets or sets the content of an element by invoking the HTML parser on the string passed as the value or extracted from the element. When the content is, or is to become just text (no HTML to be parsed), you should use .textContent as this will not invoke the HTML parser on the content, which saves processing power. In your case, you should be using .textContent.
Now, either way, data sent to or gotten from either .innerHTML or .textContent is a string, so if you want to do math with the value, you need to first convert it to a number. This can be done in several ways:
parseInt(stringToBeConverted, radix)
parseFloat(stringToBeConverted)
Number(stringToBeConverted)
+stringToBeConverted
Now, you have two issues, first when some of the text fields are still empty, their value is an empty string and parseFloat() on an empty string returns NaN. This can be solved by giving each field a default value of 0 in the HTML (i.e. <input id="a" type="number" value="0">).
Second, even with a, b, c, and d all having numeric values, your math:
((a + b) / (a * b)).toFixed(2);
Will result in NaN when a * b results in 0 because that will result in a division by zero situation.
You need to change your algorithm to test for this situation before doing the math.
I have no idea what you're trying to do, but I think this might be the correct solution it's a working way of getting the value of the percent[i] HTML element:
Change
output.innerHTML = percent[i]/(percent.length);
to
output.innerHTML = percent.item(i).innerHTML/(percent.length);
or
output.innerHTML = percent[i].innerHTML/(percent.length);
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>
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};