Display form info on alert (html and javascript) - javascript

I currently have a form in which a user can put his name, age and the message and then I have a button to submit the message and it is supposed to show an alert with the form information but when I put the information and click the button nothing is happening (the alert doesn't show). Here is the html form and javascript function code:
<form action="#" method="get">
<fieldset>
<legend>Informações do utilizador</legend>
<label for="nome">Nome:</label>
<input id="nome" name="nome" type="text" />
<br />
<label for="idade">Idade:</label>
<select id="idade" name="idade">
<option value="menor"><18</option>
<option value="jovem">18-21</option>
<option value="jovemadulto">22-29</option>
<option value="adulto">30-39</option>
<option value="adultoavancado">40-49</option>
<option value="idoso">>=50</option>
</select>
</fieldset>
<fieldset>
<legend>Ideias para tornar um campus mais sustentável</legend>
<label for="mensagem">Mensagem:</label><br />
<textarea id="mensagem" name="mensagem" rows="10" cols="50" placeholder="Introduza a sua ideia">
</textarea>
<br />
<input id="enviar" name="enviar" type="submit" onClick="submitForm()" value="Enviar">
<script>
function submitForm() {
var n = document.getElementById('nome').value;
var i = document.getElementById('idade').value;
var m = document.getElementById('mensagem').value;
alert("Nome: "+s+"\n Idade: "+i+"\n Mensagem: "+m);
}
</script>
<input id="limpar" name="limpar" type="reset" value="Limpar" />
</fieldset>
</form>

the correct way to do that...
const myForm = document.querySelector('#my-form') // use the form parent
// to refer each form elements
// think about how to write your code:
// easier to read again = less typing errors
myForm.onsubmit = evt =>
{
alert( 'Nome: ' + myForm.nome.value // access each element by his name
+ '\n Idade: ' + myForm.idade.value
+ '\n Mensagem: ' + myForm.mensagem.value
);
evt.preventDefault(); // for testing without page relaod
}
<form action="#" method="get" id="my-form"> <!-- have an id (or a name) here -->
<fieldset>
<legend>Informações do utilizador</legend>
<label for="nome">Nome:</label>
<input id="nome" name="nome" type="text" />
<br />
<label for="idade">Idade:</label>
<select id="idade" name="idade">
<option value="menor"><18</option>
<option value="jovem">18-21</option>
<option value="jovemadulto">22-29</option>
<option value="adulto">30-39</option>
<option value="adultoavancado">40-49</option>
<option value="idoso">>=50</option>
</select>
</fieldset>
<fieldset>
<legend>Ideias para tornar um campus mais sustentável</legend>
<label for="mensagem">Mensagem:</label><br />
<textarea id="mensagem" name="mensagem"
rows="10" cols="50" placeholder="Introduza a sua ideia"></textarea>
<br>
<button type="submit"> Enviar </button>
<button type="reset"> Limpar </button>
</fieldset>
</form>

Related

Form: preview button in popup window, submit button without popup window

I have a form and 3 buttons on it: Preview, reset and submit. And I want a new window to pop up when I click on the preview. Unfortunately, it also pops up when I send it
<html lang="cs-cz">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<link rel="stylesheet" href="styly.css">
<form name="submit" method="POST" action="preview.php" id="formID" onsubmit="target_popup(this)" >
<form name="submit" method="POST" action="mailer.php" >
<div class="box">
<h1>ODVOZY</h1>
<p class="info"><input type="text" name="name" class="textfield1" placeholder="Jméno a příjmení"/></p>
<p class="info"><input type="text" name="adress" class="textfield1" placeholder="Adresa"/></p>
<p class="info"><input type="text" name="contact" class="textfield1" placeholder="Kontakt"/></p>
<p class="info"><input type="text" name="model" class="textfield1" placeholder="Typ zboží"/></p>
<p class="info"><input type="datetime-local" name="date" class="textfield1" placeholder="Date"/></p>
<select name="money" class="info1" name="money" method="post">
<option value="Vyber způsob platby">Vyber způsob platby</option>
<option value="Placeno">Placeno</option>
<option value="Platit doma">Platit doma</option>
<option value="Placeno jen odvoz">Placeno jen odvoz</option>
<option value="Jiné (viz poznámky)">Jiné (viz poznámky)</option>
</select>
<select name="city" class="info1" name="city" method="post" >
<option value="Vyber pobočku">Vyber pobočku</option>
<option value="Dvůr Králové n/L">Dvůr Králové n/L</option>
<option value="Hořice">Hořice</option>
</select>
<textarea name="message" class="info1" type="text" cols="20" rows="5"placeholder="Poznámka"></textarea>
<p> </p>
<input type="submit" name="preview" value="Tisk" class="boxa" />
<input type="reset" value="Reset" class="boxc" />
<input type="submit" name="mailer" value="Odeslat" class="boxb" formaction="mailer.php" formmethod="POST" />
<script src="script.js"></script>
</div>
</form> </form>
</body>
</html>
Here is the Javascript, can you please tell me where it is going wrong
var myForm = document.querySelector("#formID");
if(myForm === "#formID" ){
myForm.onsubmit = function() {
var w = window.open('about:blank','Popup_Window','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300,left = 312,top = 234');
this.target = 'Popup_Window';
}
;
Your code is really badly formatted and I see a lot of issues here
</form> </form>
for instance.
BTW you have
<input type="submit" name="preview" value="Tisk" class="boxa" />
<input type="reset" value="Reset" class="boxc" />
<input type="submit" name="mailer" value="Odeslat" class="boxb" formaction="mailer.php" formmethod="POST" />
Do you want to submit the form when you click the preview button?
Otherwise change the type ( input type="button" instead of submit).
Add a function on the click and change the js consequently.
<input type="button" name="preview" onclick="openPopup()">
/// JS
function openPopup(){
var w = window.open('about:blank','...
}

1 button for 2 forms where one of the forms is a <select>

I got 2 forms, one of the forms is a select which can show 2 hidden divs. When one of the options is selected it should send the value to the database. Now the second form is where the button is. When this button is pressed it should submit both forms. I already tried some things, but they don't seem to work. Anyone has an idea?
The first 'main' form:
<form class="areaType" id="formSelect" action="saveData.php" method="POST">
<p>Are you a student showcasing a project or a school institution looking to collaborate?</p>
<select id="textAreaType" onchange="chooseType(this)" name="type">
<option value="0" selected></option>
<option value="1">Student project</option>
<option value="2">School institution project</option>
</select>
</form>
The second (hidden) form:
<form class="textAreas" id="formSchool" action="saveData.php" method="POST">
<div class="fieldsForSquare">
<p>Fill in these fields for your square</p>
</div>
<div class="areaTitle">
<p>Title</p>
<textarea type="text" id="textAreaTitle" name="summary" required></textarea>
</div>
<div class="areaDescription">
<p>Short description</p>
<textarea maxlength="200" type="text" id="textAreaDescription" name="shortSummary" required></textarea>
</div>
<div class="areaPersons">
<p>How many people are you looking for and how big is the team going to be?</p>
<input type="number" maxlength="2"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
id="textAreaPersons" required>
<input type="number" maxlength="2"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
id="textAreaPersons2" required>
</div>
<div class="areaHours">
<p>Is it fulltime or parttime?</p>
<select id="textAreaHours" required>
<option value="0" selected></option>
<option value="1">Fulltime</option>
<option value="2">Parttime</option>
</select>
</div>
<div class="fieldsForPage">
<p>Fill in these fields for your page</p>
</div>
<div class="areaAbout">
<p>What is it about?</p>
<textarea type="text" id="textAreaAbout" required></textarea>
</div>
<div class="areaLookingFor">
<p>What/who are you looking for?</p>
<textarea type="text" id="textAreaLookingFor" required></textarea>
</div>
<div class="areaCollab">
<p>U wish to add other accounts to this project?</p>
<textarea type="text" id="textAreaCollab"></textarea>
</div>
<div class="areaImg">
<p>Add some images of the product/project.</p>
<input id='files' type='file' multiple />
<output id='result' />
</div>
<div class="submitButton">
<input type="submit" value="submit" onclick="submitForms()">
</div>
</form>
The third (hidden) form:
<form class="textAreas" id="formStudent" action="saveData.php" method="POST">
<div class="fieldsForSquare">
<p>Fill in these fields for your square</p>
</div>
<div class="areaTitle">
<p>Title</p>
<textarea type="text" id="textAreaTitleStudent" name="summary" required></textarea>
</div>
<div class="areaDescription">
<p>Short description</p>
<textarea maxlength="200" type="text" id="textAreaDescriptionStudent" name="shortSummary"
required></textarea>
</div>
<div class="fieldsForPage">
<p>Fill in these fields for your page</p>
</div>
<div class="areaAbout">
<p>What is it about?</p>
<textarea type="text" id="textAreaAbout" required></textarea>
</div>
<div class="areaCollab">
<p>U wish to add other accounts to this project?</p>
<textarea type="text" id="textAreaCollab"></textarea>
</div>
<div class="areaImg">
<p>Add some images of the product/project.</p>
<input id='files' type='file' multiple />
<output id='result' />
</div>
<div class="submitButton">
<input type="submit" value="submit" onclick="submitForms_()">
</div>
</form>
The Javascript code for submitting the forms depending on which value is selected:
function submitForms() {
document.getElementById('formSelect').submit();
document.getElementById('formSchool').submit();
}
function submitForms_() {
document.getElementById('formSelect').submit();
document.getElementById('formStudent').submit();
}
the PHP code where it first checks if an option is selected and then (it should) insert it:
<?php
include('../general.config.php');
print_r($_POST);
$summary = $_POST['summary'];
$shortSummary = $_POST['shortSummary'];
$type = $_POST['type'];
if(isset($type)){
$query = $db->prepare("INSERT INTO `project`( `type`, `short_summary`, `summary`) VALUES (?, ?, ?)");
$query->bindPARAM(1,$type, PDO::PARAM_INT);
$query->bindPARAM(2,$shortSummary, PDO::PARAM_STR);
$query->bindPARAM(3,$summary, PDO::PARAM_STR);
if($query->execute())
echo "succes!";
else
echo "NO SUCCES!";
}
?>
chooseType() function:
function chooseType(select) {
if (select.value == 1) {
document.getElementById('mainAddProjectStudentID').style.display = 'block'
document.getElementById('mainAddProjectSchoolID').style.display = 'none'
} else if (select.value == 2) {
document.getElementById('mainAddProjectSchoolID').style.display = 'block'
document.getElementById('mainAddProjectStudentID').style.display = 'none'
} else if (select.value == 0) {
document.getElementById('mainAddProjectSchoolID').style.display = 'none'
document.getElementById('mainAddProjectStudentID').style.display = 'none'
}
}
When no option is selected:
When one of the options is selected:
First thing is you cannot submit two forms with one submit button unless you use ajax. Neither is this the best way to deal with the situation.
I will answer the question in two parts. One where you have three forms and are able to send data from both the forms and then a better way to do this.
Your select option has static values that represent either of the forms. You can simply add a hidden input field to have your form data include the correct type.
<!-- Hidden Input Tag for the formStudent form-->
<input type="hidden" name="type" id="studentType" value="1">
<!-- Hidden Input Tag for the formSchool form-->
<input type="hidden" name="type" id="schoolType" value="2">
Now when either of the forms are submitted your objective of having the type variable populated correctly is met.
One of the right and easier way of doing this would be to use just one form instead of three. You can toggle display of the forms with the select tag, like you are already doing. Use unique names for your fields and in your php script use $type variable to conditionally populate the variables $summary, $shortSummary and $type.
Demonstration (adding just the basic elements)
<form action="saveData.php" method="POST">
<select id="textAreaType" onchange="chooseType(this)" name="type">
<option value="0" selected></option>
<option value="1">Student project</option>
<option value="2">School institution project</option>
</select>
<!-- Student Form> -->
<div id="mainAddProjectStudentID" style="display:none;">
<textarea type="text" id="textAreaTitleStudent" name="studentSummary" required></textarea>
<textarea maxlength="200" type="text" id="textAreaDescriptionStudent" name="studentShortSummary" required></textarea>
</div>
<!-- School Form -->
<div id="mainAddProjectSchoolID" style="display:none;">
<textarea type="text" id="textAreaTitleStudent" name="schoolSummary" required></textarea>
<textarea maxlength="200" type="text" id="textAreaDescriptionStudent" name="schoolShortSummary" required></textarea>
</div>
<!-- Submit Button -->
<input type="submit" value="submit">
</form>
And your php to read the data will be
if(!empty($_POST['type']) && ($_POST['type'] == 1 || $_POST['type'] ==2 )){
$type = $_POST['type'];
$summary = ($type == 1)? $_POST['studentSummary'] : $_POST['schoolSummary'];
$shortSummary = ($type ==1)? $_POST['studentShortSummary'] : $_POST['schoolShortSummary'];
}
This is just one way of doing it, there could be many.

Enable submit button only when all fields are not empty - type > file & select & input

<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script type="text/javascript">
required = function(fields) {
var valid = true;
fields.each(function () { // iterate all
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(":checked")) || // checkbox
(($this.is(':text') || $this.is('textarea')) && !$this.val()) || // text and textarea
($this.is(':radio') && !$('input[name='+ $this.attr("name") +']:checked').length)) { // radio
valid = false;
}
});
return valid;
}
validateRealTime = function () {
var fields = $("form :input:not(:hidden)"); // select required
fields.on('keyup change keypress blur', function () {
if (required(fields)) {
{submit.disabled = false} // action if all valid
} else {
{submit.disabled = true} // action if not valid
}
});
}
validateRealTime();
</script>
<form action="" method="post" id="submitform" />
Title:
<input type="text" name="title">
Select:
<select>
<option value="">aaa</option>
<option value="1">bbb</option>
<option value="2">ccc</option>
</select>
<br/>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br>
Description:
<textarea name="description"></textarea>
<br/>
Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>
<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>
</ul>
<input type="submit" value="Submit Topic" class="button-primary" name="submit" id="submit" disabled="disabled" />
</form>
Hi i want to enable the submit button only when all field are filled specially the select input and the file input here's a working code for the other type except the select and the file type
The code below is doing this
When the text field is empty the submit should be disabled
(disabled="disabled").
When something is typed in the text field to remove the disabled
attribute.
If the text field becomes empty again(the text is deleted) the
submit button should be disabled again.
My aim is to enable submit button only once everything has been filled. How do I do this?
Any ideas? how can i disable the submit button when user is not choosing a file or an option in the form
<form action="" method="post" id="submitform" /> Title:
<input type="text" name="title"> Select:
<select>
<option value="">aaa</option>
<option value="1">bbb</option>
<option value="2">ccc</option>
</select>
<br/>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br> Description:
<textarea name="description"></textarea>
<br/> Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>
<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>
</ul>
<input type="submit" value="Submit Topic" class="button-primary" name="submit" id="submit" disabled="disabled" />
</form>
You closed your form tag
You cannot name or ID anything in a form "submit" - it will stop any future submission by script so get used to not doing it
You COULD just add the required attribute to the fields, then the form would give error when submitted
Here is how to disable in not both text field and textarea have content
$(function() {
$("#submitform").on("input",function() {
const anythingEmpty = $(":input").val().trim() === "";
$("#subBut").prop("disabled",anythingEmpty);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="submitform"> Title:
<input type="text" name="title"> Select:
<select>
<option value="">aaa</option>
<option value="1">bbb</option>
<option value="2">ccc</option>
</select>
<br/>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br> Description:
<textarea name="description"></textarea>
<br/> Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>
<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>
</ul>
<input type="submit" id="subBut" value="Submit Topic" class="button-primary" disabled="disabled" />
</form>
Plain JS
window.addEventListener("load",function() {
document.getElementById("submitform").addEventListener("input",function() {
const desEmpty = this.querySelector("[name=description]").value.trim() === "";
const txtEmpty = this.querySelector("[name=title]").value.trim() === "";
document.getElementById("subBut").disabled = desEmpty || txtEmpty
})
})
If u add id on every input, u can use next js vanilla code, and add onchange function on form.
<head>
<script>
function validate(){
var submit = document.getElementById('submit');
var title = document.getElementById('title').value === ""? false: true;
var file = document.getElementById("myfile").value === ""? false: true;
var val19 = document.getElementById("in-category-19").checked;
var val20 = document.getElementById("in-category-20").checked;
var checked = val19 || val20;
var textArea = document.getElementById("textarea").value===""?false: true;
var filled =(checked && title&& textArea && file);
filled? submit.disabled=false: submit.disabled=true;
}
</script>
</head>
<body><form onchange="validate();" action="" method="post" id="submitform" /> Title:
<input type="text" id="title" name="title"> Select:
<select>
<option value="">aaa</option>
<option value="1">bbb</option>
<option value="2">ccc</option>
</select>
<br/>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br> Description:
<textarea id ="textarea" name="description"></textarea>
<br/> Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">
<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>
<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>
</ul>
<input type="submit" value="Submit Topic" class="button-primary" name="submit" id="submit" disabled=true />
</form>
</body>

Disable form button and field with Javascript

I need to disable some filed and button in a form. The form shows user data and the button "Modifica" allow the user to modify field (username, mail, password). If user is worker can modify also exp and photo field. If user is manager this field are hidden.
I wrote some javascript in order to hide and disable fields but the button "modifica" seems to be blocked and I don't know why.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<div th:replace="header :: header"></div>
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<div id="password-confirm-block">
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
</div>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
Javascript:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirmBlock = document.getElementById("password-confirm-block");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
view();
buttonModifica.addEventListener("click", modify, true);
buttonAnnulla.addEventListener("click", view, true);
}
init();
function modify() {
unlockImputs();
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function view() {
lockImputs();
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.hidden=false;
}
function lockImputs (){
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirmBlock.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
}
function unlockImputs (){
username.readOnly=false;
email.readOnly=false;
password.readOnly=false;
radioManager.disabled=false;
radioWorker.disabled=false;
exp.disabled=false;
photo.disabled=false;
}
If you need to disable the button "Modifica", You can just set "disabled" to true for this button's id:
document.getElementById("buttonModifica").disabled = true;
You can get that HTML_DOM with document object then you can apply event listener on it.
Then get another id to which you want to disable and apply disable property into it
For reference :
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/disabled

Passing variable from script to HTML

I'm sure I must be missing something really silly here, but I can't seem to pass a value from my javascript function to my html form.
I have the following code:
<form class="form">
<p>Potencia a Instalar (Watts)
<br />
<span class="form"><input type="text" name="watts_to_install" value="" size="40" id="watts_to_install" required />
</span>
</p>
<p>Panel a ser utilizado<br />
<span class="form">
<select name="panel" class="form" id="panel">
<option id="Hanwha">Hanwha 250W</option>
<option id="Sharp">Sharp 250W</option>
</select>
</span>
</p>
<button onclick="Process1()">Nivel 1</button>
<span class="form">
<p>Potencia Maxima de Panel</p>
<input type="text" id="max_power" value="">
<br />
<p>Cantidad a Instalar</p>
<input type="text" id="quantity" value="">
</span>
</form>
<script type="text/javascript">
function Process1()
{
var power = document.getElementById('watts_to_install').value;
var panel = document.getElementById('panel').value;
switch(panel)
{
case 'Hanwha':
var power_panel = 250;
var panel_quantity = power/power_panel;
document.getElementById('max_power').value = power_panel;
document.getElementById('quantity').value= panel_quantity;
break;
case 'Sharp':
break;
}
}
</script>
The problem is that the page loads and...nothing happends. I see the information in my URL but nothing else. I tried passing it using .innerHTML instead of .value but it was to no avail. I know I must be missing something really easy but I just can't seem to find it.
You need to replace id with value on your option tags:
function Process1() {
var power = document.getElementById('watts_to_install').value;
var panel = document.getElementById('panel').value;
switch (panel) {
case 'Hanwha':
var power_panel = 250;
var panel_quantity = power / power_panel;
document.getElementById('max_power').value = power_panel;
document.getElementById('quantity').value = panel_quantity;
break;
case 'Sharp':
break;
}
}
<form class="form">
<p>Potencia a Instalar (Watts)
<br />
<span class="form"><input type="text" name="watts_to_install" value="" size="40" id="watts_to_install" required /></span>
</p>
<p>Panel a ser utilizado
<br />
<span class="form"><select name="panel" class="form" id="panel">
<option value="Hanwha">Hanwha 250W</option>
<option value="Sharp">Sharp 250W</option>
</select></span>
</p>
<button onclick="Process1()">Nivel 1</button>
<span class="form">
<p>Potencia Maxima de Panel</p>
<input type="text" id="max_power" value="">
<br />
<p>Cantidad a Instalar</p>
<input type="text" id="quantity" value="">
</span>
</form>

Categories