Problem with function and buttons in JavaScript - javascript

Today I have a tricky (for me at least) question. There is a bug in my code, I don't know how to eliminate it. Basically I'm creating a simple Form in JavaScript as an homework, and I encountered this problem.
I have to enter my age in this form, and for now it's all ok. But I have to enter it twice: one with an <input> tag and one with a popup window. I can input the value in the <input> tag just fine, but when I'm trying to input the value by the prompt(), it "resets" the script, so I lose the value in the <input> object.
I need a way to store these information somewhere, or stop the prompt() from deleting these values or resetting the page.
<html lang="en">
<head>
<title>Document</title>
<style>
* {margin: 0; padding: 0;}
body {padding: 20px;}
</style>
<script>
var eta_btn;
function eta_controllo(eta_btn) {
eta_btn = Number(prompt("Inserisci la tua età"));
console.log(eta_btn);
}
function profession() {
var temp = document.getElementById("select").selectedIndex;
if (temp == 0) {
document.getElementById("lavoratore_txt").style.display = "";
document.getElementById("studente_txt").style.display = "none";
} else if (temp == 1) {
document.getElementById("studente_txt").style.display = "";
document.getElementById("lavoratore_txt").style.display = "none";
} else {
document.getElementById("studente_txt").style.display = "none";
document.getElementById("lavoratore_txt").style.display = "none";
}
}
function send_to_server() {
if (!(eta_btn == document.getElementById("età").value)) {
alert("Le due età inserite non sono concordi");
return false;
}
else if (eta_btn == document.getElementById("età").value && eta_btn < 14) {
alert("Hai meno di 14 anni!");
return false;
} else if (confirm("Sicuro di aver scelto la provincia " + document.querySelector('input[name="città"]:checked').value))
alert("Dati inviati correttamente");
else {
alert("Errore");
return false;
}
}
</script>
</head>
<body>
<form action="">
<p>NOME</p>
<input placeholder="scrivi qui il tuo nome" type="text"><br><br>
<p>PASSWORD</p>
<input placeholder="scrivi qui la tua password" type="text"><br><br>
<p>ETA'</p>
<input placeholder="scrivi qui la tua età" type="text" id="età">
<button onclick="eta_controllo()">CONTROLLO</button><br><br>
<input name="città" type="radio">GENOVA<br>
<input name="città" type="radio">SAVONA<br>
<input name="città" type="radio">IMPERIA<br>
<input name="città" type="radio">LA SPEZIA<br><br>
<select name="" id="select" onchange="profession()">
<option value="lavoratore">Lavoratore</option>
<option value="studente">Studente</option>
<option value="disoccupato">Disoccupato</option>
</select>
<p id="studente_txt" style="display: none">Vai a studiare!</p><br>
<textarea id="lavoratore_txt" style="display: none;" name="" id="" cols="30" rows="10"></textarea><br><br>
<button>ANNULLA TUTTO</button>
<button onclick="send_to_server()">INVIA AL SERVER</button>
</form>
</body>
</html>

All you have to do is to add type="button" to the button.
The default type of button is "submit", so when you click it, it will submit the form.

Hi have you already taken a look at this link?
It could be ulile in my opinion ..
there are no global variables to manage the memories ..
The Localstorage of the browser.
I hope I have been of help .. good studyhttps://www.w3schools.com/jsref/prop_win_localstorage.asp

Related

I can't see an alert advise

I’m studying how to work with HTML forms and JavaScript (JS) and I faced a problem:
I wrote the Meta tags (HTML) and used JS elements, events and functions to treat possible user mistakes. The page shows when user follow in mistake and don’t insert the correct information. But, even with these mistakes, when the “submit button” is used, the alert message is not showing. I tried to inspect what’s happening and browser give a message like:
“DevTools failed to load source map: Could not load content for chrome-extension://nllcnknpjnininklegdoijpljgdjkijc/bundles/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT”.
Here is my code:
HTML
<!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>Document</title>
</head>
<body>
<h2>HTML Forms</h2>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="submit" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
JavaScript
`
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
let form = document.getElementById("formulario");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
//validar quando usuário envia o formulário
form.onsubimit = function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
}
`
My expactation is: when the form has mistakes, according to the rules, shows the alert and forbiden the submitoin.
First, you wrote your event property incorrectly as: **onsubimit** instead of **onsubmit**.
But, you are using a submit button, which attempts to send the form data to whatever resource the form element's action attribute is set to and it will attempt to redirect the browser to that location. In your case, you're not submitting data anywhere, so you should be using a regular button with a click event handler.
Also, you really should be using the modern standard for setting up event handlers, which is .addEventListener() instead of event properties like onXyz. See the updated code for the button's click event below.
And the 6 heading elements in HTML (h1...h6) should not be used because of the way they style their text. They are for setting up the structure of the document. As such, you should always start with h1 and then only use h2 if you want to create a sub-section of the h1. If you then don't like the style of the text that the heading element produces, use CSS to modify that instead of changing to a heading style that you like to the look of.
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
// You don't need a reference to the form, you need a reference to the button
let button = document.querySelector("input[type='button']");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário envia o formulário
// You should just use a regular button and set up a click event handler for it
// using the modern, standards-based approach of .addEventListener()
button.addEventListener("click", function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
});
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
<!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>Document</title>
</head>
<body>
<h1>HTML Forms</h1>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="button" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

Form Field Submission

I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.

Form Validation and Alert issues in JavaScript

The following is a complete copy of the project I'm working on. I'm having problems with the JavaScript validating segments of the form as well as JavaScript producing an alert at the end of the function.
The idea is to have the functions is to validate the form so that, if you are over 18: you only need the first and last name fields filled out. (The content doesn't really matter so long as it works.) On the other hand however, if you are under 18, the function will need to validate guardian details as well.
Until somewhat recent changes were made however this worked fine, the problem is I left the project for several weeks so I don't know what changes were made to be able to undo them. Ideally the basic code wouldn't change too much, I'm looking for a quick fix or stop-gap measures that will have the same effect.
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.forms("death")("GuardianName").setAttribute("required", "");
document.forms("death")("GuardianNumber").setAttribute("required", "");
//alert("Step4");
}
function validateForm() {
var a = document.forms("death")("GuardianName").value;
var b = document.forms("death")("GuardianNumber").value;
var c = document.forms("death")("FirstName").value;
var d = document.forms("death")("LastName").value;
if (document.getElementById("YesNo").selectedIndex == "1")
{
if (a == "" || b == "") {
alert("Please fill ALL required fields");
}
else {
alert("Registration Complete!");
}
}
else if (c == "" || d == "") {
alert("Please fill ALL required fields")
}
else {
alert("Registration Complete!")
}
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input onClick="validateForm()" type="submit" value="Submit">
</form>
</body>
</html>
1) you don't need to call validate if you already set field to required. The browser will handle that for you.
2. I wonder why you used 'getElementbyId' in NoRequirement() but document.forms in AddRequirement().
In anycase here is a modified version of your code. cheers
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.getElementById('GuardName').setAttribute("required","")
document.getElementById('GuardPhone').setAttribute("required","")
//alert("Step4");
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>

Launch script after confirming action (HTML)

So, I'm currently doing my final internship for the Network Administration training at school. And I've been asked to create a simple web page that allows for selecting a range of servers to perform a clean install on. Like: when I select 'Server 1' and 'Server 4' > click 'Submit' > confirm my action > launch VBscript that performs clean install.
What I have so far (also refer to pieces of code at end):
- Basic welcome text
- Check boxes
- Select all (javascript)
- Continue button
- When clicking continue button > show warning that asks for confirmation
What I want it to do, is launching the script of the selected box(es) after confirming. Is that possible? I mean, I assume I'll need something else than HTML. Javascript maybe? How would I do such thing?
I'm not a total expert with this stuff, not at all. I do have some experience with HTML and CSS, but Javascript and all that? Nope, not at all. Would be very happy to have some help with this!
<html>
<head>
<title>
Huawei Cleaning Center
</title>
<script type="text/javascript">
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
</script>
<script type="text/javascript">
function clicked() {
if (confirm('Weet u zeker dat u wilt doorgaan?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
</head>
<body>
<center><h1>Welkom bij Huawei Cleaning Center!</h1></center>
<br><br>
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:<br><br>
<form method="GET" action="page17.php" name="myForm" onsubmit="return false;">
<label for="myCheckbox1">
<input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1">
172.16.115.11 </label>
<br>
<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2">
172.16.115.21 </label>
<br>
<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3">
172.16.115.31 </label>
<br>
<label for="myCheckbox4"><input type="checkbox" name="myCheckbox" value="4" id="myCheckbox4">
172.16.115.41 </label>
<br><br><input type="submit" id="submit1" onclick="clicked();" value="Doorgaan">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="Selecteer alles">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="Deselecteer alles">
</form>
</body>
</html>
Change your js like this. Form gonna submit if you click yes
<script type="text/javascript">
function clicked() {
var confirmed = confirm('Weet u zeker dat u wilt doorgaan?')
if (confirmed) {
yourformelement.submit();
} else {
alert('You clicked No');
}
}
</script>
if you use JQuery you also could do this:
$(yourformelement).submit(function(e){
var dialogresult = confirm('Confirm');
if (dialogresult ) {
return true;
} else {
return false;
}
});
Looking at your code, it seems like you're using PHP. In this case you could try something like this in your php page (page17.php as referred in the action attribute):
if(!empty($_POST['serverList'])) {
foreach($_POST['serverList'] as $arg) {
exec('cscript "path/to/script.vbs" ' . $arg);
}
}
$_POST['serverList'] contains an array of the checkboxes values and the foraech loop will execute a VBscript passing the values as arguments.
Here's a snippet of the JS/CSS/HTML code:
function setCheckboxes(checkboxName, value) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = value;
}
}
function submitForm(checkboxName) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == true) {
confirmation = confirm('Weet u zeker dat u wilt doorgaan?');
if (confirmation) {
return true;
} else {
return false;
}
}
}
alert('No server selected!');
return false;
}
.main-heading {
margin-bottom: 60px;
text-align: center;
}
.info {
margin-bottom: 60px;
}
<h1 class="main-heading">Welkom bij Huawei Cleaning Center!</h1>
<p class="info">
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:
</p>
<form method="POST" action="page17.php" name="myForm" onsubmit="return false;">
<label for="checkbox-1">
<input type="checkbox" name="serverList[]" value="1" id="checkbox-1">
172.16.115.11
</label>
<br>
<label for="checkbox-2">
<input type="checkbox" name="serverList[]" value="2" id="checkbox-2">
172.16.115.21
</label>
<br>
<label for="checkbox-3">
<input type="checkbox" name="serverList[]" value="3" id="checkbox-3">
172.16.115.31
</label>
<br>
<label for="checkbox-4">
<input type="checkbox" name="serverList[]" value="4" id="checkbox-4">
172.16.115.41
</label>
<br><br>
<input type="submit" onclick="submitForm('serverList[]');" value="Doorgaan">
<input type="button" onclick="setCheckboxes('serverList[]', true);" value="Selecteer alles">
<input type="reset" value="Deselecteer alles">
</form>
Hope it helps :)

Categories