accessing <span> text within a <div> - javascript

My first post, so go easy on me!
I'm very new to programming, and I'm making a browser based application that will track arriving flights (I'm an aircraft mechanic by day) and use the .effect("highlight") to make elements flash when the arrival time is near. This will be displayed on a big monitor in our ready room.
Not all of the code is in it's final stages. Some of it is still set up just to test whether or not functions work, like the pulseRed and pulseYellow functions below. I've only tested this in chrome, and only intend it to run in chrome for now, so no guarantees that it will work properly in other browsers.
Here's my issue...
Each new timer that is created is a new div with a unique ID. Each div contains several span elements that are used to display the info on the monitor and store the data.
If you run this code, the block that is marked # problem area # should alert the value of arrivalHour, and it does! Success!... sort of.The problem is that after the first timer, each time the function fires it jams ALL of the arrivalHour values into one window. So if 3 timers had values of 05, 08, and 12, it would display 050812, and it would do it 3 times due to the window popping up once per timer in the loop. What I'm trying to do is have each window display the info from that ONE span element in the div. I'm assuming I need to index which element of the loop I'm on, but I'm fairly stumped as to where the [z] index should go (if that's even the fix here). Once I can pull single values out of those spans, I can set up the rest of the loops and statements to handle the data and I'm basically done.
WHEW! Long explanation, but I wanted to make sure my question made sense.
$(document).ready(function() {
var i = 01; //variable for iterating ID's for each timer below
$("#startButton").fadeTo("fast",0.5);
$("#startButton").mouseenter(function() {
$("#startButton").fadeTo("slow",1);
});
$("#startButton").mouseleave(function() {
$("#startButton").fadeTo("slow",0.5);
});
// pulse function causes the called object to blink red 3 times.
var pulseRed = function() {
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
$(".timers").effect("highlight", {color: 'red'}).fadeIn();
}
// pulse function to blink the target div yellow - currently pulses ALL div's for testing
var pulseYellow = function() {
$(".timers").effect("highlight").fadeIn();
$(".timers").effect("highlight").fadeIn();
$(".timers").effect("highlight").fadeIn();
}
setInterval(function(){ //set up just for testing purposes
pulseYellow();
pulseRed();
for (var z = 1; z <= ($(".timers").length); z++) {
alert($('div.timers span.arrivalHour').text()); //<---PROBLEM AREA!!!!!
}
},5000);
//time data formatting for proper display
var d = new Date();
var currentHours = function() {
var hourCheck = d.getHours();
if (hourCheck <= 9) {
return("0" + hourCheck);
}
else {
return(hourCheck);
}
};
var currentMinutes = function() {
var minCheck = d.getMinutes();
if (minCheck <= 9) {
return("0" + minCheck);
}
else {
return(minCheck);
}
};
//button to create the new timer and related functions.
$("#startButton").click(function() {
var tailNumber = $("#tail").val();
var borderColor = $("#colorPicker").val();
var alertTime = $("#alert").val();
var arrHour = $("#hour").val();
var arrMinute = $("#minute").val();
var remarks = $("#discrepancy").val();
// example of similar code at http://jsfiddle.net/nick_craver/TTHDQ/
//creates a new div containing all of the user input data, iterates a new ID so that div's can be blinked individually
$("<div />", { "class":"timers", id:"timer"+i})
.append("<span class='tailNumber'>"+tailNumber +' '+"</span><span class='arrivalHour'>"+arrHour+"</span><span>-</span><span class='arrivalMinute'>"+arrMinute+"</span><span class='table'>"+' ' +"</span><span class='remarks' style='margin: 0 auto; text-align: right'>"+remarks+"</span><div class='delete'>DELETE</div></div>")
.appendTo("#main");
$("#timer" + i).css('border', '2px solid ' +borderColor);
i++;
//delete timer DIV's when no longer needed
$(".delete").click(function() {
$(this).closest(".timers").remove();
});
$('#getTail').get(0).reset();
});
});
EDIT: adding HTML
<!DOCTYPE html>
<html>
<head>
<title>Flight Timer</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body id="main">
<div id="menu">
<form id="getTail" action="">
Flight Tracker<br>
<input id="tail" type="text" name="Tail Number" placeholder="Tail #">
<select id="colorPicker">
<option value="Green">Color</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Orange">Orange</option>
</select>
<select id="alert">
<option value="default">Flash...</option>
<option value="1">1 minute prior</option>
<option value="5">5 minutes prior</option>
<option value="10">10 minutes prior</option>
<option value="15">15 minutes prior</option>
</select>
<input id="hour" type="text" name="hour" placeholder="Hour">
<br>
<input id="minute" type="text" name="minute" placeholder="Minute">
<input id="discrepancy" type="text" name="pirep" placeholder="Discrepancy or action">
</form>
<div id="startButton">
Add Timer
</div>
</body>
</html>

If I understand correctly, you want a separate alert for each timer (specified by $('.timers')). If that is the case, you want to switch that for statement to look like this:
$("div.timers").each(function() {
alert($(this).find('span.arrivalHour').text());
});
The reason why you're getting all of the text combined is that $('div.timers span.arrivalHour') works as a global selection - meaning that it will retrieve all of the matching elements in the page. The code I'm proposing iterates through each timer, retrieving the arrival hour for each one.

Related

setting html <select> option to be the default value based on current time

I have made a basic punchclock webpage & MySQL database,
only problem is when people accidently clock in instead of out at end of day or vice versa it leaves alot of gaps.
I need some sort of code that defaults "startfinish" value to "Start" before 10:30 and "End" after 14:30 but still allows the user to change the option if they needed to
note really sure where to start and if i should use javascript or php (php is in a seperate file as the "form action")
heres my current html code that needs the option changed:
<select name="startfinish" id="startend" required>
<option selected="selected" disabled selection>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
any help would be greatly appreciated
thanks,
Danial
If you aren't opposed to PHP you could check the current time and compare it against the times you've specified. This will have to go in the file you're working from though, not your action file.
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
To use this in your select control, you'd echo the variables (shown in shorthand for brevity) in the options. If the date calculations are correct, that option will be selected, otherwise it will remain unchanged. I removed the selection from the placeholder because this setup will ensure Start or End are always selected.
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
The benefit of using PHP in this case is that it runs server-side instead of client-side, so you don't have to worry about the user disabling Javascript and ruining your form design. Though, if you're already depending on jQuery in your application that's probably a non-issue.
You can use the Date object and a bit of jQuery to get the result you're after: http://jsfiddle.net/8cuL0k3h/
$(function() {
// Grab the date object and get hours/minutes
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
// Check if time is before 10:30am
if( hours <= 10 && minutes < 30 ) {
$('#startend').val('Start');
}
// Check if time is after 2:30pm
else if( hours >= 14 && minutes > 30 ) {
$('#startend').val('End');
}
});
I'm assuming the site is statically generated, in which case PHP wont get a bite of this particular apple. Here's a JS only approach.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
initSelectElement();
}
function makeItemSelected(listElem, index)
{
var i, n = listElem.options.length;
for (i=0; i<n; i++)
{
if (index == i)
listElem.options[i].setAttribute('selected','');
else
listElem.options[i].removeAttribute('selected');
}
}
function initSelectElement()
{
var curTime = new Date();
var curHour = curTime.getHours();
var curMin = curTime.getMinutes();
if ((curMin <= 30) && (curHour <= 10))
{
makeItemSelected(byId('startend'), 1);
}
else if ((curMin >= 30) && (curHour >= 2))
{
makeItemSelected(byId('startend'), 2);
}
}
</script>
<style>
</style>
</head>
<body>
<select name="startfinish" id="startend" required>
<option selected disabled>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
</select>
</body>
</html>

Javascript date returning wrong value

I'm new to Java script and am literally tearing my hair out here. I want a simple date calculator, which updates itself when ever a user changes either a date box or a duration from a drop down menu. I've looked at several ways to do it, and have found one that appears to be quite simple as per below.
It works perfectly if I have 'var interval = 4;' as a fixed value (interval is the duration after the user inputted date). However if I change that line to 'var interval = number;' (the duration input from the select menu), it gives me all kinds of crazy dates(dates which are significantly after the interval), and I don't know why
Is anyone able to help? Thanks in advance
<script type="text/javascript">
function setExpDate(){
var formDate = document.getElementById('startDate').value;
var number = document.getElementById('days').value;
// set number of days to add
var interval = 4;
var startDate = new Date(Date.parse(formDate));
var expDate = startDate;
expDate.setDate(startDate.getDate() + interval);
document.getElementById('total').innerHTML = expDate;
document.getElementById('daysdays').innerHTML = interval;
};
</script>
</head>
<body>
<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">
<select name="days" id="days" onchange="setExpDate(this.value)">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
<div id="total"></div> <br/><div id="daysdays"></div>
</body>
</html>
The values of form fields are always strings. You have to force them to be numbers:
var number = +document.getElementById('days').value;
or
var number = parseInt( document.getElementById('days').value, 10 );
(Either one will work; it's up to you.)
If you don't perform that conversion, then the addition step here:
expDate.setDate(startDate.getDate() + interval);
will be carried out as string concatenation.

Javascript roller on radio button's onclick

I have four radio buttons to select a country. When a user clicks on any of the radio button, I use Ajax to get the states of that country. In order to show the end user that we are processing the data, I use a roller image(gif).
When any user clicks on of country radio, in the method (onclick event of radio), loadStates(), I enable the roller image by setting it's display property to 'inline'.
Then send a request to the server using Ajax(for showing a working example, I have removed that code and have inserted a "sleep" instead, just to show that it takes some time).
Right after getting the result, I put back the display property to 'none'.
However it is not working. Can anybody tell me how to fix it ?
PS : I dont want to use jQuery for the time being, only Javascript please.
<html>
<head>
<script type="text/javascript">
window.onload = init;
function init() {
countryFunctions();
}//init
function countryFunctions() {
var inputElems = document.forms[0].getElementsByTagName('input');
for (var i = 0, j = inputElems.length; i < j; i++) {
var elemName = inputElems[i].name;
if ( typeof elemName != 'undefined' && elemName === 'country' ) {
//inputElems[i].onmouseup = showRoller;
inputElems[i].onclick = loadStates;
}//if
}//for
return;
}
function loadStates() {
var action = 'get_states';
document.getElementById("fSpinner").style.display = "inline";
//alert("hi........");
var result = doLoad(action);
document.getElementById("countryStates").innerHTML = result;
document.getElementById("fSpinner").style.display = "none";
}
function doLoad(action) {//A dummy function just show what it returns (actually it is Ajax)
sleep(7000);
var value = "\
<p>\
Which state of the country would you like to go?\
</p>\
<select name=\"state\">\
<option value=\"1362\">Delhi</option>\
<option value=\"481\">Kerala</option>\
<option value=\"666\">Punjab</option>\
<option value=\"668\">Kashmir</option>\
</select>";
return(value);
}
function sleep(ms) {
var unixtime_ms = new Date().getTime();
while(new Date().getTime() < unixtime_ms + ms) {}
}
</script>
<style type="text/css">
#fSpinner { display:none; }
</style>
</head>
<body>
<form>
<p>What country do you belong to?</p>
<p>
<input name="country" value="in" type="radio"> India
<input name="country" value="au" type="radio"> Australia
<input name="country" value="nz" type="radio"> New Zealand
<input name="country" value="my" type="radio"> Malaysia
<span id="fSpinner">
<img style="vertical-align:text-bottom;" src="http://107.20.148.146/shak/images/roller.gif">
</span>
</p>
<div id="countryStates"></div>
</form>
</body>
</html>
The sleep function "blocks" the browser, the page is not refreshed until the function returns.
To simulate an asynchronous process, like an AJAX call, use setTimeout instead:
function loadStates() {
var action = 'get_states';
document.getElementById("fSpinner").style.display = "inline";
setTimeout( function() {
var value = "\
<p>\
Which state of the country would you like to go?\
</p>\
<select name=\"state\">\
<option value=\"1362\">Delhi</option>\
<option value=\"481\">Kerala</option>\
<option value=\"666\">Punjab</option>\
<option value=\"668\">Kashmir</option>\
</select>";
document.getElementById("countryStates").innerHTML = value;
document.getElementById("fSpinner").style.display = "none";
}, 7000) ;
}

HTML/Javascript issue

I'm having an issue writing some code for a website. It's written in HTML/Javascript. I've managed to write a large chunk of code that seems to work alright, but this issue is now I can't seem to have multiple line strings within Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Multiline test</title>
</head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<p id="selection"></p>
<script type="text/javascript">
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now, get a reference to the <p> where we'll show the result:
var selectionP = document.getElementById('selection');
// This Array will hold the labels. label[0] will be 'Text1', labels[1] 'Text2', etc.
var labels = [
"Multiline test \n Multiline test",
"Text2",
"Text3"
];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
selectionP.innerHTML = text;
};
</script>
</body>
This is the updated code. Now all I need is a multiline work around.
This
document.form001.choice
"Text" + choice + "Text"}
Doesn't make any sense, does it? You need to do something like
var choice = document.form001.choice
"Text" + choice + "Text"}
By the way to follow the flow of your JavaScript program you should use Google Chrome's JavaScript Console. It really help understanding what's going on.
i noticed you wrote:
Now what I believe to be happening is that when it's not calling the
Javascript function as it is supposed to.
Inside your function either:
write:
console.log('this function is being executed');
// this will make a line show up in the chrome document inspector / firebug console (just google those)
or
alert('This function is being executed!')
That should help with troubleshooting a lot.
Note: I've put up a working example of this code here: http://jsfiddle.net/F87tJ/
Let's take the following HTML:
<html>
<head></head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<script type="text/javascript">
// JavaScript goes here
</script>
</body>
</html>
Now, I'm going to assume you want to respond to the user changing the selection of the dropdown box. This is pretty easy in JavaScript. Just get a reference to the <select> element and attach an event handler to it. An event handler is just a function that will be called when the given event occurs. In this case:
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
// Do something
};
With me so far? Good.
Now, you wanted to show 'Text1', 'Text2' or 'Text3', based on the selection, right? So, we have to know which <option> is selected. That, too, is easy:
var optionIndex = choice.selectedIndex;
This will just give you a zero-based index of the selected <option>. So, if the first option is selected, optionIndex will have value 0.
To show some text based on the selection, we need some strings. Since we're dealing with a collection here, let's put it in an array:
var labels = [
"Text1",
"Text2",
"Text3"
];
Arrays in JavaScript are also zero-based, so label[0] will be 'Text1', labels[1] 'Text2', etc.
If we bring it all together, we get something like this:
var choice = document.getElementsByName('choice')[0];
var labels = [
"Text1",
"Text2",
"Text3"
];
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
alert(text);
};
I hope this helps. :-)
I rewrote problem areas in your code, and added comments to show what was changed.
<!DOCTYPE html> <!-- HTML pages should have a DOCTYPE header, as well as html, head, and body tags. -->
<html>
<head>
<title></title>
</head>
<body>
Text
Text
Text
Text
<br/>
<br/>
Select variable value below:
<br/>
-
<div>
<form name="form001">
<select name="choice">
<!-- <size=3> Don't think there's a such thing as a size tag -->
<option value=1 selected="selected">1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<script type="text/javascript">
function js001(){ //This was missing paranthesis
var v1 = "Text1"
var v2 = "Text2"
var v3 = "Text3"
var choice = document.form001.choice; //choice wasn't defined
alert("Text" + choice + "Text");
}
</script>
<script type="text/javascript">
//js001();
</script> <!-- The S needed to be lowercase here -->
<div class="pagetext">
<br/>
<br/>
Text
<br/>
<br/>
Text
<div>
</body>
</html>
Here's another version which I think will do what you need.
When the user selects an item from the dropdown, it displays a text string below the dropdown that corresponds to the item that the user selected.
<html>
<body>
<form name="form001">
<!-- when the user changes the selected item in this dropdown, -->
<!-- the JavaScript function "js001()" will get called -->
<select name="choice" onchange="js001()">
<option value=0 selected="selected">1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
</form>
<!-- This is the div in which the selected item's related text will be shown -->
<div id="selectedStuff"/>
<script type="text/javascript">
function js001()
{
// Rather than use separate variables for each value,
// it is simpler if we store them in an array
var values = ["Text1", "Text2", "Text3"];
// The value of the selected item in the dropdown maps to the index in the values
// array for the text we want to show
var valueIndex = document.form001.choice.value;
var text = "Text" + values[valueIndex] + "Text"
document.getElementById("selectedStuff").innerHTML = text;
}
// When the page loads it makes sense to call the js001() function,
// so that the text for initially-selected dropdown value gets shown
js001();
</script>
</body>
</html>

Show/Hide Div with JavaScript based on Select from Triple Dropdown

Gang -
This is my first time posting. I'm a JavaScript noob - I think I've figured out what direction to take - just not sure how to get there.
I have a triple drop down select menu. I want the third(final) selection to reveal a hidden div. Am I on the right track by thinking I need to use a combination of onchange, getElementById and if statements?
The javascript code for the dropdown is Philip M's Cut & Paste Triple Combo box from JavaScriptKit.com. That work's beautifully. I won't insert my exact code as the category list is significantly longer.
var categories = [];
categories["startList"] = ["Wearing Apparel","Books"]
categories["Wearing Apparel"] = ["Men","Women","Children"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
categories["Men"] = ["Shirts","Ties","Belts","Hats"];
categories["Women"] = ["Blouses","Skirts","Scarves", "Hats"];
categories["Children"] = ["Shorts", "Socks", "Coats", "Nightwear"];
categories["Biography"] = ["Contemporay","Historical","Other"];
categories["Fiction"] = ["Science Fiction","Romance", "Thrillers", "Crime"];
categories["Nonfiction"] = ["How-To","Travel","Cookbooks", "Old Churches"];
var nLists = 3; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(L3, L2, L1) {
alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3);
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
My HTML is:
<div id="menuSearch">
<form name="tripleplay" action="">
<p><select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>-- Topic of Interest --</option>
</select></p>
<p><select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>-- Geographic Area --</option>
</select></p>
<select id="info"name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)">
<option selected >-- Information Type --</option>
</select>
</form>
</div>
the divs to show/hide are:
<div id="modelingCV">list of publications</div>
<div id="groundwaterCV">list of publications</div>
<div id="subsidenceCV">list of publications</div>
<div id="managementCV">list of publications</div>
<div id="qualityCV">list of publications</div>
<div id="wildlifeCV">list of publications</div>
Is replacing the getValue in the onchange in the final form select with getElementByID the best approach? And replace the getValue in the javascript function with some type of if statement to specify the values? I am guessing I need to hide the divs with javascript vs CSS? Am I completely off base all around?
Oy. Definitely bit off more than I can chew on this one. Any guidance would be appreciated. Thanks for reading!

Categories