I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}
Related
Is there possibility to get all html option from selected dropdown.
While i have
<select class="myselect">
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>
I would like to get whole option which is:
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
As far i as tried i can get all options in html by:
$('.myselect').html()
Or just one data by :
$('.myselect').find(':selected').data('one')
Or just one value
$('.myselect').find(':selected').val()
So is there simple way to get selected whole html option from < option >... to < /option>
Like this - it is not clear if you want the tag or the data attributes so here are either
$(".myselect").on("change",function() {
console.log(this.options[this.selectedIndex]); // complete tag
console.log(this.options[this.selectedIndex].dataset); // array of data attribute values
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
<option value="">Please select</option>
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>
I wasn't quite clear precisely what result you wanted, so here are a couple of ideas to get things you may be interested in:
1) To get the names and values of all the data-attributes you can just call .data() without any arguments and it will return all the data-attributes and their values in an object. There's also an example in the documentation.
2) To get the whole HTML of the selected item you can use outerHTML on the DOM element found by jQuery.
Demo of each below:
//to get the data-attributes
var selectedData = $('.myselect').find(':selected').data();
console.log(selectedData);
//to get the HTML of the selected item:
var selected = $('.myselect').find(':selected')[0].outerHTML;
console.log(selected);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
<option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>
I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}
I could not find any example that suite my problem. I would like to count selected variables from drop down menu using javascript.
My biggest concern is, these drop down menu values are dynamically retrieved from db.The drop down menu is generated multiple times depending on number of student displayed in the form.
This is the codes for drop down menu of examiner name:
<select id="examinerID" name="examinerID">
<option selected disabled>Examiners Name</option>
<%
try{
//connection
String query1="select lecturerID, lecturerFullname from lecturer ";
while(rs1.next())
{
%>
<option value="<%=rs1.getString("lecturerID") %>"><%=rs1.getString("lecturerFullname") %></option>
//close connection and exception
%>
</select>
This is how it actually looks like:
Below the form, I would like to add a list of the examiner (also retrieve from db) and I would like to count how many times an examiner has been selected.
Assume these are the value in drop down menu (to make it easy to understand):
<select id="examinerID" name="examinerID">
<option selected disabled>Examiners Name</option>
<option>Mark</option>
<option>Adam</option>
<option>Lucy</option>
<option>John</option></select>
Expected outcome of counting the selected examiner:
Mark: 2 //assuming Mark has been selected twice
Adam: 1
Lucy: 1
John: 0 //assuming John is not selected to be an examiner
Change Id to class as you are creating multiple instance of select.
For eg:
HTML:-
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option> </select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
JS:-
var count = {};
var selects = document.querySelectorAll("select[name=examinerID]");
for(var i=0;i<selects.length;i++){
selects[i].addEventListener("change",function(event){
count = {};
Array.prototype.forEach.call(selects, function(select, index) {
var selectedValue = select.value;
if(selectedValue != "")
count[selectedValue] = (count[selectedValue])?count[selectedValue]+1:1;
});
console.log(count)
});
}
Re your HTML:
<select id="examinerID" name="examinerID" onchange="checkLecturer()">
First, remove that id value. If you're outputting that in a loop (as your screenshot suggests), you're creating an invalid document, as id values must be unique.
If your goal is to get the value of the select that changed, pass this into your checkLecturer function:
<select name="examinerID" onchange="checkLecturer(this)">
<!-- Here ----------------------------------------^^^^ -->
...and then in checkLecturer, the first argument will be a reference to the select element:
function checkLecturer(select) {
// Use select.value or select.selectedIndex
}
If your goal is to access the values of all of the select boxes, you can find them with document.querySelectorAll:
var selects = document.querySelectorAll("select[name=examinerID]");
That will give you a NodeList, with a length telling you how many were found. You can access each one as though the NodeList were an array. So for instance, this will show the current value of each of them:
var selects = document.querySelectorAll("select[name=examinerID]");
Array.prototype.forEach.call(selects, function(select, index) {
console.log("#" + index + ": " + select.value);
});
(More on that odd-looking use of forEach in this answer on looping through arrays and array-like things such as NodeLists.)
How can I select an option with javascript (/console in google chrome)?
This is a part of the html code:
<nobr>
Element<br>
<span class="absatz">
<br>
</span>
<select name="element" class="selectbox" style="width:114" size="12" onchange="doDisplayTimetable(NavBar, topDir);">
<option value="0">- All -</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">X</option>
<option value="4">C</option>
<option value="5">D</option>
<option value="6">E</option>
<option value="7">F</option>
<option value="8">G</option>
<option value="9">H</option>
<option value="10">I</option>
<option value="11">J</option>
<option value="12">K</option>
<option value="13">L</option>
<option value="14">M</option>
<option value="15">N</option>
<option value="16">O</option>
<option value="17">P</option>
<option value="18">Q</option>
<option value="19">R</option>
</select>
</nobr>
Or http://pastebin.com/JSaKg4HB
I already tried this:
document.getElementsByName("element")[0].value = 1;
But it gives me this error:
Uncaught TypeError: Cannot set property 'value' of undefined
at :2:48
at Object.InjectedScript._evaluateOn (:875:140)
at Object.InjectedScript._evaluateAndWrap (:808:34)
at Object.InjectedScript.evaluate (:664:21)
EDIT:
I I tried it but it don't works on for the full website. Maybe because there is another html tag inside the first html tag(if I download the website, there is another html file called welcome.html where the selectbox is.) I thinks it's in an iFrame, because chrome gives me the Option "show Frame".
EDIT 2:
I can access the frame where the selectbox is but I still won't find the selectbox. Here is the code of the frame(not the full code): pastebin.com/iVUeDbYV
Try this:
document.querySelectorAll('[name="element"]')[0].value;
Although it is very weird that getElementsByName is not working for you. Are you sure the element is in the same document, and not in an iFrame?
The simple answer:
document.getElementById("select_element").selectedIndex = "option index";
Where option index is the index of the option in the dropdown that you'd like to activate.
You can get the index of an option by using this:
var selected = document.querySelector( '#'+div+' > option[value="'+val+'"]' );
Where div is the ID of the <select> tag.
how this helps!
This will do what you want.
document.querySelector('[name="element"]').value = 4 // The value you want to select
and this will retrieve the value
var value = document.querySelector('[name="element"]').value; // 4
this explains what's going on
var option = document.querySelector('[name="element"]');//option element
option.value; // 4
option.selectedIndex; // 4
option.selectedOptions; // [<option value="4">C</option>]
option.selectedOptions[0].innerText; // C
option.selectedOptions[0].value; // 4
Remember that selectedOptions is an array because more than one option may be selected, in those cases, you will have to loop through the array to get each value. As per Hanlet Escaño's comment, make sure your code is set to execute after the DOM has loaded.
window.onload = function() {
document.querySelector('[name="element"]').value = 0; // sets a default value
}
I have 6 different select boxes and a text field which I need to fetch the value from and combine in to one text field using jQuery.
I understand essentially I will build the value for the targetTextField with a string like this: $('#targetTextField').val(opt1+opt2+opt3+opt4+opt5+opt6+textField);
What do I use to fetch the value of select#options1 and transform that in to opt1?
Would it be along the lines of opt1 = $('select#options1').val(); or am I heading in completely the wrong direction?
I've created a basic jsfiddle with just two options at:
http://jsfiddle.net/e2ScF/2/
jQuery
$(function() {
$("#options").change(function(){
var opt1 = $('select#options').val()
}$('#targetTextField').val(opt1+opt2);
});
$("#options2").change(function(){
var opt2 = $('select#options2').val()
}$('#targetTextField').val(opt1+opt2);
});
});
HTML
<select id="options">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">
...but it doesn't appear to be working, so I've obviously misunderstood or missed something.
I made this demo for you, hope it helps
http://jsfiddle.net/e2ScF/5/
$(function() {
$("#options").change(function(){
setTarget() ; // Something has changed so lets rebuild the target
});
$("#options2").change(function(){
setTarget();// Something has changed so lets rebuild the target
});
});
// Just get the values you want and update the target
function setTarget(){
var tmp = $("#options").val();
tmp += $("#options2").val();
$('#targetTextField').val(tmp);
}
for dropdown try following
$('select option:selected').text()
have a look at this it should hopefully give you a pointer in what you need to do.
you can change the name to be a class and then just provide your format you want to display in the input. but from your question in presume it should be about that.
If you have different id for select box
var toalopt=$('select option1:selected').text();
toalopt+=$('select option2:selected').text();
toalopt+=$('select option3:selected').text();
toalopt+=$('select option4:selected').text();
toalopt+=$('select option5:selected').text();
toalopt+=$('select option6:selected').text();
document.getElementById('id where you want to club data').innerHTML=toalopt;
If you have same id
$(document).ready(function(){
$('#optionvalue).click(function(){
var values ='';
$('select[name="sameid"]').each(function(index,item){
values +=$(item).val() +' ';
});
$('id where you want to club data').val(values);
});
});
HTml will be normal select tag with id.
First of all, add a class to each of your select elements to better identify them as a group:
<select id="options" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt1Value1" >Option 1</option>
<option value="opt1Value2" >Option 2</option>
</select>
<select id="options2" class="auto-updater">
<option value="" selected>Choose...</option>
<option value="opt2Value1" >Option 1</option>
<option value="opt2Value2" >Option 2</option>
</select>
<input type="text" id="targetTextField" name="targetTextField" size="31" tabindex="0" maxlength="99">
Then in jQuery, you can use map() to create an array of the values and display them:
$(".auto-updater").change(function() {
var values = $(".auto-updater").map(function() {
return ($(this).val() == "") ? null : $(this).val(); // ignore default option select
// return $(this).val(); // include all values
}).get();
$("#targetTextField").val(values.join(','));
});
Example fiddle
You can see that I've set this up to ignore select elements which are left on their default value. If you uncomment the line beneath it will include all selects, regardless of value chosen.
Minimal code required for you as below:
$(function() {
$("select").change(function(){
var opts=$('option:selected').val();
var oldVal=$('#targetTextField').val();
$('#targetTextField').val(oldVal+opts);
});
});
Find the jsfiddle demo here.