Setting rules on a form - javascript

So, I need a function to check if the rules I've made apply to the options I have in my form.
The first box is a name box and it needs to have at least three letters and contain at least one whitespace to pass.
The other box is age, it needs to have a number between 1 and 125, I can do that on my own but I'm thinking there might be a nice way to set all of the rules at once so I thought I'd include it.
The third option is a set of three radio buttons of which one has to be selected and the fourth box is an info box that should consist of a text with at least 30 letters. These rules should be checked on the press of a button, this is how far I've gotten on my own:
var sendButton = $("button:first").addClass("sendButton");
var age = document.getElementsByName('age')[0].value;
sendButton.click(function(){
var infoName = document.getElementsByName('infoName')[0].value;
if (infoName.length<3){
console.log("Your name must consist of at least three letters and contain a whitespace");
};
}
});
<section class="column">
<h2>Contact us</h2>
<form action="#">
<fieldset>
<legend>Form</legend>
<div class="textinput">
<label for="infoName">Ditt namn:</label>
<input type="text" name="infoName" placeholder="ex. John Doe">
</div>
<div class="textinput">
<label for="infoName">Din ålder:</label>
<input type="text" name="age" placeholder="ex. 25">
</div>
<div class="radioSelection">
<label>Choose your favorite</label>
<input type="radio" name="favorite" id="html" value="html">
<label for="html">HTML</label>
<input type="radio" name="favorite" id="js" value="js">
<label for="js">JavaScript</label>
<input type="radio" name="favorite" id="css" value="css">
<label for="css">CSS</label>
</div>
<div class="textareainput">
<label for="info">Info about you:</label>
<textarea placeholder="Type something about yourself, this area must contain 30 letters or more"></textarea>
</div>
<div class="action">
<button>Send</button>
</div>

function validateForm(){
var infoName = document.getElementsByName('infoName')[0].value;
var age= document.getElementsByName('age')[0].value;
var favourites = document.getElementsByName('favorite');
var problems = 0;
if(infoName.length < 3){
// Failed length validation
problems++;
}
var spaceIndex = infoName.indexOf(' ');
if(spaceIndex === -1){
// Name does not contain a space.
problems++;
}
else if(spaceIndex === 0){
// Name begins with space
problems++;
}
else if(spaceIndex === infoName.length - 1){
// Space is last character.
problems++;
}
var hasCheck = false;
for(var i = 0; i < favourites.length; i++){
if(favourites[i].checked){
hasCheck = true;
break;
}
}
if(!hasCheck){
// No radio button has been checked.
problems++;
}
var ageNum = parseInt(age);
if(isNaN(ageNum)) {
// Age is not a number
problems++;
}
else if(ageNum < 1 || ageNum > 125){
// Age is not within boundaries
problems++;
}
/// etc etc, for all your validations.
return problems === 0;
}
At the end of the validation, if any problems are detected, the form will not be submitted (because problems === 0 is false). Also the number validation I've put in there is not very robust. Check out this question which goes into detail about number validation.
The validation method should be called on submission of the form, rather than when the button is clicked
$('form').submit(function(e){
var valid = validateForm();
if(!valid){
e.preventDefault();
return false;
}
});

Related

If statement executing both if and else

I'm building a web app that converts Galloons to Liters and vise versa. Got one textbox to enter gallon/litters, the user selects on a radio button what they want to convert too. Now the problem arises when validating the input:
for liters it must be Greater than 0 but less than 1000 for the gallons it must be greater than 0 but less than 4000. So if I've selected liters it must validate only liters but both validations are coming up. Here's my code:
Form:
<body onload="setup()">
<div data-role="page">
<div style="padding: 20px;">
<div data-role="fieldcontain">
<input type="number" id="temperature" name="temperature">
<label id="label">Gallons</label>
</div>
<fieldset data-role="controlgroup">
<legend>Convert to:</legend>
<input type="radio" name="units" id="Gallons" value="Gallons"
onclick="setUnits('Liters')">
<label for="Gallons">Gallons</label>
<input type="radio" name="units" id="Liters" value="Liters"
checked="checked" onclick="setUnits('Gallons')">
<label for="Liters">Liters</label>
</fieldset>
<input type="button" onclick="convert()" value="Convert">
<p id="answer"></p>
</div>
</div>
</body>
JavaScript:
function setup()
{
var cType;
setUnits("Gallons");
cType = "Gallons";
document.getElementById("Gallons").onclick =
function () {
cType="";
cType="Liters";
setUnits("Liters");
CheckInput(cType);
};
document.getElementById("Liters").onclick =
function () {
cType="";
cType="Gallons";
setUnits("Gallons");
CheckInput(cType);
};
CheckInput(cType);
}
function setUnits(unit) {
var label = document.getElementById("label");
label.innerHTML = unit;
}
function CheckInput(cType) {
var CheckInputcType= cType;
var angleInput = document.getElementById("temperature");
if(CheckInputcType.localeCompare("Gallons")==0)
{
angleInput.addEventListener("blur",validateG);
}
else(CheckInputcType.localeCompare("Liters")==0)
{
angleInput.addEventListener("blur",validateL);
}
}
function validateL(){
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 1000 || angleInput.value<=0)
{
alert('Liters must be between 0 and 1000');
angleInput.value = "";
}
}
function validateG() {
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 4000 || angleInput.value<=0)
{
alert('Gallons must be between 0 and 4000');
angleInput.value = "";
}
}
You have a problem with your method CheckInput(cType), because every time you click on Galons or liters radio button you are adding a new listener event on temperature input.
Just simply create one listener and verify radio state on that validator method.

How do I create multiple inputs after a button is clicked (Javascript)

I am new to javascript and I'm trying to make a web app that tests users and also lets them make tests. I'm currently focusing on the making-tests part of the web app. When the user enters the name of the test and the number of questions they want in the test, they click the button and then a javascript function should be called that has a loop that repeats for the number that they entered. In the loop a 'question' and an 'answer' input should be created. Here is the html for this feature:
<h3>Enter the name of the test you want to make:</h3><br>
<input type="text" name="testname" id="testnameID">
<h3>Enter the number of questions you want the test to have:</h3><br>
<input type="text" name="numofquestions" id="numID">
<button type="button" onclick="createNewElement()">Let's make it!</button>
And this is the function 'createNewElement' in javascript:
function createNewElement() {
var testname = document.getElementById("testnameID").value;
var numquestions = document.getElementById("numID").value;
var numofquestions = parseInt(numquestions)
for ( var i = 0; i < numofquestions; i++ ) {
// This will loop the amount of times as the user input
var questioninput = document.createElement("input");
questioninput.type = 'text';
questioninput.id = 'question' + i;
var answerinput = document.createElement("input");
answerinput.type = 'text';
answerinput.id = 'answer' +i;
}
}
From what I've read online I think this should work but I must have made some errors in what I've written. Any advice on how to do this successfully would be really appreciated.
You need the Template literals method to append the question(your input fields to the DOM)
Also, you need some element in your HTML, that will have all the multiple input fields.
Example:
<div id="question-paper"></div>
The above div will be your container where you can append n -number of fields you want.
function createNewElement() {
var testname = document.getElementById("testnameID").value;
var numquestions = document.getElementById("numID").value;
var numofquestions = parseInt(numquestions)
var questionAnswerHTML = "";
for (var i = 0; i < numofquestions; i++) {
questionAnswerHTML += `
<label for="question${i}">
Question: ${i+1}
</label>
<br />
<input type="text"
id="question${i}"
placeholder="Type Question ${i+1} Here." />
<br /><br />
<label for="answer${i}">
Answer: ${i+1}
</label>
<br />
<input type="text"
id="answer${i}"
placeholder="Type Answer ${i+1} Here." />
<br /><br />
`;
}
document.getElementById("question-paper").innerHTML = questionAnswerHTML;
}
<h3>Enter the name of the test you want to make:</h3>
<input type="text" name="testname" id="testnameID">
<h3>Enter the number of questions you want the test to have:</h3>
<input type="text" name="numofquestions" id="numID"> <button type="button" onclick="createNewElement()">Let's make it!</button>
<hr>
<div id="question-paper"> </div>

Issues with if-statement adding players with `is-inactive` class to input

Problem
The maximum number of players for each position is:
2 out of 4 goalies
6 out of 15 defencemen
12 out of 31 forwards
I've gotten to the point where I'll click on a hockey player and that name gets added to a input field in a form, but if you already have two goalies selected, ie has a class of is-active and then click on one of the other two unselected players with the default is-inactive class, that name will still be added into an input when there should only be two goalies max. And unfortunately, this is also the case with the defencemen and the forwards too.
Goal
When starredGoaltenders === maxGoaltenders or starredDefencemen === maxDefencemen or starredForwards === maxFowards the names of players that do not have not been selected of that specific position and do not have an is-active class should not be added to any input in the form.
scripts.js
function countSelected() {
$(".player").on("click", function(){
// Checks if the maximum number of players have been selected
// If so, return false and then do nothing
// If not, the class will toggle from `is-inactive` to `is-active`
if ($(this).find(".picked.is-inactive.full").length > 0) return false;
$(this).find(".picked").toggleClass("is-inactive is-active");
$(".player").removeClass("not-picked");
$(".player").not(":has(.is-active)").addClass("not-picked");
// Count the number of players with stars
var starredGoaltenders = $(".player--goalie").find(".picked.is-active").length;
var starredDefencemen = $(".player--defencemen").find(".picked.is-active").length;
var starredForwards = $(".player--forward").find(".picked.is-active").length;
console.log(starredGoaltenders, starredDefencemen, starredForwards);
// The number of starred players for each position cannot exceed the following numbers
var maxGoaltenders = 2;
var maxDefencemen = 6;
var maxFowards = 12;
// If the number of starred players hits its max, a class of `is-completed` is adding to the corresponding checkmark to indicate that the task has been completed
if (starredGoaltenders === maxGoaltenders) {
$(".checkmark--goalie").addClass("is-completed");
$(".player--goalie").find(".picked").addClass("full");
} else {
$(".checkmark--goalie").removeClass("is-completed");
$(".player--goalie").find(".picked.is-inactive").removeClass('full');
}
if (starredDefencemen === maxDefencemen) {
$(".checkmark--defencemen").addClass("is-completed");
$(".player--defencemen").find(".picked").addClass("full");
} else {
$(".checkmark--defencemen").removeClass("is-completed");
$(".player--defencemen").find(".picked.is-inactive").removeClass('full');
}
if (starredForwards === maxFowards) {
$(".checkmark--forward").addClass("is-completed");
$(".player--forward").find(".picked").addClass("full");
} else {
$(".checkmark--forward").removeClass("is-completed");
$(".player--forward").find(".picked.is-inactive").removeClass('full');
}
// If all the conditions are met show the submit vote button
if (starredGoaltenders === maxGoaltenders && starredDefencemen === maxDefencemen && starredForwards === maxFowards) {
$(".btn--submit").show();
$(".btn--submit").addClass("slideLeft");
} else{
$(".btn--submit").hide();
$(".btn--submit").removeClass("slideLeft");
}
});
} countSelected();
// Every time a player is clicked, note the name of the player
$(".player").on("click", function(){
var playerNames = [];
$("input:text").each(function(i, t) { playerNames.push(t.value) });
if ($(this).find("picked.is-active")) {
var playerName = $(this).find(".player__name").html();
var index = playerNames.indexOf(playerName);
if (index == -1) // Add player
$("input:text:eq(" + playerNames.indexOf("") + ")").val(playerName);
else // Remove player
$("input:text:eq(" + index + ")").val("");
} else {
$("input").val("");
}
});
index.html - Snippet includes form and one out of the 60 available players to be clicked on
<form id="form">
<input type="text" name="p1" id="p1">
<input type="text" name="p2" id="p2">
<input type="text" name="p3" id="p3">
<input type="text" name="p4" id="p4">
<input type="text" name="p5" id="p5">
<input type="text" name="p6" id="p6">
<input type="text" name="p7" id="p7">
<input type="text" name="p8" id="p8">
<input type="text" name="p9" id="p9">
<input type="text" name="p10" id="p10">
<input type="text" name="p11" id="p11">
<input type="text" name="p12" id="p12">
<input type="text" name="p13" id="p13">
<input type="text" name="p14" id="p14">
<input type="text" name="p15" id="p15">
<input type="text" name="p16" id="p16">
<input type="text" name="p17" id="p17">
<input type="text" name="p18" id="p18">
<input type="text" name="p19" id="p19">
<input type="text" name="p20" id="p20">
<button class="btn btn--submit" type="submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>
</form>
<div class="player player--forward year--2000 year--2010">
<div class="tooltip">
<p class="tooltip__name">Mark Stone</p>
<p class="tooltip__hometown"><span>Hometown:</span> Winnipeg, Man.</p>
<p class="tooltip__years"><span>Years Played:</span> 2008-2012</p>
<div class="tooltip__stats--inline">
<div class="stats__group stats--games">
<p class="stats__header">GP</p>
<p class="stats__number stats__number--games">232</p>
</div>
<div class="stats__group stats--goals">
<p class="stats__header">G</p>
<p class="stats__number stats__number--goals">106</p>
</div>
<div class="stats__group stats--assists">
<p class="stats__header">A</p>
<p class="stats__number stats__number--assists">190</p>
</div>
<div class="stats__group stats--points">
<p class="stats__header">Pts</p>
<p class="stats__number stats__number--points">296</p>
</div>
<div class="stats__group stats--penalties">
<p class="stats__header">Pim</p>
<p class="stats__number stats__number--penalties">102</p>
</div>
</div>
</div>
<div class="player__headshot player--mstone">
<div class="picked is-inactive"><i class="fa fa-star" aria-hidden="true"></i></div>
</div>
<p class="player__name">Mark Stone</p>
<p class="player__position">Forward</p>
</div>
Probably, the easiest way to approach this problem is to repopulate all your inputs every time someone clicks on a player, rather than trying to populate each input once. This means you can keep your application state in a simple, easily understood data structure that is independent of your DOM/UI, rather than having to consult the DOM each time something new happens.
This is how I would probably write it.
var players = [
{name: 'Ovechkin', type: 'F'},
{name: 'Dubnyk', type: 'G'}
// your complete player list goes here
],
selectedPlayers: []; // these are the players the user has chosen
var getCurrentPlayerCount = function (playerType) {
// return the number of players currently selected of one type
return selectedPlayers.reduce(function (count, player) {
if (player.type === playerType) return count + 1;
return count;
}, 0);
}
var selectPlayer = function (player) {
// You call this when someone clicks on a player
var currentForwardCount = getCurrentPlayerCount('F')
currentDefenceCount = getCurrentPlayerCount('D'),
currentGoalieCount = getCurrentPlayerCount('G');
// Do nothing (or show a UI message) if someone goes over their
// player-type limit
if (player.type === 'F' && currentForwardCount > 12) return;
if (player.type === 'D' && currentDefenceCount > 6) return;
if (player.type === 'G' && currentGoalieCount > 2) return;
// If you get here, it means the player can be added, so add
// it to the user's list
selectedPlayers.push(player);
updateUI();
}
I'm not including updateUI here. You can work that out on your own.
If you need to support IE 8 or any other browser that does not support Array.prototype.reduce, you will need to do getCurrentPlayerCount differently.

Need to send data to server via javascript in json format [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am having trouble posting my data from a form to the server but must be in json format and using ajax. How do I do this while using javascript & cannot use Jquery. Here my questions...
Also Thanks in Advance!
How do I convert it and send it to the server with handling HTTP 200 success and using ajax?
On return of a JSON
object with the status encoded like so: {"status":"---"}, where "---" is either "success" or "error".
If the response status is success, a thank you message should be
displayed.
If the response status is error, the page should display a general
warning such as 'request could not be completed'.
HTML
Contact Me
<form id="contactus" action="http://wirehoer.net" method="post">
<fieldset>
<!-- Contact Name
-->
<label for="name">Name:</label>
<input name="name" id="name" type="text" pattern="\b[-'a-zA-Z]+,?\s[-'a-zA-Z]{0,19}\b" autofocus required>
<span id="name-error" class="error">Please enter first & last name</span>
<!-- Email
-->
<label for="email">Email:</label>
<input name="email" id="email" type="email" pattern="^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$" required>
<span id="email-error" class="error">Please enter email address</span>
<!-- Phone
-->
<label for="phone">Phone:</label>
<input name="phone" id="phone" type="tel" pattern="\d{10}" required>
<span id="phone-error" class="error">Phone number must only contain numbers</span>
<!-- Status - Client | Partner | Vendor
-->
<label for="status">Status:
<select name="status" id="status">
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<!-- Subscribe
-->
<label for="subscribe">
<input name="newsletter" id="subscribe" type="checkbox" value="on" checked>
Send me your newsletter</label>
<!-- Support - Sales | Support
-->
<label class="needs" for="select_sales">
<input id="select_sales" name="slsSelect" type="radio" value="sales" checked>Sales
</label>
<label class="needs" for="select_support">
<input id="select_support" name="slsSelect" type="radio" value="support">Support
</label>
<!-- Description
-->
<label for="details">Message:</label>
<textarea name="message" id="details" rows="10" cols="30"></textarea>
<span id="details-error" class="error">Please describe what your request is</span>
</fieldset>
<fieldset>
<button id= "send" type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<!-- javascript validation
-->
<script type="text/javascript" src="contactform_Lab11.js"></script>
</body>
</html>
Javascript
> //This will get the data of the fields
> document.getElementById('send').onclick=function(evt) {
>
> var errors = false; //Gets all the inputs from contact form var
> myNodeList = document.querySelectorAll('input, textarea, select');
>
> //Declar the vars //var i, val; // empty Array
>
> //Start of loop for (i = 0; i < myNodeList.length; i++) {
> // Get element
> val = myNodeList[i];
>
> //Get pattern attribute of regEx
> regEx = new RegExp(val.getAttribute("pattern"));
>
> //Get Error message
> err = document.getElementById(val.id+"-error")
>
> //By default, set the class to error, which hides the error message
> err.className="error";
>
> //Test value "val" again the regEx
> if(!regEx.test(val.value)){
> //input fails and does not pass regEx test, set .display class
> err.className+=" display";
>
> errors = true;
> } } evt.preventDefault(); if(errors ===false){
> document.getElementById("contactus").submit(); } };
You need to set all the data you need in an object, and send it as a JSON string in an AJAX request.
document.getElementById('send').onclick = function (evt) {
var errors = false; //Gets all the inputs from contact form var
myNodeList = document.querySelectorAll('input, textarea, select');
var data = {};
//Declar the vars //var i, val; // empty Array
//Start of loop
for (i = 0; i < myNodeList.length; i++) {
// Get element
val = myNodeList[i].value;
data[myNodeList[i].id] = val;
//Get pattern attribute of regEx
regEx = new RegExp(val.getAttribute("pattern"));
//Get Error message
err = document.getElementById(val.id + "-error")
//By default, set the class to error, which hides the error message
err.className = "error";
//Test value "val" again the regEx
if (!regEx.test(val.value)) {
//input fails and does not pass regEx test, set .display class
err.className += " display";
errors = true;
}
}
evt.preventDefault();
if (errors === false) {
var req = new XMLHttpRequest();
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.open('POST', 'http://wirehopper.net/ajax-submit.php');
req.onload = function () {
if(req.status == 200)
alert(req.response);
}
//TODO: implement error handling
req.send(JSON.stringify(data));
};
}

Javascript to Grab the Selected Value from a list of Form Radio Options OR text field, whichever is used, and output to text?

I'm new to Stack and this is my first question, but I did search and wasn't able to find anything that was specifically what I am trying to accomplish. I'm all for learning, so any reference material that would help me better understand how to approach this would be appreciated, but if someone wants to provide some example code I wouldn't mind that either :p
OK, so the scenario is this. I am writing a "Note Creator" that will generate automatic client notes based on some fields I enter into a form. I've already scripting getting the values from text fields, but I have one field that I want to be a combination of a radio option OR text field, and the java needs to grab whichever one was used and the proper value. Any help is appreciated, below is my code:
<script type="text/javascript">
function getNotes() {
//Grab Variables
spokeTo = document.thisForm.spokeWith.value;
problemItem = document.thisForm.problemWith.value;
resolvedBy = document.thisForm.resolvedWith.value;
thisTech = document.thisForm.techName.value;
fSpace = "... "
//Read in the location information and prep the output container
outputValue = "";
{
//Test if things are blank
if (spokeTo == "") { alert('Please Enter the Name of the Person.'); }
else if (problemItem == "") { alert('Please Select the Problem.'); }
else if (resolvedBy == "") { alert('Please Type Your Resolution.'); }
else {
//The loop that puts the output together
outputValue += "Spoke With: " + spokeTo + "\n\n" + "Called About: " + problemItem + "\n\n" + "Resolution: " + resolvedBy +fSpace + thisTech;
}
//output to the user
document.thisForm.outputArea.value = outputValue;
}
}
</script>
<form name="thisForm">
<p>
1. Spoke With: <input type="text" id="spokeWith" class="input" name="spokeWith">
</p>
<p>
2. Called About:
Hardware <input type="radio" id="problemWith" class="input" name="problemWith" value="Hardware">
Software <input type="radio" id="problemWith" class="input" name="problemWith" value="Software">
<input type="text" id="problemWith" class="input" name="problemWith"><br>
</p>
<p>
3. Resolved By:<br /><br />
<textarea name="resolvedWith" id="resolvedWith"></textarea>
</p>
<p>
4. Your Name:<br>
<input type="text" id="techName" class="input" name="techName" /><br>
</p>
<p>
<input type="button" class="button" value="Make My Notes!" onClick="javascript:getNotes();" />
<input type="reset" class="button" value="Start Over" />
</p>
<br><br>
<textarea name="outputArea" id="outputArea"></textarea>
<p class="finishMessage" id="finishMessage" name="finishMessage"></p>
</form>
I am referring specifically to The Step 2 section of the form where it has radio options and a text field with the same IDs and names. I know IDs are only supposed to be used once per page so this would probably change but I'm open to any suggestion/assistance. I'm moderate with Javascript, still in the learning phases.
Thanks again!
---------------
ROUND 2
---------------
Here is my revised code after taking the suggestion of the provided answer. I added a bunch of alerts to kind of let me know along the way which parts of the script I'm managing to hit, and I can't get anything past the first alert to trigger, and can't get any output at all anymore. What am I missing?
<script type="text/javascript">
function getNotes() {
alert('You\'ve hit the function. Congratulations - you didn\'t break the whole damn thing.');
//Grab Variables
var spokeTo = document.thisForm.spokeWith.value;
var resolvedBy = document.thisForm.resolvedWith.value;
var thisTech = document.thisForm.techName.value;
var fSpace = "… ";
//Grab if radio else text
var inputVal1 = document.getElementByClass('problemRadio').value;
var inputVal2 = document.getElementByClass('problemWith').value;
alert('You made it! Almost there.');
// If Input Value 1 is not Null, Show Radio Value. Else, show Text Value
var problemOutput;
if (inputVal1.length > 0) {
problemOutput = inputVal1;
alert('I found value 1!');
}
else {
problemOutput = inputVal2;
alert('I found value 2!');
}
//Read in the location information and prep the output container
outputValue = "";
//Test if things are blank
if (spokeTo == "") { alert('Please Enter the Name of the Person.'); }
else {
alert('We Made it to Else to parse outputValue');
//The loop that puts the output together
outputValue += "Spoke With: " + spokeTo + "\n\n" + "Called About: " + problemOutput + "\n\n" + "Resolution: " + resolvedBy +fSpace + thisTech;
}
//output to the user
document.thisForm.outputArea.value = outputValue;
}
</script>
<form name="thisForm">
<p>1. Spoke With: <input type="text" id="spokeWith" class="input" name="spokeWith"></p>
<p>2. Called About:
Hardware <input type="radio" id="problemRadio" class="problemRadio" name="problemRadio" value="Hardware">
Software <input type="radio" id="problemRadio" class="problemRadio" name="problemRadio" value="Software">
<input type="text" id="problemWith" class="problemWith" name="problemWith"><br>
</p>
<p>3. Resolved By:<br /><br />
<textarea name="resolvedWith" id="resolvedWith"></textarea>
</p>
<p>4. Your Name:<br>
<input type="text" id="techName" class="input" name="techName" /><br>
</p>
<p>
<input type="button" class="button" value="Make My Notes!" onClick="javascript:getNotes();" />
<input type="reset" class="button" value="Start Over" />
</p>
<br><br>
<textarea name="outputArea" id="outputArea"></textarea>
<p class="finishMessage" id="finishMessage" name="finishMessage"></p>
</form>
sorry about that, I don't know the best way to get code in here yet. Always ends up messy looking ( till I figure it out )
Few things I spotted in your update;
1) getElementbyId is best ( it wasn't getting past your first lines)
2) duplicate IDs on the radio buttons
3) We Needed to 'check' which of the radio buttons was checked
4) always handy to alert the variables ( I've added some in to show )
I gave this code below a rough test and it looks to be along the lines ..
see comments added in your code below ..
<script type="text/javascript">
function getNotes() {
//Grab Variables
var spokeTo = document.getElementById('spokeWith').value;
var resolvedBy = document.getElementById('resolvedWith').value;
var thisTech = document.getElementById('techName').value;
var fSpace = "… ";
alert("spokeTo:" + spokeTo
+" , resolvedBy: " +resolvedBy+", thisTech: "+thisTech);
//Grab if radio else text
var problemWith = document.getElementById('problemWith').value;
alert("problemWith: "+problemWith);
/* set a default value */
var problemOutput="other";
/* if they added no notes */
if((problemWith=="") || ( problemWith==null)) {
/* check which radio is selected if any */
if(document.getElementById('problemHardware').checked) {
problemOutput = document.getElementById('problemHardware').value;
}
if(document.getElementById('problemSoftware').checked) {
problemOutput = document.getElementById('problemSoftware').value;
}
} else {
problemOutput=problemWith;
}
alert("problem output is: "+problemOutput);
alert('You made it! Almost there.');
//Read in the location information and prep the output container
outputValue = "";
//Test if things are blank
if (spokeTo == "") { alert('Please Enter the Name of the Person.'); }
else {
alert('We Made it to Else to parse outputValue');
/* The loop that puts the output together */
outputValue += "Spoke With: "
+ spokeTo + "\n\n"
+ "Called About: "
+ problemOutput + "\n\n"
+ "Resolution: " + resolvedBy +fSpace + thisTech;
}
//output to the user
document.thisForm.outputArea.value = outputValue;
}
</script>
<form name="thisForm">
<p>1. Spoke With: <input type="text" id="spokeWith" class="input" name="spokeWith"> </p>
<p>2. Called About:
Hardware <input type="radio" id="problemHardware" class="problemRadio" name="problemRadio" value="Hardware">
Software <input type="radio" id="problemSoftware" class="problemRadio" name="problemRadio" value="Software">
<input type="text" id="problemWith" class="problemWith" name="problemWith"><br>
</p>
<p>3. Resolved By:<br /><br />
<textarea name="resolvedWith" id="resolvedWith"></textarea>
</p>
<p>4. Your Name:<br>
<input type="text" id="techName" class="input" name="techName" /><br>
</p>
<p>
<input type="button" class="button" value="Make My Notes!" onClick="javascript:getNotes();" />
<input type="reset" class="button" value="Start Over" />
</p>
<br><br>
<textarea name="outputArea" id="outputArea"></textarea>
<p class="finishMessage" id="finishMessage" name="finishMessage"></p>
</form>
one approach would be to check on the value and if else
var input1val = document.getElementById('input1Id').value;
var input2val = document.getElementById('input2Id').value;
var valfromeitherbox = (input1val.length > 0) ? input1val : input2val;
/* UPDATE : ^ is the same as -
var valfromeitherbox;
if(input1val.length > 0) { valfromeitherbox=input1val;
} else { valfromeitherbox=input2val; }
*/
document.getElementById('input3Id').value = valfromeitherbox;
/* if val is empty in input1 use val from text box 2 */
Sorry if a little scrappy , but hope you get the gist and I haven't missed the point

Categories