Javascript Array elements not writing to innerHTML - javascript

I have a Javascript function that reads entries from an HTML form into an array. However, when I try to read the array into a display element back on the HTML page, it shows up blank. I debugged and know the elements are getting into the array fine, but they aren't displaying when I use innerhtml on my desired output elements. Any help? Below is my JS code (the changepage function isn't complete)
var attributes = new Array("Name", "Nickname", "Email", "Favorite Movie", "Favorite Book", "Favorite Music", "Paragraph", "Image", "Page Background", "Text Color", 0)
function populateAttributes(){
var userInput = document.getElementById("myForm");
var i;
for (i = 0; i < userInput.length; i++){
if (userInput.elements[i].value == null){
document.write("All fields must be entered. Please try again.");
break;
} else {
attributes[i] = userInput.elements[i].value;
}
}
changePage();
}
function changePage(){
document.getElementById("nameOutput").innerHTML = attributes[0];
document.getElementById("avatar").src = attributes[7];
document.body.style.backgroundColor = attributes[8];
document.body.style.color = attributes[9];
document.body.style.fontSize = attributes[10];
}
And here is the HTML code
<form id="myForm" action="#" method="post" onsubmit="return populateAttributes()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="nickname">Nickname:</label><br>
<input type="text" id="nickname" name="nickname"><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<label for="movie">Favorite Movie:</label><br>
<input type="text" id="movie" name="movie"><br>
<label for="book">Favorite Book:</label><br>
<input type="text" id="book" name="book"><br>
<label for="music">Favorite Type Of Music:</label><br>
<input type="text" id="music" name="music"><br>
<label for="name">About You:</label><br>
<textarea id="about" name="about" rows="4" cols="50"></textarea><br>
<label for="avatar">Link To Avatar Image:</label><br>
<input type="text" id="avatar" name="avatar"><br><br>
<label for="background">Select a background color:</label><br>
<select id="background" name="background">
<option value="white">White</option>
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select><br>
<label for="txtcolor">Select a text color:</label><br>
<select id="txtcolor" name="txtcolor">
<option value="white">White</option>
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select><br>
<label for="txtsize">Enter text size (in pixels):</label><br>
<input type="text" id="txtsize" name="txtsize"><br><br>
<input type="submit">
</form>
<p>Name: <span id="nameOutput" class="result"></span></p>
Edit: I may have found the issue. After debugging, it shows that the values are in fact reading into the array. However, as soon as the function ends, it reverts back to a normal page. I'm not sure how to keep the values after the page reloads

Related

Opening URL from select list and passing all variables on submit

I have a pretty basic form consisting of 3 elements – 2 text input boxes and a select drop-down list. What I’m looking to achieve when hitting the submit button is to open the page that is listed at the value for the drop-down option and also pass through the values/data entered into the 2 text boxes.
I can get the form to open the correct url from the selected drop-down item, however the two text inputs are not carried through to the opened page.
Can this be done? Any helps would be greatly be appreciated.
<p align="center">
<form method="POST" name="jump" class="center">
Start Time : <INPUT TYPE="TEXT" name="stime" SIZE="10" /><br>
End Time : <INPUT TYPE="TEXT" name="etime" SIZE="10" /><br>
<select name="menu">
<option value="#">Select a Device</option>
<option value="rep-fire.php">Firewall</option>
<option value="rep-wap.php">WAP</option>
.....
</select>
<input type="button" onClick="window.open(document.jump.menu.options[document.jump.menu.selectedIndex].value);" value="GO">
</form>
</p>
I would use url.searchParams and eventListeners
Note I changed name to ID
window.addEventListener("load", function() { // on page load
document.getElementById("jump").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const path = document.getElementById("menu").value;
if (path) {
let url = new URL(location.href);
url.pathname = path;
let parms = url.searchParams;
parms.set("stime", document.getElementById("stime").value)
parms.set("etime", document.getElementById("etime").value)
console.log(url.toString());
// window.open(url.toString()); // uncomment when tested
}
})
})
<form method="POST" id="jump" class="center">
Start Time :
<input type="text" id="stime" size="10" /><br> End Time :
<input type="text" id="etime" size="10" /><br>
<select id="menu">
<option value="">Select a Device</option>
<option value="rep-fire.php">Firewall</option>
<option value="rep-wap.php">WAP</option>
</select>
<input type="submit" value="GO">
</form>

Javascript issue with selector session storage

Hello so I added some javascript to keep selection stored when page is reloaded in my select menu , but the issue is when I load the page for the first time nothing appears in my select menu (First choice of the select menu)
what appears
window.onload = function() {
var selItem = sessionStorage.getItem("SelItem");
$('#date').val(selItem);
}
$('#date').change(function() {
var selVal = $(this).val();
sessionStorage.setItem("SelItem", selVal);
});
<label class="op" for="date">Periode : </label>
<select id="date">
<option value="toutes">Toutes</option>
<option value="2019">Année en cours</option>
<option value="2018">Année pécédente</option>
<option value="2017">Année -2</option>
<option value="2016">Année -3</option>
<option value="2015">Année -4</option>
</select>
<br/><br/>
<input type="hidden" name="date" id="date1" class="datepicker w100" value="2015-01-01"type="date" placeholder="Du jj/mm/aaaa"> <input type ="hidden"name="date2" id="date2" value="2026-12-31"class="datepicker w100" type="date" placeholder="Au jj/mm/aaaa">
<br/>
So only set the value if there is something in storage.
if (selItem) $('#date').val(selItem);

Validating Paired Form Fields

I am trying to create what I hope is a somewhat simple donation form. There are two options to choose from:
A drop down with a text field to enter an amount
A text field to write in an other designation along with a text field to enter an amount
I've been looking through a lot of different examples of code, but I'm not entirely sure how to search the technical name for what I need. I need to have an alert appear when nothing is entered as well as an alert when only one part of 1 or one part of 2 is entered. I know this is something I need JS for, but have zero experience with it.
I found several pages that were a little helpful with validation and alert messages for multiple fields, but I think I need to have an either/or type of alert (if that makes sense). EITHER you choose from the drop down and enter an amount OR you enter something in the "Other" text field and enter an amount.
You can see my code below. I included some JS I found and tried to modify that seemed to be closest to what I'm looking for, but with my limited knowledge of the language I know it's not correct (try not to judge me). I can get an alert message that works sometimes and not for everyone. And sometimes the alert still appears when it's filled out correctly.
I feel like my brain is fried at this point, so any help you can provide is greatly appreciated. Javascript is definitely going to the top of my "Must Learn" list after this. Thank you!
<script>
function validateForm() {
var x = document.forms["form1"]["FUND1"].value;
var x = document.forms["form1"]["FUND2"].value;
var x = document.forms["form1"]["GIFT_AMOUNT1"].value;
var x = document.forms["form1"]["GIFT_AMOUNT2"].value;
if (form1.FUND1.value == '' && form1.FUND2.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
if (form1.GIFT_AMOUNT1.value == '' && form1.GIFT_AMOUNT1.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
}
</script>
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="0.00"/>
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation"/>
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="0.00"/>
</div>
<div style="clear:both; float:left;">
<p><input type="submit" value="Continue" class="continue_button" onclick="validateAndSend()"></p>
</div>
What you are doing is ok.
To improve what you are doing you can try this:
I'm paring FUND and GIFT_AMOUNT because I guess is what you are trying to do, now the alert will show when both 1s or 2s are empty.
function validateForm() {
var form1 = document.forms['form1']
if (form1.FUND1.value === '' || form1.GIFT_AMOUNT1.value === '') {
alert("please select a donation designation and an amount 1.");
return false;
}
if (form1.FUND2.value === '' || form1.GIFT_AMOUNT2.value === '') {
alert("please select a donation designation and an amount 2.");
return false;
}
return true;
}
In your form you need to initialize your GIFT_AMOUNT inputs with value="" otherwise if you compare '0.00' with '' always will be false.
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="" />
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation" />
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="" />
</div>
<div style="clear:both; float:left;">
<p>
<input type="submit" value="Continue" class="continue_button" />
</p>
</div>
</form>
There is no need to call a function in your onclick property because you are calling the submit function already to improve this behavior you can do something like this:
function submitForm() {
if (validateForm()) {
// do some stuff
}
}
and change the onsubmit property from your form
<form ... onsubmit="submitForm()">
If you are starting with javascript will be a good idea to learn how to use the console in order to debug your scripts. This article is a good point to start and as a last tip check this out.

How can I hide form if first form is not validated properly

JavaScript:
function myFunction() { //creating the onlick function
var locationFrom = document.getElementById("LocationFrom").value;// Getting both "from" and "to" Ids fromt he homepage.hmtl
var locationTo = document.getElementById("LocationTo").value;
if (locationFrom === locationTo) { // If both have same values then give an error as below
document.getElementById("errorLocationFrom").textContent = 'Destination cannot be the same.';
}
else {
document.getElementById("errorLocationFrom").textContent = ''; // if not the same then give no error
}
$("#Submit").click(function(){
$("#Form-2").show(); //Display form when Submit button is clicked
});
function SecForm(){
var ErrorLocation = document.getElementById("errorLocationFrom");
if(ErrorLocation == false) //Hide form2 if ErrorLocation is false
$("#Form-2").hide();
return false;
}
HTML:
<div class="full-col">
<label for="FDestination">From</label> <!---Label for select element--->
<select name="Location" id = "LocationFrom"> <!---Select element to give user options to select from-->
<option value="" disabled selected>Please Select </option> <!---Options for departing location-->
<option value="Newport">Newport</option>
<option value="Mahdi">London</option>
<option value="Cardiff">Cardiff</option>
<option value="Cilo">Brazil </option>
</select>
<label for="FDestination">To</label>
<select name="LocationTo" id = "LocationTo" >
<option value="" disabled selected>Please Select </option>
<option value="Cardiff">Cardiff</option>
<option value="Mahdi">London</option>
<option value="Newport">Newport</option>
<option value="Cilo">Brazil</option>
</select>
<!---Hidden Error message only shown when there is a validation error for departing and arrival--->
<label id="errorLocationFrom"></label>
</form>
<Form action="#" class="group" name="form2" id="Form-2" method="post" hidden = "true">
<legend id="fixed"><span class="number">2</span>Tickets</legend>
<div class="half-col">
<label for="Adult-ticket" class="center-label">Adults(+16)</label>
<input type="number" id="adult" name="user_adult">
<label id="AdTickError"></label>
</div>
<div class="half-col">
<label for="child-ticket" class="center-label">Child</label>
<input type="number" id="child" name="user_child">
<label id="ChildTickError"></label>
</div>
<input type="checkbox" id="Standard" name="Type" value="Standard">
<label class="light" for="Standard">Standard</label><br>
<input type="checkbox" id="First-Class" name="Type" value="First-Class">
<label class="light" for="First-Class">First Class</label><br><br>
<p id="total-cost"></p>
<button type = "button" value="checkout" id="checkoutbtn" onclick="AdultNumber(); calculateFare(); " >CHECKOUT</button>
</Form>
I am making a railway ticketing system and what I need, is the form to do is first be validated then after clicking the Submit button it will display the other form both forms are on the same page.
You could change the submit of form1 to input type button. When button1 is clicked you do your validation as before and if it is passed you show the form2.
In form2 you could use the onsubmit event to copy the fields you need from form1 to form2; <form id="Form-2" onsubmit="CopyData()">
In copy function you can do:
$('#Form-2').append( '<input type="hidden" name="LocationFrom" value="' + $('#LocationFrom').val() + '">' );
$('#Form-2').append( '<input type="hidden" name="LocationTo" value="' + $('#LocationTo').val() + '">' );
UPDATE - fiddle: https://jsfiddle.net/blocknotes/copyuwyd/

javascript - How do i use .click on an <option>

I'm fairly new to JavaScript and I cant figure out why this won't work. My friend said to try use .click or .select to test for a click on the option but nether of them worked.
My html:
<body>
<form>General
<hr>Full Name:
<br>
<input Type="text" name="name">
<br>Gender:
<br>
<input type="radio" Name="gender" value="Male">Male
<input Type="radio" name="gender" value="female">Female
<br>Birthday:
<br>
<input type="text" name="bday" placeholder="mm/dd/yy">
<br>Email Adress:
<br>
<input type="text" name="email">
<br>PayPal address:
<br>
<input type="text" name="PayPal" placeholder="for when we start paying staff">
<br>Short Biography:
<br>
<textarea rows="4" cols="50"></textarea>
<br>
<br>Apply:
<hr>Username:
<br>
<input type="text" name="nick" placeholder="Your Ingame Name">
<br>What Rank Are You Applying For:
<br>
<select>
<option id="Dev" value="Developer">Developer</option>
<option id="Headadmin" value="HeadAdmin">Head Admin</option>
<option id="Headmod" value="HeadMod">Head Modetator</option>
<option id="Headbuilder" value="HeadBuilder">Head Builder</option>
<option id="admin" value="Admin">Admin</option>
<option id="mod" value="Moderator">Moderator</option>
<option id="builder" value="Builder">Builder</option>
</select>
<br>Why do WE want you (Rank you picked above):
<br>
<textarea rows="4" cols="50"></textarea>
<br>How Many Hours Can You Be On a day:
<br>
<input type="text" name="day">
<br>how many days can you be on a week:
<br>
<input type="text" name="week">
<br>have you been staff before?
<br>
<select>
<option value="yes">yes
<option value="no">no</select>
<br>Test:
<hr>
<div id="DevTest">Devtest</div>
<div id="admintest">admin test</div>
<div id="modtest">mod test</div>
<div id="HAtest">head admin test</div>
<div id="HMtest">head mod test</div>
<div id="HBtest">headbuilder test</div>
<div id="buildertest">buildertest</div>
<br>
<hr>
<textarea readonly rows="5" cols="30">Staff Contract: ---------------- 1. As a staff member, YOU, are represent the "Piggalot Gaming Network" both online and offline. this means; A. If WE, The "Piggalot Gaming Network" Community,</textarea>
<hr>
<input type="checkbox" value="test" required>by clicking this you agree to the staff contract
<br>
<input type="reset">
<input type="submit" value="Send Application">
</form>
My JavaScript:
$(document).ready(function(){
$("#Dev").Click(function(){
$("#DevTest").show();
$("#HAtest").hide();
$("#HMtest").hide();
$("#HBtest").hide();
$("#admintest").hide();
$("#modtest").hide();
$("#buildertest").hide();
});
$("#Headadmin").Click(function(){
$("#HAtest").show();
$("#DevTest").hide();
$("#HMtest").hide();
$("#HBtest").hide();
$("#admintest").hide();
$("#modtest").hide();
$("#buildertest").hide();
});
});
Here the link to a Fiddle of it: http://jsfiddle.net/a2nw2sus/1/
<option> does not work that way. Listen for a change in <select> instead:
$('#id_for_your_select').change(function () {
var selected_value = $(this).val();
switch (selected_value) {
case 'Developer': {
// do something
break;
}
case 'HeadAdmin': {
// do something else
break;
}
}
});
In http://jsfiddle.net/a2nw2sus/2/ I fixed the spelling error (click() vs Click()), and lo: it does not work in Chrome. In Firefox it works, but you must not take this for granted!
You don't select options like you have. You're meant to give your select menu a reference (ID/class/name) and select that instead.
<select id="mySelectMenu">
<option value="Developer">Developer</option>
<option value="HeadAdmin">Head Admin</option>
<option value="HeadMod">Head Modetator</option>
<option value="HeadBuilder">Head Builder</option>
<option value="Admin">Admin</option>
<option value="Moderator">Moderator</option>
<option value="Builder">Builder</option>
</select>
If you just want to detect a click on the select:
$('#mySelectMenu').click(function() {
var currentValue = $(this).find(":selected").val();
console.log("The current selected option is "+ currentValue +".");
});
or maybe you want to get value of the select after a change was detected:
$('#mySelectMenu').on('change', function() {
var selectedValue = $(this).val();
if (selectedValue === "Dev") {
$("#DevTest").show();
$("#HAtest, #HMtest, #HBtest, #adminTest, #modtest, #buildertest").hide();
} else if (selectedValue === "HeadAdmin") {
$("#HAtest").show();
$("#DevTest, #HMtest, #HBtest, #adminTest, #modtest, #buildertest").hide();
}
});

Categories