I'm trying to make it so when a select box within a div changes, it will grab values from both that select box and one other one that I've yet to add, but I don't know how to go about it.
I currently have this code
<select id='selMag' onchange='getSelMag(this)'>
<option value='0.0>Select Minimum Magnitude</option>
<option value='1.0'>1.0</option>
<option value='2.0'>2.0</option>
<option value='3.0'>3.0</option>
<option value='4.0'>4.0</option>
<option value='5.0'>5.0</option>
<option value='6.0'>6.0</option>
<option value='7.0'>7.0</option>
<option value='8.0'>8.0</option>
<option value='9.0'>9.0</option>
<option value='10.0'>10.0</option>
</select>
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
}
This, as it is right now, works fine from grabbing it from the , but I would like to add another one and put them inside a container div, and make it so when either one changes it will grab the values from both of them, add both strings together, and convert them into a number. I plan to make it so the select box above will not have the decimal values and just be 1, 2, etc. and have the second box be .1, .2, etc. so when they are added together, it will show 1.1, 1.2, etc.
Presumably, the select is in a form. To be successful, form controls must have a name, so:
<select id='selMag' name='selMag' onchange='getSelMag(this)'>
Adding a name nearly always obviates the requirement for an ID. If the other select also has a name:
<select name='selMag2'>
and it belongs to the same form as the first, you can reference it from the getSelMag function via the form:
function getSelMag(sel) {
// Always declare variables
var value = Number(sel.value);
// Access them from the appropriate scope
console.log(value);
// Reference the other select using named properties of the form
var otherSelect = sel.form.selMag2;
// Do stuff with it
var otherValue = otherSelect.value;
}
Note that all form controls have a form property that references their parent form, and that the controls belonging to a form can be accessed via the form's elements collection.
Those with names (and in some browsers those with IDs) can be accessed as named properties of the form and of the elements collection, and also by index in the collection.
It seems that you want to concatenate the values with a period between, so the function might look like:
function getSelMag(sel) {
var value0 = sel.form.selMag.value;
var value1 = sel.form.selMag2.value;
console.log(value0 + '.' + value1);
}
and the HTML:
<form>
<select name="selMag" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
<select name="selMag2" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
</form>
Use the answer from this link to get the value of other select box in getSelMag() function
Get selected value in dropdown list using JavaScript?
as follows:
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag2");
var option2 = e.options[e.selectedIndex].text;
//do whatever u want
}
You can make another function say x() that will be called for other select box you make and access the value of first select box from that
<select id='selMag2' onchange='x(this)'>
as
function getSelMag2(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag");
var option1 = e.options[e.selectedIndex].text;
//do whatever u want
}
Hope this helps
Related
Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...
I've looked around and I don't see this being asked before.
I have a select box, like so:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
I want to add another option...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value of the option.
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
I wanted to know what the best way to do this is with plain old javascript - I'll use jQuery if I have to.
Any ideas? An example would be great as well.
Take a look at this code. I think this is what you're trying to do:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom. Then after you choose a custom value, it will rewrite the value of that the custom option element to the value you just entered in the prompt. I logged the new value after assigning it to show you that it is working.
Here is a fiddle: https://jsfiddle.net/ng7xvy05/
Your onchange event is the appropriate way to handle this. This is mostly a matter of user interface (UX) design though. To do this in the prompt fashion you ought to use parseFloat:
change() {
var value = prompt('You\'ve chosen Other. Please enter a value', '60');
if(value) {
value = parseFloat(value);
// apply it to your model
} else {
// apply NULL to your model
}
}
From a UXD point of view I would use a typeahead input. It would autosearch known answers but also allow the user to input their own. This is not standard html so you would need to write this yourself or use jquery. But from a user interface design point of view, prompts suck.
I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach
I have a <"select'>, with some options and onChange listerner. When an option is selected certain values are set in some hidden fields. So if this change event won't happen, it means the values of those fields will remain in their initial state i.e 0.
What I want to achieve is that, only when an onchange has happened, that means hidden fields values has been set, I get the values from those hidden fields and perform some ajax with the data
This is what I have so far:
<select class="form-control choosedegree" name="sem" id="semester">
<option value="" selected="selected" disabled>Select Semester</option>
<option value="1">Year 1, Semester 1</option>
<option value="2">Year 1, Semester 2</option>
<option value="3">Year 2, Semester 1</option>
</select>
After this has fired, and finished,
$('select#semester').on('change', function(){});
then find some hidden input and set the new value gotten as a result of the onChange.
$('div.tab-content div.tab-pane.active form').find('input[type=hidden]').val()
How can i achieve that! Any kind of help is highly appreciated.
do like this:
$('select#semester').on('change', function(){
if($(this).val() != "")
{
// send ajax call here
setTimeout(SendAjaxCall,3000); // execute SendAjaxCall after 3 secs
}
});
function SendAjaxCall()
{
var val = $('div.tab-content div.tab-pane.active form').find('input[type=hidden]').val();
}
i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().