style.display not working in Chrome, Safari - Firefox, IE11 OK - javascript

I have a simple form with cross-browser issues. The form has two select lists, “class_chorus” and “accompaniment”. On page load, class_chorus is displayed and accompaniment is hidden. If the user selects the Children’s Chorus option, the accompaniment select list should display. It works correctly in Firefox 35 and IE11. I cannot get it to work in Chrome 40 or Safari 5.1.7. What am I missing here?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="">
<table id="formTable" border="0">
<tr valign="top" style="margin-bottom:0">
<td>Class/Chorus </td>
<td>
<select name="class_chorus" size="1">
<option value="" onclick="hideAccomp();">Any</option>
<option value="Preschool" onclick="hideAccomp();">Early Childhood</option>
<option value="Elementary" onclick="hideAccomp();">Elementary</option>
<option value="Childrens Chorus" onclick="showAccomp();">Children's Chorus</option>
</select>
</td>
</tr>
<tr valign="top" style="margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0">
<td>
<div id="accomp" style="display:none"><br />
Accompaniment<br /><br />
</div>
</td>
<td>
<div id="accomp2" style="display:none"><br />
<select name="accompaniment" id="accompaniment" size="1" >
<option value="">Any</option>
<option value="None">None</option>
<option value="Piano">Piano</option>
</select>
</div><br />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
function showAccomp() {
document.getElementById("accomp").style.display = "inline";
document.getElementById("accomp2").style.display = "inline";
}
function hideAccomp() {
document.getElementById("accomp").style.display = "none";
document.getElementById("accomp2").style.display = "none";
}
</script>
</body>
</html>

No you don't need to use jQuery, the problem isn't your Javascript but rather your HTML. The onclick attribute is not supported in Chrome and IE when used on option elements. The best cross browser method would be to use the onchange attribute on your select (remove all onclicks on the option tags) and then write a third function to determine whether to call the show or hide functions you wrote.
Your new HTML:
<select name="class_chorus" size="1" onChange="checkValue(this.selectedIndex)">
<option value="">Any</option>
<option value="Preschool">Early Childhood</option>
<option value="Elementary">Elementary</option>
<option value="Childrens Chorus">Children's Chorus</option>
</select>
Your new JS function:
function checkValue(index)
{
if(index == 3)
showAccomp();
else
hideAccomp();
}
Bear in mind that this assumes your Children's Chorus value is always fourth in the list. If that position could change periodically, it might be better to get the value itself and compare that instead.

You are probably running into issues as a result of putting the event listener on the individual <option> elements, rather than the <select> (browsers are VERY picky about what you can do with <option> elements).
Try binding a function to the onchange for the <select>, instead, and then, when the value changes, get the new value and trigger the correct function based on that.
Trying to use the code that you already have, you could do something like this:
<select name="class_chorus" size="1" onchange="toggleAccomponement(event);">
<option value="">Any</option>
<option value="Preschool">Early Childhood</option>
<option value="Elementary">Elementary</option>
<option value="Childrens Chorus">Children's Chorus</option>
</select>
. . . and then, in the <script> section:
function toggleAccomponement(event) {
var sCurrSelection = event.target.value;
if (sCurrSelection === "Childrens Chorus") {
showAccomp();
}
else {
hideAccomp();
}
}

better Use JQuery show()
http://api.jquery.com/show/
and hide()
http://api.jquery.com/hide/

Related

Radio Button Yes or No call to JavaScript Visible or Hidden Select List

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.

Filter drop down jquery is not working on IE but is on Chrome/FF

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.

Understanding a basic onChange example

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.

Hiding a class of Div depending on Select statement option

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/)

How to pass parameters on onChange of html select

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);
}

Categories