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
Related
How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
I'm not a coder ut I've found this code here
http://jsfiddle.net/kjy112/kchRh/
<textarea id="mytext"></textarea>
<select id="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
I'd like to modify it so that I've more than one dropdown and each one add his text in the same field.
Practically I'd have to create a compact code easily for the user so that the user select some phrases using the dropdown and the code will fill the text field.
If I can be more precise please let me know. As said Iìm not a coder so if you can write down the code to use I'll be very happy.
Thanks!
Here's a js bin with multiple dropdowns' onchange event being listed to: https://jsfiddle.net/kchRh/944/
You want to give the dropdowns class names and then loop through each drop down to setup their listeners.
HTML:
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">2None</option>
<option value="2text1">2text1</option>
<option value="2text2">2text2</option>
<option value="2text3">2text3</option>
<option value="2text4">2text4</option>
</select>
JS:
var mytextbox = document.getElementById('mytext');
var mydropdowns = document.getElementsByClassName('dropdown');
for(i=0;i<mydropdowns.length;i++) {
mydropdowns[i].onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
}
I'd suggest the following approach:
// create a reusable function:
function updateTextArea() {
// get all the elements with the class 'dropdown':
var selectElems = document.querySelectorAll('.dropdown'),
// get the <textarea> element, using its id:
textArea = document.getElementById('mytext'),
// using Array.prototype.filter on the array-like
// NodeList, using Function.prototype.call, in
// order to iterate over the found '.dropdown'
// elements to form an array of only those elements
// with a non-zero-length value:
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
// iterating over the filter-created array, to form a map of
// the selected values of the elements:
}).map(function(el) {
return el.value;
// joining those arrays together, with Array.prototype.join,
// to form a comma-separated string of values, and appending
// a period:
}).join(', ') + '.';
// setting the value of the <textarea> to:
// - an empty string (if the values variable is
// just the appended-period), or to the value of
// the values variable:
textArea.value = values === '.' ? '' : values;
}
// as above, retrieving the '.dropdown' elements:
var selects = document.querySelectorAll('.dropdown');
// iterating over the '.dropdown' elements, using
// Array.prototype.forEach:
Array.prototype.forEach.call(selects, function(el, index, arr) {
// within the anonymous function of Array.prototype.foreach:
// the first argument (here: 'el') is the current array-element,
// second argument (here: 'index') is the index of the current
// array-element within the array over which we're iterating,
// third argument (here: 'arr') is the array over which we're
// iterating.
// binding updateTextArea as the change event-handler for
// each of the array-elements over which we iterate:
el.addEventListener('change', updateTextArea);
});
function updateTextArea() {
var selectElems = document.querySelectorAll('.dropdown'),
textArea = document.getElementById('mytext'),
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
}).map(function(el) {
return el.value;
}).join(', ') + '.';
textArea.value = values === '.' ? '' : values;
}
var selects = document.querySelectorAll('.dropdown');
Array.prototype.forEach.call(selects, function(el) {
el.addEventListener('change', updateTextArea);
});
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">None</option>
<option value="text5">text5</option>
<option value="text6">text6</option>
<option value="text7">text7</option>
<option value="text8">text8</option>
</select>
JS Fiddle demo.
Note, in the HTML, I've changed from the use of id to identify the <select> elements, to using class; simply because it allows a group of elements to be associated together without having to use a large number of ids and subsequently having to update the JavaScript in turn with the HTML.
Referencs:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.map().
document.querySelectorAll().
eventTarget.addEventListener().
Function.prototype.call().
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;
};
I have an html form that triggers a function to change a value, reference: http://jsfiddle.net/ZvuMh/3/
How can I use avalue dynamically in another function?
HTML:
<select id="sort_post_date">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
</select>
Change value function:
var avalue='';
function getSelectData(id) {
// set value to be the current selected value
avalue = jQuery(id+" option:selected").val();
// change value whenever the box changes
jQuery(id).change(function () {
avalue = jQuery(id+" option:selected").val();
console.log("I see a change! -> "+avalue);
});
console.log(avalue);
return avalue;
}
var d = getSelectData("#sort_post_date");
console.log(d);
Another function that wants to inherit avalue when function getSelectData changes it to another letter:
function somefunction(){
var test = "foo"+avalue;
}
why not just call it directly like this, this way, the somefunction will be called every time the letter changes:
// change value whenever the box changes
jQuery(id).change(function () {
avalue = jQuery(id+" option:selected").val();
console.log("I see a change! -> "+avalue);
somefunction(avalue);
});
function somefunction(avalue){
var test = "foo"+avalue;
}
Use the global scope for that variable, like so window.avalue = 'value' and access it with window.avalue