I have this code where I take the submissions from a form and append it to a HTML.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button] {
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<div>
<input type="button" id="bt" value="Write" onclick="writeFile()" />
</div>
</div>
<p>Submission Number: <a id="clicks">1</a>
<div class="output-area">
<h4>Output</h4>
<div id="output" class="inner">
</div>
</div>
<span></span>
</body>
<script>
var clicks = 1;
let writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.value}</p>`];
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
</html>
In this code, I wanted to print the users' current submission number. So I made a click counter.
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
And then I tried to put it into a constant and append it.
const submissions = document.getElementById('clicks');
But issue I'm facing here is, when appended my submission field comes out as Submission No: undefined. Any help would be much appreciated.
Your submissions element is an anchor (<a>) element. These HTML elements do not have a value field.
You can read the value the same way you are writing it, via innerHTML.
E.g.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button] {
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<div>
<input type="button" id="bt" value="Write" onclick="writeFile()" />
</div>
</div>
<p>Submission Number: <a id="clicks">1</a>
<div class="output-area">
<h4>Output</h4>
<div id="output" class="inner">
</div>
</div>
<span></span>
</body>
<script>
var clicks = 1;
let writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.innerHTML}</p>`]; // Use innerHTML here
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
</html>
Generally you could of course also insert the clicks variable directly (instead of the contents of the a element).
Note
It is highly insecure to render user-input into your HTML. It creates all sorts of vulnerabilities for malicious users so DON'T do this in production.
<a> tags don't have a value attribute. You'll have to use textContent or innerText to get the count.
console.log(document.getElementById('clicks').textContent);
<a id="clicks">2</a>
Ok, so submissions is not a input element and so it does not have the value method.
Instead of using submissions.value use submissions.innerHTML.
Also, rearrange the last few lines to make sure the clicks counter is updated before outputting all the data.
Edit: I did not realize your clicks counter was initially let clicks = 1; and not let clicks = 0;. The rearranging in the below JS will only work if clicks is initially set to 0.
I would generally advise to use let clicks = 0; because it makes more sense to potentially yourself and another person reading your code. If you think about it - when you make your counter (clicks), there have not been any clicks yet and so it would make more sense to have it initially set to 0.
let clicks = 0;
const writeFile = () => {
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
const submissions = document.getElementById('clicks');
// ++ is same thing as += 1
clicks++;
submissions.innerHTML = clicks;
let data = [
`<p>Name: ${name.value}</p>`,
`<p>Age: ${age.value}</p>`,
`<p>Email: ${email.value}</p>`,
`<p>Country: ${country.value}</p>`,
`<p>Message: ${msg.value}</p>`,
`<p>Submission No: ${submissions.innerHTML}</p>`
];
$('#output').append("<br />" + "<br />");
data.forEach(line => $('#output').append(line));
}
Related
I have a chess form with six fields. Two are drop down menus to select names (whiteplayername and blackplayername) and the other four can be used to add a custom name instead (firstnamewhite, lastnamewhite, firstnameblack, lastnameblack). Currently, I want my javascript to disable the custom fields if a name has been selected from the drop down menu (this is working). I also want the submit button to be disabled if neither the whiteplayername or firstnamewhite and blackplayername of firstnameblack is selected. Currently, the submit-button becomes enabled if a name is selected from both the blackplayername and whiteplayname menus but then does not become disabled again if an empty field is selected in either.
Edit
The full html is below, though I have taken out a section just made up of text and rows from the table in order to cut down on the space used.
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>chessopenings3</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
body {
style: "background-color: #FF0000;
}
.topnav {
position: relative;
overflow: hidden;
background-color: #333;
border: 2px;
width: max-content;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
border: 2px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
border: 2px;
}
.formformat {
color: white;
padding: 50px;
font-size: 24px;
font-family: Arial, Helvetica, sans-serif;
}
.instructions-text {
position: absolute;
color: white;
align: center;
left: 750px;
top: 150px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
.warning {
position: absolute;
color: white;
text-align: left;
left: 150px;
top: 50px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
select {
width: 120px;
}
select:focus {
min-width: 120px;
width: auto;
}
#media screen and (max-width: 500px) {
.navbar a {
float: none;
display: block;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
let isformvalid = false;
document.getElementById("submit-button").disabled = !isformvalid;
document.getElementById("whiteplayername").addEventListener("change", function () {
let blackplayername =
document.getElementById("blackplayername");
let firstnameblack =
document.getElementById("firstnameblack");
let firstnamewhite =
document.getElementById("firstnamewhite");
let lastnamewhite =
document.getElementById("lastnamewhite");
let lastnameblack =
document.getElementById("lastnameblack");
disablewhenmandatorynamemissingwhitename(this.value, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite);
isformvalid = checkeitherfirstorfullnamepopulated (this.value, firstnamewhite, blackplayername, firstnameblack, isformvalid);
document.getElementById("submit-button").disabled = !isformvalid;
});
});
function disablewhenmandatorynamemissingwhitename(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (whiteplayername !== "") {
firstnamewhite.disabled = true;
lastnamewhite.disabled = true;
} else {
firstnamewhite.disabled = false;
lastnamewhite.disabled = false;
}
}
function disablewhenmandatorynamemissingblackname(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (blackplayername !== "") {
firstnameblack.disabled = true;
lastnameblack.disabled = true;
} else {
firstnameblack.disabled = false;
lastnameblack.disabled = false;
}
};
function checkeitherfirstorfullnamepopulated(whiteplayername, firstnamewhite, blackplayername, firstnameblack, isformvalid) {
if ((whiteplayername === "" || whiteplayername === null) && (firstnamewhite.trim() === "")) {
return false;
}
else if ((blackplayername === "" || blackplayername === null) && (firstnameblack.trim() === "")) {
return false;
}
return true;
};
</script>
<body style="background-color:rgb(68, 57, 57);">
<div class="warning">
<p id="warningtext"></p><br>
</div>
<div class="topnav">
<a th:href="#{main.html}"><i class="material-icons"
style="border:2px;font-size:60px;color:rgb(0, 0, 0);">arrow_back</i></a>
</div>
<div class="formformat">
<form th:object="${game}" th:action="#{/addgame}" th:method="post">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<table>
<tr>
<th>Move</th>
<th>White</th>
<th>Black</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="white1" th:field="*{moves}"></td>
<td><input type="text" id="black1" th:field="*{moves}"></td>
</tr>
</table>
<input type="submit" value="Submit" id="submit-button">
</form>
</div>
<br><br>
</body>
</html>
Here's a solution that should meet all your requirements:
<script type="module">
const form = document.getElementById("form");
const submitButton = document.getElementById("submitbutton");
const whitePlayerName = document.getElementById("whiteplayername");
const blackPlayerName = document.getElementById("blackplayername");
const firstNameBlack = document.getElementById("firstnameblack");
const firstNameWhite = document.getElementById("firstnamewhite");
const lastNameWhite = document.getElementById("lastnamewhite");
const lastNameBlack = document.getElementById("lastnameblack");
form.addEventListener('change', () => {
const whiteNameSelected = whitePlayerName.value;
// Disable white name inputs if white name is selected in the dropdown
firstNameWhite.disabled = whiteNameSelected;
lastNameWhite.disabled = whiteNameSelected;
// Determine if the white name is either selected or typed in the inputs
const validWhiteName = whiteNameSelected || (firstNameWhite.value && lastNameWhite.value);
const blackNameSelected = blackPlayerName.value;
// Disable black name inputs if black name is selected in the dropdown
firstNameBlack.disabled = blackNameSelected;
lastNameBlack.disabled = blackNameSelected;
// Determine if the black name is either selected or typed in the inputs
const validBlackName = blackNameSelected || (firstNameBlack.value && lastNameBlack.value);
const submitAvailable = validWhiteName && validBlackName;
submitButton.disabled = !submitAvailable;
});
</script>
<form th:object="${game}" th:action="#{/addgame}" th:method="post" id="form">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<button id="submitbutton" disabled>Submit</button>
</form>
It works by combining all the logic into a single handler for the entire form change. Then, if a name is selected in the dropdown, it disables the custom name fields, if not, it leaves them enabled. The code checks to make sure both white and black name are valid and depending on that sets the submit button enabled/disabled state.
You didn't post your whole HTML so I added the button by hand and also your selects are populated dynamically so I had to hardcode some options in them. Please, for Stack Overflow questions, always post examples reproducible by other people to aid them in helping you.
Can you provide the html code too? I also recommend to name properly ur variables and fucntions beacuase are pretty illegibles by the way. Try to type the first letter of each word that compunds the varibale in uppercase at least.
Instead of:
let firstnameblack
Do:
let firstNameBlack
I also recommend to put 2 or 3 letters according to what specifies this varibale, for example if it's a button, do:
let btnFirstNameBlack
Anyways if you can provide the html code maybe I can help you with the button issue.
so when i press submit on my form in my 2nd tab, it automatically goes to the first tab, I would like it if possible for it to stay on the 2nd tab as i'm not able to view my information. Thank you.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box
}
/* Set height of body and the document to 100% */
body,
html {
height: 100%;
margin: 0;
font-family: Arial;
}
/* Style tab links */
.tablink {
background-color: #555;
color: white;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
font-size: 17px;
width: 50%;
}
.tablink:hover {
background-color: #777;
}
/* Style the tab content (and add height:100% for full page content) */
.tabcontent {
color: white;
display: none;
padding: 100px 20px;
height: 100%;
}
#Metric {
background-color: royalblue;
}
#Imperial {
background-color: mediumseagreen;
}
</style>
</head>
<body>
<button class="tablink" onclick="openPage('Metric', this, 'royalblue')" id="defaultOpen">Metric BMR Calculator</button>
<button class="tablink" onclick="openPage('Imperial', this, 'mediumseagreen')" id="defaultOpen">Imperial BMR Calculator</button>
<div id="Metric" class="tabcontent">
<form><br>
<label>Sex </label>
<select id="sex">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br><br>
Age: <input type="text" id="Age" /><br><br>
Your Height: <br>
<br>
Centimeters: <input type="text" id="cm" />
<br>
<br>
Your Weight: <br>
<br>
Kilograms: <input type="text" id="kg" />
<br>
<br>
<input type="radio" id="id1" name="fit" value="1.2" checked >
<label for="id1" >I am sedentary (little or no excercise)</label><br>
<input type="radio" id="id2"name="fit" value="1.375" >
<label for="id2" >I am lightly active (light excercise or sports 1-3 days per week)</label><br>
<input type="radio" id="id3" name="fit" value="1.55">
<label for="id3">I am moderately active (moderate excercise or sports 3-5 days per week)</label><br>
<input type="radio" id="id4" name="fit" value="1.725">
<label for="id4">I am very active (hard excercise or sports 6-7 days per week</label><br>
<input type="radio" id="id5" name="fit" value="1.9">
<label for="id5">I am super active (very hard excercise or sports and a physical job or 2x training)</label><br><br>
<input type="submit" onclick="metricCalculation()" /><br>
<br>
</form>
</div>
<div id="Imperial" class="tabcontent">
<form><br>
<label>Sex </label>
<select id="sex">
<option value="M">Male</option>
<option value="F">Female</option>
</select><br><br>
Age: <input type="text" id="Age" name="Age" /><br><br>
Your Height: <br>
Feet: <input type="text" id="Feet" name="Feet" />
Inches: <input type="text" id="Inches" name="Inches" /><br><br>
Your Weight: <br>
Stones: <input type="text" id="Stones" /> Pounds: <input type="text" id="Pounds"><br><br>
<input type="radio" id="age1" name="age" value="30" >
<label for="age1">I am sedentary (little or no excercise)</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">I am lightly active (light excercise or sports 1-3 days per week)</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">I am moderately active (moderate excercise or sports 3-5 days per week)</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">I am very active (hard excercise or sports 6-7 days per week</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">I am super active (very hard excercise or sports and a physical job or 2x training)</label><br><br>
<input type="submit" value="Submit" onclick="imperialCalculation()" /><br>
</form>
</div>
</body>
<script>
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
function metricCalculation() {
var theDiv = document.getElementById("Metric");
var Age = document.getElementById("Age").value;
var Sex = document.getElementById("sex").value;
var Cm = document.getElementById("cm").value;
var Kg = document.getElementById("kg").value;
var activity = document.querySelector('input[name="fit"]:checked').value;
if(Sex === "M"){
theDiv.innerHTML += ("male!<br>");
var total1 = (10 * Kg) + (6.25 * Cm) - (5 * Age) + 5
var total2 = total1*activity;
theDiv.innerHTML += ("Your BMR is: " +total1+ " Calories/Day<br>");
theDiv.innerHTML +=("Your daily caloric intake should be: " + total2+ " Calories/Day<br>");
}
if(Sex === "F"){
theDiv.innerHTML += ("female!<br>");
var total1 = (10 * Kg) + (6.25 * Cm) - (5 * Age) - 161
var total2 = total1*activity;
theDiv.innerHTML += ("Your BMR is: " +total1+ " Calories/Day<br>");
theDiv.innerHTML +=("Your daily caloric intake should be: " + total2+ " Calories/Day<br>");
}
}
function imperialCalculation() {
var Age = document.getElementById("Age").value;
var LastName = document.getElementById("LastName").value;
var Email = document.getElementById("Email").value;
var Sex = document.getElementById("sex").value;
document.getElementById("total").innerHTML("<h1>Data Received</h1><br>");
document.writeln("Form Completed<br><br>");
document.writeln("The first name you entered is <b>" + FirstName + "</b><br>");
document.writeln("The last name you entered is <b>" + LastName + "</b><br>");
document.writeln("The email address is <b>" + Email + "</b><br>");
document.writeln("Your sex is: " + Sex)
document.getElementById('spanResult1').textContent = "hi";
document.getElementById('spanResult').textContent = "cool";
}
function openPage(pageName, elmnt, color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
</script>
</html>
I'm assuming it has to do with the "defaultOpen" id, but i'm not sure how to make it so it doesn't always go to the default opened tab.
You're looking for event.preventDefault() MDN. You need to change imperialCalculation() to take the parameter event, then call event.preventDefault(). Like this:
function imperialCalculation(event) {
event.preventDefault();
// ...
// rest of function is the same
// ...
}
The default behavior of a <form> tag is to reload the page, so form data can be sent to a server. Your form doesn't have a action attribute so it doesn't send anything to a server, but the browser will still reload the page. Calling event.preventDefault() stops the default behavior.
The idea is for the user to select the options and the best employment
sector would be suggested by the form based on his selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Survey that will will give you suggestion.
</title>
<style>
/* Styling the Body element i.e. Color,
Font, Alignment */
body {
background-color: #05c46b;
font-family: Verdana;
text-align: center;
}
/* Styling the Form (Color, Padding, Shadow) */
form {
background-color: #fff;
max-width: 500px;
margin: 50px auto;
padding: 30px 20px;
box-shadow: 2px 5px 10px rgba(0, 0, 0, 0.5);
}
/* Styling form-control Class */
.form-control {
text-align: left;
margin-bottom: 25px;
}
/* Styling form-control Label */
.form-control label {
display: block;
margin-bottom: 10px;
}
/* Styling form-control input,
select, textarea */
.form-control input,
.form-control select,
.form-control textarea {
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
padding: 10px;
display: block;
width: 95%;
}
/* Styling form-control Radio
button and Checkbox */
.form-control input[type="radio"],
.form-control input[type="checkbox"] {
display: inline-block;
width: auto;
}
/* Styling Button */
button {
background-color: #05c46b;
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
font-size: 21px;
display: block;
width: 100%;
margin-top: 50px;
margin-bottom: 20px;
}
</style>
</head>
The form is made with HTML. and for javascript operations i have added
value=1 in the checkbox for generating the different output string.
please view the code below to understand better.
<body>
<h1>Your job type survey suggestion quiz</h1>
<!-- Create Form -->
<form id="form">
<!-- Details -->
<div class="form-control">
<label for="name" id="label-name">
Name
</label>
<!-- Input Type Text -->
<input type="text"
id="name"
placeholder="Enter your name" />
</div>
<div class="form-control">
<label for="email" id="label-email">
Email
</label>
<!-- Input Type Email-->
<input type="email"
id="email"
placeholder="Enter your email" />
</div>
<div class="form-control">
<label for="age" id="label-age">
Age
</label>
<!-- Input Type Text -->
<input type="text"
id="age"
placeholder="Enter your age" />
</div>
<div class="form-control">
<label for="role" id="label-role">
Which option best describes you?
</label>
<!-- Dropdown options -->
<select name="role" id="role">
<option value="student">Student</option>
<option value="intern">Intern</option>
<option value="professional">
Professional
</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-control">
<label>
DO you like studying?
</label>
<!-- Input Type Radio Button -->
<label for="recommed-1">
<input type="radio"
id="recommed-1"
name="recommed">Yes</input>
</label>
<label for="recommed-2">
<input type="radio"
id="recommed-2"
name="recommed">No</input>
</label>
<label for="recommed-3">
<input type="radio"
id="recommed-3"
name="recommed">Maybe</input>
</label>
</div>
<div class="form-control">
<label>Skills that you have
<small>(Check all that apply)</small>
</label>
<!-- Input Type Checkbox -->
<label for="inp-1">
<input type="checkbox" name="inp" id="c" value=1>Coding</input></label>
<label for="inp-2">
<input type="checkbox" name="inp" id="d" value=2>Dancing</input></label>
</div>
<button onclick="checkCheckbox()">
Submit
</button>
</form>
Here as of now only 2 questions are in the form, I want to add more
questions and on based of the selection the form will suggest. In this
the alert or any message i`enter code here`s not shown neither there is any error.
<script>
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add=0
if (c.checked == true){
var y = document.getElementById("c").value;
var add=y;
return add;
}
else if (d.checked == true){
var n = document.getElementById("d").value;
var add += n;
}
else {
return document.getElementById("error").innerHTML = "*Please mark any of checkbox";
}
if(add==2){
alert('You are multi-talented! become a dancer or a coder');
}
else{
alert('Become a coder');
</script>
</body>
</html>
here on selecting dancing and coding a different output should be
given and on selecting either dancing or either coding a different
output string should be shown. please suggest for any modifications or
if there is a better way to complete this idea.
There are several errors in the script section. You can use Web Developer debugging in your browser to check them out. I can see that you are new to coding in general, so there are a couple of common mistakes we've all made in the beginning.
This is one way of writing the function so it works as I think you intended it:
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add = 0, val;
if (c.checked == true){
val = "coder";
add += 1;
}
if (d.checked == true){
val = "dancer";
add += 1;
}
if (add == 2) {
alert('You are multi-talented! become a dancer or a coder');
return true;
}
else if (add == 1) {
alert('Become a ' + val);
return true;
}
else {
document.getElementById("error").innerHTML = "*Please mark any of checkbox";
return false;
}
}
Also, you need to add return in the event handler of the button, to avoid it submitting when the form is invalid:
<button onclick="return checkCheckbox()">Submit</button>
And lastly add an element for the error message that is referred to in the script. Something like:
<div id="error"></div>
I have a form in visual studio that asks for feedback, name and their order number.
I'd like to save all this information into a txt file when they click Submit so that I can review it later on.
return (
<>
<Typography variant="h6" gutterBottom>Feedback</Typography>
<FormProvider {...methods}>
<form onSubmit=''>
<Grid container spacing={3}>
<FormInput required name='fullName' label='Full Name' />
<FormInput required name='orderNumber' label='Order Number' />
<FormInput required name='message' label='Message' />
</Grid>
</form>
</FormProvider>
<div>
<Button component= className={classes.checkoutButton} size="large" type="button" variant="contained" color="primary">Submit</Button>
</div>
</>
Try this code:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text], textarea, select {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button]{
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<!--Add few elements to the form-->
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<!--Add to button to save the data.-->
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</div>
</body>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
// This variable stores all the data.
let data =
'\r Name: ' + name.value + ' \r\n ' +
'Age: ' +age.value + ' \r\n ' +
'Email: ' + email.value + ' \r\n ' +
'Country: ' + country.value + ' \r\n ' +
'Message: ' + msg.value;
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.txt'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
</script>
</html>
In the below code, after clicking on 'Save Data' I want the page to go to another htm page 'confrim.html'. Instead what is happening is its just showing "localhost:3000/confirm.html" and not opening a new page. Can anyone help to fix this, attaching the code for the reference.
I tried to implement the following through the submitInfo() function
Thanks
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">-->
<style>
* {
box-sizing:border-box;
border-color: teal;
}
html{
background : radial-gradient(rgba(48, 97, 97, 0.5),rgba(255,255,255,0.5))
}
div {
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
.input[type=button]{
font: 25px Calibri;
width: auto;
float: left;
cursor: pointer;
padding: 7px;
color: teal;
font-size: 30px;
}
#bt{
width : 190px;
height: 60px;
font-size: 25px;
font-family: 'Times New Roman', Times, serif;
background-color: #05193d;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin-top: 10px;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color:teal
}
</style>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<!--<link rel="stylesheet" href="style.css">-->
</head>
<body>
<div>
<form name="myForm" action="confirm.html" method="POST" >
<!--Add few elements to the form-->
<div>
<label for="Name">Name</label>
<input type="text" id="txtName" placeholder="Enter your name" required />
</div>
<div>
<label for="Email">Email</label>
<input type="text" id="txtEmail" placeholder="Enter your Email Id" />
</div>
<div>
<label for="Controller Type">Controller Type</label>
<select id="selProd">
<option value=""> - Select the Controller - </option>
<option value="RAID">RAID</option>
<option value="JBOD">JBOD</option>
<option value="EBOD">EBOD</option>
<option value="AP">AP</option>
</select>
</div>
<div>
<label for="Test Type">Test Type </label>
<select id="selTest">
<option value=""> - Select The Test - </option>
<option value="BFT">BFT</option>
<option value="Manufacturing">Manufacturing</option>
<option value="Channel">Channel</option>
<option value="DVT" >DVT</option>
</select>
</div>
<div>
<label for="Protocol Type">Protocol Type </label>
<select id="selProto">
<option value=""> - Select The Protocol - </option>
<option value="SAS">SAS</option>
<option value="iSCSI">iSCSI</option>
<option value="FC">FC</option>
</select>
</div>
<div>
<label for="IP Address">IP Address:</label>
<input type="text" id="txtIP" placeholder="Enter your IP address" />
</div>
<div>
<label for="Chasis Input">Number of Chasis Input:</label>
<input type="number" id="txtInputs" placeholder="Enter Number of Chasis" />
</div>
<div>
<input type="button" id="myBtn" value="Save data" onclick="submitInfo()"/>
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</form>
</div>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const email = document.getElementById('txtEmail');
const test = document.getElementById('selTest');
const product = document.getElementById('selProd');
const protocol = document.getElementById('selProto');
const IP = document.getElementById('txtIP');
const Inputs = document.getElementById('txtInputs');
// This variable stores all the data.
let data =
'\rName : ' + name.value + '\r\n' +
'Email ID : ' + email.value + '\r\n' +
'Test Type : ' + test.value + '\r\n' +
'Product Type : ' + product.value + '\r\n' +
'Protocol Type : ' + protocol.value + '\r\n' +
'IP Address : ' + IP.value + '\r\n' +
'Chasis Inputs : ' + Inputs.value;
if(name.value =='' || email.value == '' || test.value =='' || product.value =='' || IP.value == ''|| Inputs.value == ''){
alert("Please fill all the fields!");
return;
}
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == false)
{
alert('Invalid Email Address');
return false;
}
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(IP.value) == false)
{
alert('Invalid IP Address');
return false;
}
if(name.value.length<3){
alert("Name must be having atleast 3 Characters");
return;
}
if(name.value == ''){
alert("Enter the name First");
}
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.yaml'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
var disable_options = false;
document.getElementById('selProd').onchange = function () {
//alert("selected value = "+this.value);
if(this.value == "RAID")
{
document.getElementById('selProto').removeAttribute('disabled');
}
else
{
document.getElementById('selProto').setAttribute('disabled', true);
}
}
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if(product == "EBOD" && test== "BFT"){
window.location ="confirm.html";
}
}
</script>
</body>
</html>
You could use the window.open method - like so:
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if( product == "EBOD" && test== "BFT" ){
window.open( "confirm.html", "Confirm", "fullscreen=yes,location=no,menubar=yes,resizable=no,scrollbars=no,status=no,toolbar=no" );
}
}
you have a
<form name="myForm" action="confirm.html" method="POST" >
which, on form submit, your browser will look for confirm.html file. I don't know whether you have file named confirm.html, but I think you do. otherwise it'll show 404 error.
As you instructed in your form, browser'll look for confirm.html, and on redirect, it'll show what's in confirm.html file.
you should remove your js script from this file and put it inside confirm.html file. or just replace action="confirm.html" with action=""