Understanding a basic onChange example - javascript

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.

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.

Using Javascript with HTML to get a selected option and display a String based on value

Sorry if this has been asked before, I've looked around (this site and a couple others) for examples and snippets of code but nothing seems to work.
I'm taking a course in HTML, an assignment requires using a script to check a ddl and display a line of text based on the selected option. The problem is that what I've found online seems a bit different to the example our teacher provided (we're using Dreamweaver 2015 if that makes a difference.)
Here's what I'm stuck with after a couple hours of cannibalizing code from a few different threads.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Hot Buns </title>
</head>
<script type="text/javascript">
function showDetails()
{
var x= document.getElementById("slctOrder");
var val= x.options[x.selectedIndex].text;
<!-- DW only displays item(n) and len after the dot, I typed in "text" manually -->
document.forms["frmOrder"]["Details"].value = val;
<!-- I'm just trying to have it display anything at this point,
same as above, I typed "value" since DW doesn't seem to recognize this code
(this is from the teacher's example) -->
}
</script>
<body>
<p> <h2> Welcome to Hot Buns </h2> <br> <h3> Ham can we bee'f service? </h3></p>
<p> <h2> Place an order </h2> </p>
<form method="get" name="frmOder">
<select name="slctOrder" onChange="showDetails();">
<!-- I'm trying to call the function showDetails()
but neither onChange here nor onClick in the option tag seem to accomplish that -->
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1" onClick="showDetails();"> Last of the Mo-jicama </option>
<option value="2" onClick="showDetails();"> Cheesus Is Born Burger </option>
<option value="3" onClick="showDetails();"> Beets of Burden Burger </option>
<option value="4" onClick="showDetails();"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output name="Details"/>
</form>
</body>
</html>
Couple of minor changes, but here's the working example:
update: outputting selected value into an html element vs alert.
update 2: i've changed the code to match exactly what you have but fixed some of errors to get it to work.
1) You have a typo of the form name "frmOder" but in your code, you used "frmOrder".
document.forms["frmOder"]["Details"].value = val;
2) You are trying to select the element by id but the id attribute doesn't exist:
document.getElementById("slctOrder");
Had to change:
<select name="slctOrder" onChange="showDetails();">
to:
<select id="slctOrder" onChange="showDetails();">
3) There's no need for the onclick events in the option tags.
The reason i switched out the 'output' element in my original answer is because it is not a supported tag in IE.
http://www.w3schools.com/tags/tag_output.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Hot Buns </title>
</head>
<script type="text/javascript">
function showDetails()
{
var x= document.getElementById("slctOrder");
var val= x.options[x.selectedIndex].text;
document.forms["frmOder"]["Details"].value = val;
}
</script>
<body>
<p> <h2> Welcome to Hot Buns </h2> <br> <h3> Ham can we bee'f service? </h3></p>
<p> <h2> Place an order </h2> </p>
<form method="get" name="frmOder">
<select id="slctOrder" onChange="showDetails();">
<!-- I'm trying to call the function showDetails()
but neither onChange here nor onClick in the option tag seem to accomplish that -->
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1"> Last of the Mo-jicama </option>
<option value="2"> Cheesus Is Born Burger </option>
<option value="3"> Beets of Burden Burger </option>
<option value="4"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output name="Details"/>
</form>
</body>
</html>
You can simplify the markup (changed portion here) and the code, adding an event listener.
Markup(revised)
<form method="get" id="frmOder">
<select id="slctOrder">
<option hidden selected="selected" value="0"> please select one of today's specials </option>
<option value="1"> Last of the Mo-jicama </option>
<option value="2"> Cheesus Is Born Burger </option>
<option value="3"> Beets of Burden Burger </option>
<option value="4"> Paranormal Pepper Jack-tivity Burger </option>
</select>
<output id="Details" />
</form>
Code
function showDetails(event) {
console.log(event);
// var x = document.getElementById("slctOrder");
var x = event.srcElement;// same as above but use the event
var val = x.options[x.selectedIndex].text;
// no need for above, just get the text value (assumes single select)
var t = event.srcElement.selectedOptions[0].text;
document.getElementById("Details").value = t;
}
// add event listener to select
var el = document.getElementById("slctOrder");
el.addEventListener("change", showDetails, false);
Note you COULD still use the name to select: (but it returns a collection so [0] needed for first one)
document.getElementsByName("slctOrder")[0];
Sample fiddle to play with:https://jsfiddle.net/MarkSchultheiss/j28cpsg9/

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

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/

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

Dijit events not working in dynamic panes

Can someone tell me why none of the following will work?
EDIT
(Just incase the link goes down this question is about how you can't seem to fire events in a page that is loaded into a dijit pane. This is applicable for Firefox 6.0.2, Crome 12.0.742.100 and Opera 11.00.1156 )
<!-- index.html -->
<script>
dojo.addOnLoad(function() {
dijit.byId("mainSettings").set("href","index2.html");
});
</script>
<body class="claro">
<div id="main" dojoType="dijit.layout.BorderContainer">
<div dojoType="dojox.layout.ContentPane" splitter="false" id="mainSettings" region="center"></div>
</div>
</body>
<!-- index2.html -->
<!-- THIS WORKS!!! -->
<select dojoType="dijit.form.Select">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
<script type="dojo/method" event="onChange">
alert("change");
</script>
</select>
<!-- NONE OF THIS WORKS!!! -->
<select dojoType="dijit.form.Select" onChange="change1">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
</select>
<script type="dojo/method" event="change1">
alert("change1");
</script>
<button dojoType="dijit.form.Button" onClick="change2">
change2
</button>
<script type="dojo/method" event="change2">
alert("change2");
</script>
<script>
dojo.addOnLoad(function() {
dojo.connect(dijit.byId('button2'), 'onClick', function(){
alert("change3");
});
});
</script>
<button dojoType="dijit.form.Button" id="button2">
button2
</button>
EDIT
Dojango code:
#forms.py
type = CharField(widget=Select(choices=VARIABLE_CHOICES,attrs={'onChange':'letterVariableTypeSelectChange'}))
#template
{{ form.type }}
<script>
function letterVariableTypeSelectChange(){
alert("dave");
}
</script>
Try setting the executeScripts and parseOnLoad properties to true on the dojox.layout.ContentPane
<div id="main" dojoType="dijit.layout.BorderContainer">
<div dojoType="dojox.layout.ContentPane" executeScripts="true" parseOnLoad="true" splitter="false" id="mainSettings" region="center"></div>
</div>
There also appears to be a fundamental disparity to how you are using dojo/method.
The <script type="dojo/method"> tags should go inside the elements that they are overriding
Notice how your snippet that works is defined:
<select dojoType="dijit.form.Select">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
<!--Script tag inside widget node, event is the name of the event to override -->
<script type="dojo/method" event="onChange">
alert("change");
</script>
</select>
versus the ones that don't work:
<!--onChange here is specified directly on the widget (which is incorrect), should be in the
<script type="dojo/method" event="OnChange">
-->
<select dojoType="dijit.form.Select" onChange="change1">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
</select>
<!--script tag outside the select. event refers to a nonexistent event for the widget.-->
<script type="dojo/method" event="change1">
alert("change1");
</script>
You get can the list of available events that you can use dojo/method to override at the reference documentation for a given widget.
http://dojotoolkit.org/api/dijit/form/FilteringSelect

Categories