How to add new data into XML - javascript

register.htm
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<script type="text/javascript" src="shoponline.js"></script>
<title>ShopOnline Register Page</title>
</head>
<body>
<H3>ShopOnline</H3>
<table width="100%">
<tr>
<td><button class="button" name="btnHome" value="Home" onclick="location.href='login.htm';">Home</button></td>
<td><button class="button" name="btnListing" value="Listing" onclick="location.href='listing.htm';">Listing</button></td>
<td><button class="button" name="btnBidding" value="Bidding" onclick="location.href='bidding.htm';">Bidding</button></td>
<td><button class="button" name="btnMaintenance" value="Maintenance" onclick="location.href='maintenance.htm';">Maintenance</button></td>
<td><button class="button" name="btnLogout" value="Logout" onclick="location.href='#';">Log Out</button></td>
</tr>
</table>
<hr><br><br>
<I>To register a new account with ShipOnline, please complete the registration form below.</I>
<br><br>
<form>
<div class="form">
<fieldset>
<legend>Registration Details</legend>
<p style="text-align:left;">* Required Fields</p>
<br>
<table>
<tr>
<td style="text-align:right;">First Name <label>*</label></td>
<td><input type="text" id="txtFName" name="txtFName" class="textbox" placeholder="Enter Your First Name"
oninvalid="this.setCustomValidity('Please Enter Your First Name!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Surname <label>*</label></td>
<td><input type="text" id="txtSurname" name="txtSurname" class="textbox" placeholder="Enter Your Surname"
oninvalid="this.setCustomValidity('Please Enter Your Surname!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Email <label>*</label></td>
<td><input type="email" id="txtEmail" name="txtEmail" class="textbox" placeholder="Enter Your Email Address"
oninvalid="this.setCustomValidity('Please Enter Your Email!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" name="btnRegister" value="Register" onclick="register()" />
<input type="button" name="btnReset" value="Reset" onclick="reset('registerForm')" />
</td>
</tr>
</table>
</fieldset>
</div>
<form>
<div id="information"></div>
</body>
</HTML>
shoponline.js
var xHRObject = false;
if (window.XMLHttpRequest)
xHRObject = new XMLHttpRequest();
else if (window.ActiveXObject)
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
function reset(formID) {
switch (formID) {
case 'loginForm':
document.getElementById('txtEmail').value = "";
document.getElementById('txtPassword').value = "";
break;
case 'registerForm':
document.getElementById('txtFName').value = "";
document.getElementById('txtSurname').value = "";
document.getElementById('txtEmail').value = "";
break;
}
}
function login() {
var email = document.getElementById('txtEmail').value;
var pass = document.getElementById('txtPassword').value;
xHRObject.open("GET", "login.php?id=" + Number(new Date) + "&email=" + email + "&pass=" + pass, false);
xHRObject.send();
if (xHRObject.responseText == true)
document.location.href = "bidding.htm";
else
window.alert("Login Failure!");
}
function register() {
var isFound = false;
var email = document.getElementById('txtEmail').value;
var firstName = document.getElementById('txtFName').value;
var surName = document.getElementById('txtSurname').value;
xHRObject.open("GET", "register.php?id=" + Number(new Date) + "&email=" + email + "&firstName=" + firstName + "&surName=" + surName, false);
xHRObject.send();
if (xHRObject.responseText == true)
window.alert("Registration Failure!");
else
window.alert("Registration Success!");
}
customer.xml
<customers>
<customer>
<ID>C1</ID>
<FirstName>Jack</FirstName>
<SurName>Wong</SurName>
<Email>jack#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C2</ID>
<FirstName>Ashley</FirstName>
<SurName>Rachael</SurName>
<Email>ashley#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C3</ID>
<FirstName>Vongola</FirstName>
<SurName>Steve</SurName>
<Email>vongola#hotmail.com</Email>
<Password>081292</Password>
</customer>
</customers>
register.php
<?php
$xmlFile = "customer.xml";
$isFound = false;
$count = 0;
// Check the XML is exist or not.
// If does, do checking against the email address.
if (file_exists($xmlFile)) {
$dom = new DOMDocument();
$dom->load($xmlFile);
$customer = $dom->getElementsByTagName("customer");
foreach($customer as $node) {
$fName = $node->getElementsByTagName("FirstName");
$valueFName = $fName->item(0)->nodeValue;
$email = $node->getElementsByTagName("Email");
$valueEmail = $email->item(0)->nodeValue;
if($_GET["email"] == $valueEmail)
$GLOBALS["isFound"] = true;
$GLOBALS["count"]++;
}
if ($isFound != true) {
// UNIQUE EMAIL, START UPDATE XML & SEND MAIL
$firstName = $_GET["firstName"];
$surName = $_GET["surName"];
$email = $_GET["email"];
$password = random_password(8);
$xml = new SimpleXMLElement($xmlFile);
$customer = $xml->addChild("customer");
$customer->addChild("ID", "C" .($count + 1));
$customer->addChild("FirstName", $firstName);
$customer->addChild("SurName", $surName);
$customer->addChild("Email", $email);
$customer->addChild("Password", $password);
$xml->saveXML($xmlFile);
}
} else {
// XML FILES NOT EXIST. STRAIGHT AWAY CREATE A NEW ONE AND SEND EMAIL
}
ECHO ($isFound);
?>
Basically, I was used AJAX for server and client communication.
Therefore, when end-users finish input their information at register.htm and it will go to javascript file using XMLHttpsRequest.open to register.php for updating data on XML.
But it doesn't update my XML data.
Any advise will be appreciate.

Related

Need preview page before send email [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My email sending script send email after submitting the form.Form data are directly sent to receiver email address after clicking submit button, but I need preview page which will show preview of form data before sending email. Here form action is controlled by javascript file workMail.js and action page is sendMail.php
Thanks for any help.
Here is my code
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<script src="http://unnayannews.com/testjs/jquery_003.js"></script>
<script src="js/workMail.js"></script>
<link rel="stylesheet" type="text/css" href="css/mailAlert.css">
</head>
<body style="margin: 0px;">
<div class="onedari_form_wrapper info_form_wrapper ajast_onedari_form mgt0">
<form id="contactForm">
<div class="form_field">
<label id="name">■Name<span class="red">*</span></label>
<input kl_virtual_keyboard_secure_input="on" placeholder="Name" class="custom_input" name="name" type="text" required>
</div>
<div class="form_field">
<label id="mail">■Email<span class="red">*</span></label>
<input kl_virtual_keyboard_secure_input="on" class="custom_input" name="mail" type="text" required>
</div>
<div class="form_field">
<label id="age">■Age<span class="red">*</span></label><br>
<input kl_virtual_keyboard_secure_input="on" style="width: 30%" placeholder="" class="custom_input" name="age" type="text" required>
</div>
<p style="margin: 0px 0px 8px;"><label id="work">■Work<span class="red">*</span></label></p>
<div class="category-wrapper">
<input id="CategoryCategory10" class="checkbox" value="10" name="data[]" type="checkbox" >
<label for="CategoryCategory10">App development</label>
<br> <input id="CategoryCategory209" class="checkbox" value="209" name="data[]" type="checkbox"> <label for="CategoryCategory209">System management</label>
<br>
<input id="CategoryCategory213" class="checkbox" value="213" name="data[]" type="checkbox"> <label for="CategoryCategory213">Web</label><br>
<input id="CategoryCategory19" class="checkbox" value="19" name="data[]" type="checkbox"> <label for="CategoryCategory19">Graphics</label><br>
<br>
<button id="send" class="submit bg_red" type="button" name="send">Submit</button>
</form>
</div>
</body>
</html>
sendMail.php
<?php
if( isset($_POST['data']) && is_array($_POST['data']) ) {
foreach($_POST['data'] as $data) { }
$datatList = implode(', ', $_POST['data']);
}
$send_for_address = "test#email.com";
$header = "From: test#email.com";
$messages = "Name: $_POST[name]\n";
$messages .= "Email: $_POST[mail]\n";
$messages .= "Age : $_POST[age]\n";
$messages .= "Work $datatList\n";
mail($send_for_address, $messages,$header);
mb_internal_encoding("UTF-8");
if (mail($send_for_address, $messages,$header)) {
$response = <<<HTML
<div class='alert'>
<div class='alert-header'><div class="alert-remove layerOff">×</div></div>
<div class="alert-body fs0_7">
Thank you for your applicaion!
</div>
<div class="alert-footer">
<input type="button" value="OK" class="layerOff">
</div>
</div>
HTML;
echo json_encode(array("success"=>true, "message"=> $response));
}else{}
?>
workMail.js
$(function(){
// sendForm
$("#send").on("click", function(e){
e.preventDefault();
chackError("#contactForm");
});
$(document).on("click", ".layerOff", function(){
$(".overlay").remove();
});
});
function chackError(selector){
var $form = $(selector);
var name = $form.find("input[name='name']").val();
var mail = $form.find("input[name='mail']").val();
var age = $form.find("input[name='age']").val();
/*var work = $form.find("textarea[name='work']").val();*/
var dataval = document.getElementsByName("data[]");
// or document.querySelectorAll('[name="summer[]"]');
var checked = [].filter.call( dataval , function( v ){
return v.checked;
});
$form.find(".coution").remove();
var error_frag = false;
if ( checked.length < 1 ) {
$("#work").append("<span class='coution'><br>Work field reqire</span>");
error_frag = true;
error_kind = "#work";
}
if(age == ""){
$("#age").append("<span class='coution'><br>Age field reqire</span>");
error_frag = true;
error_kind = "#age";
}
if(mail == ""){
$("#mail").append("<span class='coution'><br>email field reqire</span>");
error_frag = true;
error_kind = "#mail";
}
if(name == ""){
$("#name").append("<span class='coution'><br>Name field reqire</span>");
error_frag = true;
error_kind = "#name";
}
if(error_frag === false){
sendForm();
}else{
var targetY = $(error_kind).offset().top;
var headerH = $("#header").height();
var ajast = ($(window).width() >= 761)? 80 : 20;
$("html, body").animate({ scrollTop: targetY - headerH - ajast}, 'fast');
}
}
function sendForm(){
var post_data = $("#contactForm").serialize();
$("#contactForm").find("input, checkbox, textarea").val("").end().find(":checked").prop("checked", false);
$.post("sendMail.php",
post_data,
function(data){
if(data.success === false){
alert("error");
$(".overlay").remove();
}else{
$("body").append("<div class='overlay'></div>");
$(".overlay").html(data.message);
$("html, body").animate({ scrollTop: 0}, 'fast');
}
},
"json"
);
return false;
}
Further to my comment, what I mean by splitting up the sendMail.php (you will, of course, have to modify your main page javascript to accommodate a confirm response from your sendMail.php):
if(isset($_POST['data']) && is_array($_POST['data']) ) {
foreach($_POST['data'] as $data) { }
$datatList = implode(', ', $_POST['data']);
}
else
$datatList = $_POST['data'];
if(!isset($_POST['confirm'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['mail']);
$age = preg_replace('/[^0-9]/','',$_POST['age']);
$data = strip_tags($datatList);
$response = '
<h2>Preview</h2>
<table>
<tr>
<td>NAME:</td><td>'.$name.'</td>
</tr>
<tr>
<td>EMAIL:</td><td>'.$email.'</td>
</tr>
<tr>
<td>AGE:</td><td>'.$age.'</td>
</tr>
<tr>
<td>DATA:</td><td>'.$data.'</td>
</tr>
<tr>
<td colspan="2">
<form id="confirm" method="post" action="">
<input type="hidden" name="name" value="'.$name.'" />
<input type="hidden" name="mail" value="'.$email.'" />
<input type="hidden" name="age" value="'.$age.'" />
<input type="hidden" name="data" value="'.$data.'" />
<input type="submit" name="confirm" value="Confirm" />
</form>
</td>
</tr>
</table>';
echo json_encode(array("confirm"=>true, "message"=> $response));
}
else {
$send_for_address = "test#email.com";
$header = "From: test#email.com";
$messages = "Name: $_POST[name]\n";
$messages .= "Email: $_POST[mail]\n";
$messages .= "Age : $_POST[age]\n";
$messages .= "Work $datatList\n";
mail($send_for_address, $messages,$header);
mb_internal_encoding("UTF-8");
if (mail($send_for_address, $messages,$header)) {
$response = <<<HTML
<div class='alert'>
<div class='alert-header'><div class="alert-remove layerOff">×</div></div>
<div class="alert-body fs0_7">
Thank you for your applicaion!
</div>
<div class="alert-footer">
<input type="button" value="OK" class="layerOff">
</div>
</div>
HTML;
echo json_encode(array("success"=>true, "message"=> $response));
}
}

Using AJAX to pass variable to PHP and get that variabel again

I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);

Addition-based Captcha fails to check after one ALERT message

I have added a random number addition captcha to a form. The form fields are validated separately. What seems to happen is that if the captcha is blank (alert windows generated and OK button pushed) the form seems to submit anyway. Or if the captch answer is blank, the alert is generated, but clicking the Okay button submits the form.
Basically once there's a wrong captcha but all the required fields validate, the captcha doesn't really stop anything.
Random number generation is being called on the BODY, Validation is being called on the FORM line. Captcha validation is on the SUBMIT button.
I have searched for other solutions, but nothing is helping. I have also tried generating the error message like the code in the answer boxes, but that didn't help. I've simplified the page somewhat here for fewer form fields and text. Form location and email also removed.
Your help would be so appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="resource-type" content="document">
</head>
<!-- numbers generated for captcha -->
<body onLoad="randomNums();">
<!-- validation of form fields in form statement below -->
<form action="location/formemail.bml" method="get" name="contact_form" onsubmit="return Validate()">
<input type="hidden" name="my_email" value="removed" />
<input type="hidden" name="subject" value="Reservation Request Form" />
<input type="hidden" name="order" value="name,email,confirm_email,Number_Of_Adults,Number_Of_Children" />
<input type="hidden" name="thankyou_url" value="thanks-for-your-inquiry.html" />
<input type=hidden name="print_blank_fields" value="0">
<input name="required" type="hidden" value="name,email,confirm_email,Number_Of_Adults,Number_Of_Children" />
<center>
<table BORDER CELLSPACING=2 CELLPADDING=2 WIDTH="100%" >
<tr>
<td>FIRST NAME and LAST NAME<span class="style2">*</span></td>
<td><input type="text" name="name" onKeyUp="CheckForBlank('name')" onBlur="CheckForBlank('name')" title="Enter your name!" placeholder="Full Name" onClick="select()" required /> </td>
</tr>
<tr>
<td>EMAIL ADDRESS<span class="style2">*</span></td>
<td><input type="text" name="email" onKeyUp="CheckForBlank('email')" onBlur="CheckForBlank('email')" title="Enter a valid email address!" placeholder="me#example.com" onClick="select()" required="required" /> </td>
</tr>
<tr>
<td>Confirm EMAIL ADDRESS<span class="style2">*</span></td>
<tr>
<td>NUMBER OF ADULTS<span class="style2">*</span></td>
<td><select NAME="Number_Of_Adults" onkeyup="CheckForBlank('Number_Of_Adults')" onBlur="CheckForBlank('Number_Of_Adults')" title="Enter # Adults" 0nclick="select()" required /><option VALUE="" selected><option VALUE="1-adult">ONE</option><option VALUE="2-adults">TWO</option><option VALUE="3-adults">THREE</option><option VALUE="4-adults">FOUR</option><option VALUE="5-adults">FIVE</option><option VALUE="6-adults">SIX</option></select></td>
</tr>
<tr>
<td>NUMBER OF CHILDREN<span class="style2">*</span></td>
<td><select NAME="Number_Of_Children" onkeyup="CheckForBlank('Number_Of_Children')" onBlur="CheckForBlank('Number_Of_Children')" title="Enter # Children" 0nclick="select()" required /><option VALUE="NONE" selected><option VALUE="No Children">NONE</option><option VALUE="1-child">ONE</option><option VALUE="2-children">TWO</option><option VALUE="3-children">THREE</option><option VALUE="4-children">FOUR</option><option VALUE="5-children">FIVE</option><option VALUE="6-children">SIX</option></select></td>
</tr>
</table>
<center><table WIDTH="75%">
<tr>
<td>
<fieldset>
<label id="error"> </label>
<!-- Here is the captcha area. Onclick tests numbers.
I believe it's here my problem occurs, but I don't know
how to force the addNums to reloop when there's alert -->
<div id="test-it"><strong>Add these numbers, enter in box below, and submit</strong><div id="digit1"></div><div id="plus">+</div><div id="digit2"></div></div>
<div id="buttons"><input type="text" id="answer" />
<input type="submit" value="Answer at left? Click to Submit" onClick="addNums()"/> <input type="reset" value="Reset Form" /></div>
<div id="status"></div>
</fieldset>
</td></tr>
</table>
</center>
</form>
<script>
var CheckForBlank = function (name) {
var x = document.forms['contact_form'].elements[name].value;
var temp = '';
for(i=0;i<x.length;i++){
temp = x.replace(/ /g,' ');
x = temp;
}
if(temp == ' ' || temp == ' ') temp = '';
document.forms['contact_form'].elements[name].value = temp;
if(temp == '') {
document.forms['contact_form'].elements[name].focus();
document.getElementById('contact_form'+name).innerHTML = '<strong style="color:red;">You can not leave this field blank!<\/strong>';
} else{
document.getElementById('contact_form'+name).innerHTML = '';
}
}
var Validate = function () {
if( (!(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\#((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(document.contact_form._email.value))) ) {
document.getElementById('error').innerHTML = '<strong style="color:red;">Please fill in the required fields of the form! Don\'t forget to provide a valid email address! <\/strong>';
return false;
}
}
</script>
<script type="text/javascript">
function addNums(){
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(answer == ""){
alert("Please add the numbers");
return false;
}else if(answer != sum){
alert("Your answer is incorrect; try again.");
return false;
}else{
// all good now! //
document.getElementById("status").innerHTML = "Correct! Thank you for validating a person is submitting the form";
document.getElementById("answer").value = "";
}
}
function randomNums(){
var rand_num1 = Math.floor(Math.random() * 32) + 1;
var rand_num2 = Math.floor(Math.random() * 10) + 1;
document.getElementById("digit1").innerHTML = rand_num1;
document.getElementById("digit2").innerHTML = rand_num2;
}
</script>
</body>
</html>

Confirmation of radio buttons

I have all ready inserted the validation for the radio button and now all i need is to have a alert box to come up before the code proceeds asking "Are you sure you want to pick 'x'" when x would be the level selected. And if cancel is pressed it returns to the webpage.
Thank you are here is my code below.
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.number.value == "") {
msg += "You must enter a exam number \n";
document.ExamEntry.number.focus();
document.getElementById('number').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if ((document.ExamEntry.level[0].checked == false) && (document.ExamEntry.level[1].checked == false) && (document.ExamEntry.level[2].checked == false)) {
msg += "You mus select the level entered \n";
result = false;
}
}
function CheckField(obj) {
if (obj.value.length < '4') {
alert('Name field must 4 character long');
obj.focus();
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="number">Examination Number</td>
<td><input type="text" name="number" maxlength="4" onblur="CheckField(this)"/></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<input type="radio" name="level">GCSE
<input type="radio" name="level">AS
<input type="radio" name="level">A2
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
Hope this helps to get along.
<!DOCTYPE html>
<html>
<head>
<title>Exam entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
var objx;
// test for empty inputs
objx = document.getElementById("subjectInput");
if (objx.value.length == 0) {
msg += "You must enter the subject \n";
objx.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
objx = document.getElementById("numberInput");
if (objx.value.length == 0) {
msg += "You must enter a exam number \n";
objx.focus();
document.getElementById('number').style.color = "red";
result = false;
}
objx = document.getElementById("nameInput");
if (objx.value.length == 0) {
msg += "You must enter your name \n";
objx.focus();
document.getElementById('name').style.color = "red";
result = false;
}
// checked level is needed below for confirmation
var objx = document.ExamEntry;
var checkedLevel = "";
if (objx.level[0].checked) {
checkedLevel = objx.level[0].value;
}
else
if (objx.level[1].checked) {
checkedLevel = objx.level[1].value;
}
else
if (objx.level[2].checked) {
checkedLevel = objx.level[2].value;
}
if (checkedLevel.length == 0) {
msg += "You must select the level entered \n";
result = false;
}
if (result) {
// test for minimum length of name
objx = document.getElementById("nameInput");
if (objx.value.length < 4)
{
objx.focus();
document.getElementById('name').style.color = "red";
//alert('Name field must 4 character long');
msg += 'Name field must be 4 characters long'
result = false;
}
}
// confirm checked level
if (result) {
result = confirm("Are you sure you want to pick '" + checkedLevel + "' ?");
}
else {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" onsubmit="return validateForm();" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" id="nameInput" /></td>
</tr>
<tr>
<td id="number">Examination Number</td>
<td><input type="text" name="number" id="numberInput" maxlength="4" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" id="subjectInput" /></td>
</tr>
<tr>
<input type="radio" name="level" value="GCSE">GCSE
<input type="radio" name="level" value="AS">AS
<input type="radio" name="level" value="A2">A2
<tr>
<td><input type="submit" name="Submit" value="Submit" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

I wish to make my code validate a field to make sure it is a number of four digits. How can I do this?

I am currently doing a GCSE course which allows me to ask for assistance from IT sources as long as I reference them in my investigation. I wish to make the following code validate that there is a number of four digits in the Examination Number entry field. I'm okay with simple validation but this is another step for me.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+="You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
document.getElementById('examtype').style.color="red";
}
}
if(checked==null)
{
msg+="Please choose an option";
result = false;
}
else{
confirm("You have chosen "+checked.value+" is this the correct course?");
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
Regarding checking if it is number, you can use some regex:
e.g.
var reg = /^\d{4}$/ig;
var regExRes = reg.exec(document.ExamEntry.examnumber.value);
if (document.ExamEntry.examnumber.value == "" || (regExRes == null || regExRes.length == 0)) {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color = "red";
result = false;
}
To avoid entering anything beside number, I would suggest you to use something like jquery pluging called masked input
EDIT:
line changed from var reg = /\d{4}/ig; to var reg = /^\d{4}$/ig;

Categories

Resources