When either radio button is pressed there is no change in the visibility of select tag. Simply nothing happens, not even errors.
This is my first attempt at using JavaScript and I have spent about 4 days now looking at a variety of examples to do this. I feel my syntax and the placement of everything is correct. I'm lost as to what I can possibly be missing.
Using the "Inspect Element Q" Inspector tab, when the radios are checked there is no change in anything. I just thought about it. I don't know how to use the debugger.
Before I published this here I put the code posted here into the JSfiddle. It runs there: turning the drop list on and off. So, might be something else in my PHP page.
Here is my code:
<head>
<script type="text/javascript">
function hasClass(){
var checked_yes = document.getElementById("hasClass_yes").checked;
var checked_no = document.getElementById("hasClass_no").checked;
if(checked_yes) {
document.getElementById("class_drop_list").style.visibility="visible";
} else if(checked_no){
document.getElementById("class_drop_list").style.visibility="hidden";
}
}
</script>
</head>
<tr>
<td>Does the monster have a class?
<label for="hasClass_yes">Yes
<input type="radio" id="hasClass_yes" name="hasClass" onclick="hasClass();" />
</label>
<label for="hasClass_no">No
<input type="radio" id="hasClass_no" name="hasClass" onclick="hasClass();" />
</label>
<select style="visibility:" id="class_drop_list" name="monsters_class">
<option value="Adept">Adept</option>
<option value="Barbarian">Barbarian</option>
<option value="Cavalier">Cavalier</option>
<option value="Cleric">Cleric</option>
<option value="Druid">Druid</option>
<option value="Healer">Healer</option>
<option value="Jumper">Jumper</option>
<option value="Marshalist">Marshalist</option>
<option value="Rogue">Rogue</option>
<option value="Rook">Rook</option>
<option value="Sorcerer">Sorcerer</option>
<option value="Swashbuckler">Swashbuckler</option>
<option value="Witch">Witch</option>
<option value="Wizard">Wizard</option>
</select>
</td>
</tr>
I have also tried this script
<script type="text/javascript">
function hasClass(){
var checked_yes = document.getElementById("hasClass_yes");
var class_drop_list_on = document.getElementById("class_drop_list");
class_drop_list_on.style.visibility = checked_yes.checked ? "visibility" : "visible";
}
</script>
this seems to be working as a snippet. what's the problem?
<head>
<script type="text/javascript">
function hasClass(){
var checked_yes = document.getElementById("hasClass_yes").checked;
var checked_no = document.getElementById("hasClass_no").checked;
if(checked_yes) {
document.getElementById("class_drop_list").style.visibility="visible";
} else if(checked_no){
document.getElementById("class_drop_list").style.visibility="hidden";
}
}
</script>
</head>
<tr>
<td>Does the monster have a class?
<label for="hasClass_yes">Yes
<input type="radio" id="hasClass_yes" name="hasClass" onclick="hasClass();" />
</label>
<label for="hasClass_no">No
<input type="radio" id="hasClass_no" name="hasClass" onclick="hasClass();" />
</label>
<select style="visibility:" id="class_drop_list" name="monsters_class">
<option value="Adept">Adept</option>
<option value="Barbarian">Barbarian</option>
<option value="Cavalier">Cavalier</option>
<option value="Cleric">Cleric</option>
<option value="Druid">Druid</option>
<option value="Healer">Healer</option>
<option value="Jumper">Jumper</option>
<option value="Marshalist">Marshalist</option>
<option value="Rogue">Rogue</option>
<option value="Rook">Rook</option>
<option value="Sorcerer">Sorcerer</option>
<option value="Swashbuckler">Swashbuckler</option>
<option value="Witch">Witch</option>
<option value="Wizard">Wizard</option>
</select>
</td>
</tr>
So, I have done the following trying to solve this.
Copied the relevant code from the php file into a separate html file to test it outside of the larger php file. Just the script and the yes/no inputs, and select tag .
It still did not work.
Installed another browser on my system - Chromium. The test file did not run there either.
Copied the test file and the original php file to usb and tried it on a windows computer. Still did not run there.
Modified the test file to be as it is below - and it has worked in all browsers on both Windows and Ubuntu computers.
<html>
<head>
<style></style>
<script type="text/javascript">
function hasClassYes(){
document.getElementById("class_drop_list").style.visibility="visible";
}
function hasClassNo(){
document.getElementById("class_drop_list").style.visibility="hidden";
}
</script>
</head>
<body>
<form action="make_monster.php" method="post">
<table>
<tr style="background-color:#999999">
<td>Does the monster have a class?
<label for="hasClass_yes">Yes
<input type="radio" id="hasClass_yes" name="hasClass" onclick="hasClassYes();" />
</label>
<label for="hasClass_no">No
<input type="radio" id="hasClass_no" name="hasClass" onclick="hasClassNo();" />
</label>
<select style="visibility:" id="class_drop_list" name="monsters_class">
<option value="Adept">Adept</option>
<option value="Barbarian">Barbarian</option>
<option value="Wizard">Wizard</option>
</select>
</td>
<tr>
</table>
</form>
</body>
</html>
What's different is that instead of using IF or SWITCH statements inside the same function to determine the state of yes no and set the style attribute in the select tag, I now have two separate functions for yes or no.
I have this code working in Chrome and FF, but it is not working in IE. It is a simple form with 2 drop downs, with the second drop down filtering based on the first. The selection then brings you to a different site on Submit. In IE, the filtered options are greyed out rather than hidden.
<!DOCTYPE html>
<head>
<html>
<title>Dropdowns</title>
<script src="./jquery-1.11.0.min.js"></script>
<script>
function filterList(countryList) {
var selected = countryList.find(":selected").text();
if (selected == "US") {
showOption($("#city .US"));
hideOption($("#city .UK, .IE"));
}
else if (selected == "UK") {
showOption($("#city .UK"));
hideOption($("#city .US, .IE"));
}
else {
showOption($("#city .IE"));
hideOption($("#city .UK, .US"));
}
$("#city").find("option:not(:disabled):first").prop('selected', true);
}
function hideOption(option) {
option.attr("disabled", 'disabled');
option.hide();
}
function showOption(option) {
option.removeAttr('disabled');
option.show();
}
$(document).ready(function () {
var countryList = $("#country");
filterList(countryList);
$("#country").change(function () {
filterList($(this));
});
});
</script>
<script>
$(document).ready(function () {
var countryList = $("#country");
filterList(countryList);
$("#country").change(function(){
filterList($(this));
});
});
</script>
</head>
<body>
<div>
<h1>Please select your home city</h1>
</div>
<form name="dropdown" id="dropdown">
<div>
<select class="country" id="country" name="country">
<option value="United States">US</option>
<option value="United Kingdom">UK</option>
<option value="Ireland">IE</option>
</select>
</div>
<div>
<select class="city" id="city" name="city">
<!-- US options Below -->
<option value="http://www.google.ie" class="US">Chicago</option>
<option value="http://www.google.com" class="US">New York</option>
<option value="http://www.stackoverflow.com" class="US">Miami</option>
<!-- UK options Below -->
<option value="http://www.linkedin.com" class="UK">London</option>
<!-- Ireland options Below -->
<option value="http://www.ebay.com" class="IE">Ireland</option>
</select>
</div>
<div>
<input type="checkbox" name="checkbox" value="checkbox" />Remember my
selection<br />
</div>
<div>
<input type="button" value="Set as My Home" onclick=
"goToNewPage(document.dropdown.city)" />
</div>
</form>
</body>
</html>
Not all browsers support hiding option elements, IE for instance does not support hiding an option in any way.
The "greyed out" you're seeing is what happens when you disable an option, and you're not only hiding them, but disabling them as well.
As a sidenote, disabled in this context is a property, and you should be using
option.prop('disabled', true);
The cross browser way to filter options inside a select is to remove and insert the elements, not hide and show them.
I just went through this MDN tutorial regarding the DOM. Under the final section "Testing the DOM API" the following code is presented:
<html>
<head>
<title>DOM Tests</title>
<script type="application/javascript">
function setBodyAttr(attr,value){
if (document.body) eval('document.body.'+attr+'="'+value+'"');
else notSupported();
}
</script>
</head>
<body>
<div style="margin: .5in; height: 400;">
<p><b><tt>text</tt>color</b></p>
<form>
<select onChange="setBodyAttr('text',
this.options[this.selectedIndex].value);">
<option value="black">black
<option value="darkblue">darkblue
</select>
<p><b><tt>bgColor</tt></b></p>
<select onChange="setBodyAttr('bgColor',
this.options[this.selectedIndex].value);">
<option value="white">white
<option value="lightgrey">gray
</select>
<p><b><tt>link</tt></b></p>
<select onChange="setBodyAttr('link',
this.options[this.selectedIndex].value);">
<option value="blue">blue
<option value="green">green
</select> <small>
<a href="http://www.brownhen.com/dom_api_top.html" id="sample">
(sample link)</a></small><br>
</form>
<form>
<input type="button" value="version" onclick="ver()" />
</form>
</div>
</body>
</html>
Everything works as expected, except for the link color: under Chrome a change in link color only gets applied once you change the text color (i.e., the first property). Shouldn't all changes be immediate?
Thanks in advance.
That just isn't the right way to change the color of links on a page (should be done with CSS), and the body.link attribute was deprecated in HTML version 4 (http://www.w3schools.com/tags/att_body_link.asp). I can't be 100% positive, but I would say the reason it doesn't work is because Chrome is a modern browser adopting web standards - the body.link attribute is not a standard.
I'm fairly new to javascript and I'm trying to make an form for my website and I'm stuck on the javascript,
This is what I have:
<script type="text/javascript">
function hide(opt) {
if (getElementsByClassName(opt).style.display='none';){
getElementsByClassName(opt).style.display='block';
}
else{
getElementsByClassName(opt).style.display='none';
}
}
</script>
What I intended the script to do was recieve a variable (the option chosen by the user) and then reveal all the elements with the class of the same name (so if the option was orc the orc div would be displayed, but be hidden if the option chosen was elf etc.)
Html:
<form name="chargen" action="" method="post">
Name:<Input name="name" type="text" />
Gender:<select name="gender">
<option>Choose Gender...</option>
<option>Male</option>
<option>Female</option>
</select>
Species:<select name="species" onchange="hide(document.chargen.species.options[
document.chargen.species.selectedIndex ].value)">
<option> Choose Species...</option>
<option value="human">Human</option>
<option value="orc">Orc</option>
<option value="elf">Elf</option>
<option value="dwarf">Dwarf</option>
<option value="drow">Drow</option>
<option value="ent">Ent</option>
</select>
<div class="human" style="display:none;">
Sub Species:<select name="subspecies1">
<option>Norseman</option>
<option>Hellenic</option>
<option>Heartlander</option>
</select>
</div>
<div class="orc" style="display:none;">
Sub Species:<select name="subspecies2">
<option>Black Orc</option>
<option>Fel Orc</option>
<option>Green Orc</option>
</select>
</div>
<div class="human" style="display:none;">
Homeland:<select name="homeland1">
<option>Choose Homeland...</option>
<option value="citadel">Citadel</option>
<option value="wildharn">Wildharn</option>
<option value="Merith">Merith</option>
</select>
</div>
<div class="orc" style="display:none;">
Homeland:<select name="homeland2">
<option>Choose Homeland...</option>
<option value="1">Berherak</option>
<option value="2">Vasberan</option>
</select>
</div>
Unfortunately nothing happens when I change the contents of the species combobox (I've tried on multiple browsers) What am I doing wrong?
I realise that getElementsByClassName() is a HTML5 function, but according to the interwebs it is compatible with all major browsers.
Thanks for your time
getElementsByClassName returns an array, you must iterate on the result. And be careful to the = in tests (instead of ==).
But I suggest you have a look at jquery. Your life will be easier as what you want can be done as :
$('.human, .orc, .elf, .dwarf, .drow, .ent').hide();
$('.'+opt).show();
(see fiddle : http://jsfiddle.net/dystroy/2GmZ3/)
I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().
How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
The above example gets you the selected value of combo box on OnChange event.
Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:
function myFunction(chosen) {
console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
JavaScript Solution
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
I found #Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.
jQuery solution
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
See also
.val() jQuery API Documentation
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
Html template:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js code:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
function setMyValue(v) {
console.log(v);
}
<select onchange="setMyValue(this.value)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
This worked for me onchange = setLocation($(this).val())
Here.
#Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Simply:
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve_other() {
alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve() { alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
<p>RETRIEVING TEXT IN OPTION OF SELECT </p>
<form name="myForm" action="">
<P>Select:
<select id="SMS_recipient">
<options value='+15121234567'>Andrew</option>
<options value='+15121234568'>Klaus</option>
</select>
</p>
<p>
<!-- Note: Despite the script engine complaining about it the code works!-->
<input type="button" onclick="retrieve()" value="Try it" />
<input type="button" onclick="retrieve_other()" value="Try Form" />
</p>
</form>
</HTML>
</BODY>
Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value
//html code
<select onchange="get(this)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
//javscript code
function get(select) {
let value = select.value;
console.log(value);
}