Input error in PHP file - javascript

I am trying to hide a form based on a button click. Below is my code:
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio PHP
</title>
<style>
#mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="button()">Inserisci studente</button>
<div id="mybutton">
<div>
<input type="hidden" name="action" value="submit"> Nome Studente:<br>
<input name="Nome" type="text" value="" placeholder="Inserisci il
nome dello studente" size="30" /><br> Cognome Studente:<br>
<input name="Cognome" type="text" value="" placeholder="Inserisci
il cognome dello studente" size="30" /><br> Eta Studente:<br>
<input name="Eta" type="integer" value="" placeholder="Inserisci
l'età dello studente" size="30" /><br>
<input type="submit" name="insert" value="Inserisci" />
</div>
</div>
<br><br><br>
<button onclick="button()">Aggiorna nome</button>
<div id="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<div>
<input type="hidden" name="action" value="submit"> Nuovo Nome:<br>
<input name="NewName" type="text" value="" placeholder="Inserisci il
nuovo nome" size="30" /><br> Vecchio Nome:<br>
<input name="OldName" type="text" value="" placeholder="Inserisci il
nome attuale" size="30" /><br>
<input type="submit" name="insert" value="Aggiornare" />
</div>
</div>
<script>
function button() {
var x = document.getElementById('mybutton');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>
When the first button is clicked, everything works as expected, but in the second case when I press the button "Aggiorna nome", the form doesn't hide.
Why does the first button work and the second does not?

There are a few issues with the code:
1) Same ID for 2 different elements ('mybutton').
2) The form tags are not closed properly, so the button submit the form.
Here I fixed up your code so it works:
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
.mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top:20px;
}
</style>
</head>
<body>
<button data-id="first-div" onclick="button(this)">Inserisci studente</button>
<div id= "first-div" class="mybutton">
<form action = "DatabaseManagerMySQL.php?operation_type = insert" method
= "POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nome Studente:<br>
<input name = "Nome" type = "text" value = "" placeholder="Inserisci il
nome dello studente" size = "30"/><br>
Cognome Studente:<br>
<input name = "Cognome" type = "text" value = "" placeholder="Inserisci
il cognome dello studente" size = "30"/><br>
Eta Studente:<br>
<input name = "Eta" type = "integer" value = "" placeholder="Inserisci
l'età dello studente" size = "30"/><br>
<input type= "submit" name = "insert" value = "Inserisci"/>
</form>
</div>
<br><br><br>
<button data-id="second-div" onclick = "button(this)">Aggiorna nome</button>
<div id = "second-div" class="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action = "DatabaseManagerMySQL.php?operation_type = update" method =
"POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nuovo Nome:<br>
<input name = "NewName" type = "text" value = "" placeholder="Inserisci il
nuovo nome" size = "30"/><br>
Vecchio Nome:<br>
<input name = "OldName" type = "text" value = "" placeholder="Inserisci il
nome attuale" size = "30"/><br>
<input type= "submit" name = "insert" value = "Aggiornare"/>
</form>
</div>
<script>
function button(obj) {
var divId = obj.getAttribute("data-id");
var x = document.getElementById(divId);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
What i did is to use a class instead of an Id for your elements and add the data-id to the button so the JS functions receives the element's id and knows what element should hide or whatever you like to do.

The default behaviour for button elements is to submit the form they are placed in.
To prevent this behaviour, you can add the type="button" attribute to your button. This way your javascript code will be executed.
<button type="button" onclick="button()">Aggiorna nome</button>

Don't use many IDs with same value
https://www.w3.org/TR/html5/dom.html#the-id-attribute The id attribute
specifies its element's unique identifier (ID). The value must be
unique amongst all the IDs in the element's home subtree and must
contain at least one character. The value must not contain any space
characters.
Use class instead.
Check your IDE, it seems that it adds spaces before and after "=" inadequately. I bet there shouldn't be any spaces in "DatabaseManagerMySQL.php?operation_type = insert"
Answer:
You didn't close the first <form> tag, that's why first button (the "Aggiorna nome" one) in that form acts like sumbit button (behaviour by default) and submits to "DatabaseManagerMySQL.php?operation_type = insert"

In your code have some problem
1. you missing </form> // close form tag in both form
2. you use same id in main content div so it will not work
3. you use same id in your javascript function so next form will not work
so need to fixed
so fixed close tag, use 2 id and send this id in onclick button function id name so one function will fixed issue
function button(form_div) {
var x = document.getElementById(form_div);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
#mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="button('mybutton1')" type="button">Inserisci studente</button>
<div id="mybutton1">
<form action="DatabaseManagerMySQL.php?operation_type = insert" method
="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
Nome Studente:<br>
<input name="Nome" type="text" value="" placeholder="Inserisci il
nome dello studente" size="30"/><br>
Cognome Studente:<br>
<input name="Cognome" type="text" value="" placeholder="Inserisci
il cognome dello studente" size="30"/><br>
Eta Studente:<br>
<input name="Eta" type="integer" value="" placeholder="Inserisci
l'età dello studente" size="30"/><br>
<input type="submit" name="insert" value="Inserisci"/>
</form>
</div>
<br><br><br>
<button onclick="button('mybutton2')" type="button">Aggiorna nome</button>
<div id="mybutton2">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action="DatabaseManagerMySQL.php?operation_type = update" method=
"POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
Nuovo Nome:<br>
<input name="NewName" type="text" value="" placeholder="Inserisci il
nuovo nome" size="30"/><br>
Vecchio Nome:<br>
<input name="OldName" type="text" value="" placeholder="Inserisci il
nome attuale" size="30"/><br>
<input type="submit" name="insert" value="Aggiornare"/>
</form>
</div>
</body>
</html>

A quick solution would be to simply create a separate javascript function making sure the Div ids are different. The below code is similar to the one posted but (i) include a new javascript function and (2) new Div ids.
This code enables to have two buttons to hide the divs.
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
.mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top:20px;
}
</style>
</head>
<body>
<button onclick="button()">Inserisci studente</button>
<div id= "mybutton" class="mybutton">
<form action = "DatabaseManagerMySQL.php?operation_type = insert" method
= "POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nome Studente:<br>
<input name = "Nome" type = "text" value = "" placeholder="Inserisci il
nome dello studente" size = "30"/><br>
Cognome Studente:<br>
<input name = "Cognome" type = "text" value = "" placeholder="Inserisci
il cognome dello studente" size = "30"/><br>
Eta Studente:<br>
<input name = "Eta" type = "integer" value = "" placeholder="Inserisci
l'et? dello studente" size = "30"/><br>
<input type= "submit" name = "insert" value = "Inserisci"/>
</div>
<br><br><br>
<button onclick="button2();">Aggiorna nome</button>
<div id = "mybutton2" class="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action = "DatabaseManagerMySQL.php?operation_type = update" method =
"POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nuovo Nome:<br>
<input name = "NewName" type = "text" value = "" placeholder="Inserisci il
nuovo nome" size = "30"/><br>
Vecchio Nome:<br>
<input name = "OldName" type = "text" value = "" placeholder="Inserisci il
nome attuale" size = "30"/><br>
<input type= "submit" name = "insert" value = "Aggiornare"/>
</div>
<script>
function button() {
var x = document.getElementById('mybutton');
if (x.style.display === 'none') {
x.style.display = 'block';
}else{
x.style.display = 'none';
}
}
function button2() {
var x = document.getElementById('mybutton2');
if (x.style.display === 'none') {
x.style.display = 'block';
}else{
x.style.display = 'none';
}
}
</script>
</body>
</html>

Related

Cannot change the border color of child elements of a form during the loading of the page

window.onload{
var form = document.getElementById("contact").childNodes;
for (let i=0; i<form.length;i++){
form[i].style.border = "2px solid red";
}
}
<form id="contact">
<p>Votre nom : </p><input type="text"><br />
<p>Votre Prénom : </p><input type="text"><br />
<p>Votre e-mail : </p><input type="email"><br />
<p>Votre numéro de téléphone : </p><input type="tel"><br />
<p>Décrivez votre projet : </p><textarea></textarea><br />
<p> </p><input type="submit" id="bouton_valider" value="Valider" />
</form>
I am trying to change the border color of every child elements of a form. But it doesn't work and I do not understand why.
What I believe you are trying to do is highlight all the input elements to red.
Your code has the following bugs:
The syntax for window.onload is incorrect, which is a function.
Read more: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
The statement: var form = document.getElementById("contact").childNodes; will give you all the child nodes and not only the nodes that you want to set their border. This is basically a NodeList Array with values of all nodes, which might be element or text nodes.
Refer: https://javascript.info/basic-dom-node-properties
I have fixed your code and here is the working snippet.
Hope this helps :)
window.onload = function() {
var form = document.getElementById("contact");
var inputList = form.getElementsByTagName('input')
for (let i = 0; i < inputList.length; i++) {
form[i].style.border = "2px solid red";
}
}
<form id="contact">
<p>Votre nom : </p><input type="text"><br />
<p>Votre Prénom : </p><input type="text"><br />
<p>Votre e-mail : </p><input type="email"><br />
<p>Votre numéro de téléphone : </p><input type="tel"><br />
<p>Décrivez votre projet : </p><textarea></textarea><br />
<p> </p><input type="submit" id="bouton_valider" value="Valider" />
</form>
Not all elements in your array have a style property, so make sure to check for it before applying :)
var form = document.getElementById("contact").childNodes;
for (let i=0; i<form.length;i++){
if (form[i].style) {
form[i].style.border = "2px solid red";
}
}
You should write your function like this
window.addEventListener("load", function(){
var form = document.getElementById("contact").childNodes;
for (let i=0; i<form.length;i++){
if(form[i].style){
form[i].style.border = "2px solid red";
}
}
})
<form id="contact">
<p>Votre nom : </p><input type="text"><br />
<p>Votre Prénom : </p><input type="text"><br />
<p>Votre e-mail : </p><input type="email"><br />
<p>Votre numéro de téléphone : </p><input type="tel"><br />
<p>Décrivez votre projet : </p><textarea></textarea><br />
<p> </p><input type="submit" id="bouton_valider" value="Valider" />
</form>

Dynamic form for submit values

I'm creating a simple form that allows you to enter data that will then be sent to a DB. In particular I need to know from you how I can create a dynamic form that allows me to enter a number of people specified by the user. Basically if the user wants to add 3 people must present 3 new fields to enter Name, Surname and email, if he wants to add 5, 5 new fields.
I write this, but in my index.php it doesn't work.
// Funzione che permette di aggiungere elementi al form (in questo caso rate)
function Aggiungipersone(person) {
var numero_persone = person.value;
var box = document.getElementById('box_person');
if (numero_persone == "") {
box.innerHTML = '';
} else {
if (isNaN(numero_persone) == true) {
box.innerHTML = '';
} else {
var righe = "";
// Inserisco una riga ad ogni ciclo
for (i = 1; i <= numero_persone; i++) {
righe = righe + "Persona n°" + i + " : <input type='text' name='iname" + i + " size='10' value='" + Cognome + "' type='text' name='isurname' size='10' value=''/><br/>";
}
// Aggiorno il contenuto del box che conterrà gli elementi aggiunti
box.innerHTML = righe;
}
}
}
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br> Nome:
<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br> Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
UPDATE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="utils.js"></script>
</head>
<body>
<?php
$( document ).ready(function() {
$("#add").click(function(){
var val1 =$("#n1").val();
for(var i=0;i<val1;i++){
$("#start").append($("#first").clone());
}
});
});
?>
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nome:<input type="text" name="name" size="20"><br>
Cognome:<input type="text" name="surname" size="20"><br>
Email: <input type="email" name="email" size="20"><br>
Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
</body>
</html>
In the utilis.js i inserted:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br>
<br>
</div>
</div>
// content of external javascript file:
$(document).ready(function() {
$("#add").click(function(e) {
e.preventDefault(); // stop the link
var val1 = $("#n1").val();
for (var i = 0; i < val1; i++) {
$("#start").append($("#first").clone());
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- here is the external file -->
<script src="utils.js"></script>
</head>
<body>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name[]" size="20"><br> Cognome:
<input type="text" name="surname[]" size="20"><br> Email: <input type="email" name="email[]" size="20"><br>
<br>
</div>
</div>
</body>
</html>
once you submit form then you will get array into php file and you can access like this
if($_POST['name']){ foreach($_POST['name'] as $name) { echo $name; } }
1) With VueJS - demo on code pen
2) JQuery
const tmpl = $('#tmpl').html().trim()
$('#btn-add').click(() => {
let peopleCount = +$('#people-count').val(),
html = Array(peopleCount)
.fill(tmpl)
.join('')
$('#form-items').append(html)
})
$('#form')
.submit(() => {
alert('Submit form by ajax or remove this mathod for default behavior')
return false;
})
.delegate('.btn-del', {
click() {
$(this).closest('.row').remove()
},
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
you will need something like this:
$("#people").on("keyup", function() {
$("#form").html(""); // clear the form
var people = $(this).val();
for(i=1;i<=people;i++) {
$("#form").append("<input type='text' name='name[]' placeholder='Name Person "+i+"'><br>");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Number of People:</label>
<input type="number" id="people">
<div id="form"></div>
as you see the input names are with [] which means they are arrays.. That means on your server side script you will recieve an array where you have to go through via
foreach($_POST["names"] as $name) {
// do whatever
}

Using DOM to create an input

I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)

Uncaught TypeError: Cannot read property 'appendChild' of null. Can't find the error in my code

So, first, I'm not done with my code.However, the following Javascript part is suppose to change the site language when an image is clicked. I read ( on other post here) that it could be because the whole html document has not finished loading? Anyway, here's my code: hope I can get some insight on what causes the error:
<DOCTYPE! html>
<html>
<head>
<title> Registration</title>
<link type="text/css" rel="stylesheet" href="stylesheetex3.css"/>
<script>
function changeLanguage()
{
document.getElementById("z").addEventListener("click");
var Username1= document.getElementById("User");
var Password1= document.getElementById("Pass");
var Retype1= document.getElementById("Pass2");
var Firstname1= document.getElementById("First");
var Middlename1= document.getElementById("Second");
var LastName1= document.getElementById("Third");
var email1 = document.getElementById("at");
var NomUtilisateur1 = document.createTextNode("Nom D'utilisateur");
var mdp1 = document.createTextNode("Mot de Passe");
var mdp21 = document.createTextNode("Verification du mot de passe");
var Prenom1 = document.createTextNode("Prenom");
var Prenom2 = document.createTextNode("Deuxieme prenom");
var NomdeFamilly1 = document.createTextNode("Nom de Famille");
var Email1 = document.createTextNode("Addresse courielle");
Username1.appendChild(NomUtilisateur1);
Password1.appendChild(mdp1);
Retype1.appendChild(mdp21);
Firstname1.appendChild(Prenom1);
Middlename1.appendChild(Prenom2);
LastName1.appendChild(NomdeFamilly1);
email1.appendChild(Email1);
}
</script>
</head>
<body>
<h1>Registration Form</h1>
<div>
<div>please fill out the form below</div>
<div class="Img">
<img id="z" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRR2pntKihP8gow1vBejsXhgYmHDctgwjcXKWKk9y0PEXsXEbUxpELQ" onClick="changeLanguage()" />
</div>
<form>
<fieldset>
<legend id="login"> Login Details </legend>
<p>Username* <input type="text" name="Username" id="User"></p>
<p>Password* <input type="Password" name="Password" id="Pass"></input</p>
<p>Retype Password*<input type="Password" name="RetypePassword" onChange="checkPasswordMatch();" id="Pass2"></input></p>
</fieldset>
<fieldset>
<legend>User Data</legend>
<p>Firstname* <input type="text" name="firstName"></input id="First"></p>
<p>Middlename*<input type="text" name="middleName" id="Second"></input></p>
<p>LastName*<input type="text" name="lastName" id="Third"></input></p>
<p>Email*<input type="email" name="email" id="at"> </input></p>
</fieldset>
<input type="submit" value="Submit"></input>
</form>
</div>
</body>
You have syntax error in <input type="text" name="firstName"></input id="First">
Also, you can't append children to input element, instead you can insert them as its sibling
function changeLanguage() {
document.getElementById("z").addEventListener("click");
var Username1 = document.getElementById("User");
var Password1 = document.getElementById("Pass");
var Retype1 = document.getElementById("Pass2");
var Firstname1 = document.getElementById("First");
var Middlename1 = document.getElementById("Second");
var LastName1 = document.getElementById("Third");
var email1 = document.getElementById("at");
var NomUtilisateur1 = document.createTextNode("Nom D'utilisateur");
var mdp1 = document.createTextNode("Mot de Passe");
var mdp21 = document.createTextNode("Verification du mot de passe");
var Prenom1 = document.createTextNode("Prenom");
var Prenom2 = document.createTextNode("Deuxieme prenom");
var NomdeFamilly1 = document.createTextNode("Nom de Famille");
var Email1 = document.createTextNode("Addresse courielle");
insertAfter(NomUtilisateur1, Username1);
insertAfter(mdp1, Password1);
insertAfter(mdp21, Retype1);
insertAfter(Prenom1, Firstname1);
insertAfter(Prenom2, Middlename1);
insertAfter(NomdeFamilly1, LastName1);
insertAfter(Email1, email1);
}
function insertAfter(node, anchor){
if(anchor.nextSibling){
anchor.parentNode.insertBefore(node, anchor.nextSibling);
}else{
anchor.parentNode.appendChild(node);
}
}
<h1>Registration Form</h1>
<div>
<div>please fill out the form below</div>
<div class="Img">
<img id="z" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRR2pntKihP8gow1vBejsXhgYmHDctgwjcXKWKk9y0PEXsXEbUxpELQ" onClick="changeLanguage()" />
</div>
<form>
<fieldset>
<legend id="login">Login Details</legend>
<p>Username*
<input type="text" name="Username" id="User" />
</p>
<p>Password*
<input type="Password" name="Password" id="Pass" />
</p>
<p>Retype Password*
<input type="Password" name="RetypePassword" onChange="checkPasswordMatch();" id="Pass2"/>
</p>
</fieldset>
<fieldset>
<legend>User Data</legend>
<p>Firstname*
<input type="text" name="firstName" id="First" />
</p>
<p>Middlename*
<input type="text" name="middleName" id="Second" />
</p>
<p>LastName*
<input type="text" name="lastName" id="Third" />
</p>
<p>Email*
<input type="email" name="email" id="at" />
</p>
</fieldset>
<input type="submit" value="Submit" />
</form>
</div>
Note: Input element's don't have closing tags

Combining javascript functions

hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/

Categories