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));
}
}
Related
I want to disable all the user input fields in a form, if the 'Status Active' checkbox is unchecked. The target is to load the page with all the details but if the Status is not active then the checkbox will show as unchecked and the rest of the input fields will remain disabled, till the user checks the checkbox. He can then edit the data and save it.
However, if the record is active, then all the fields will be enabled for editing straight away.
I have already achieved this, but the only problem is even when the record is active, the input fields are getting disabled. Can anyone please point out where is the error in my code?
<script type='text/javascript'>
$(function(){
if($('#square').not(':checked')){
$('#prizename, #prizedesc, #comment').attr('disabled','disabled');
}
});
function checkDisable(){
var square = document.getElementById('square');
var prizename = document.getElementById('prizename');
var prizedesc = document.getElementById('prizedesc');
var comment = document.getElementById('comment');
if(square.checked){
prizename.disabled = false;
prizedesc.disabled = false;
comment.disabled = false;
}
if(!square.checked ){
prizename.disabled = true;
prizedesc.disabled = true;
comment.disabled = true;
}
}
</script>
<php codes here>
<div>
<table>
<tr>
<td>Prize Status - Active:</td>
<td><div class="square">
<input type="checkbox" name="status" id="square" value="1" onchange="checkDisable()" <?php if ($status == 1) echo 'checked'; ?> />
</div>
</td>
</tr>
</table>
<label>Prize Name <input type="text" name="prizename" id="prizename" value="<?php echo isset($_POST['prize']) ? $prizename : '' ?>" > </label>
<label>Prize Description <input type="text" name="prizedesc" id="prizedesc" value="<?php echo isset($_POST['prize']) ? $prize_description : '' ?>" > </label>
<label>Comment <textarea name="comment" id="comment" rows="4" ><?php echo $comment ?> </textarea> </label>
</div>
<div class="button-section">
<input id="save_button" type="submit" name="submit" value="Save">
</div>
$('#square').not(':checked')
this condition is not satisfied because it will return the object. You have to check with length. Please check in your code.
if($('#square').not(':checked').length > 0)
Or
if(!$('#square').is(":checked"))
I have altered your code - Working from my side.
HTML: (Just insert your variables again)
<table>
<tr>
<td>Prize Status - Active:</td>
<td>
<div class="square">
<input type="checkbox" name="status" id="square" value="1">
</div>
</td>
</tr>
</table>
<label>Prize Name <br><br><input type="text" name="prizename" id="prizename"
value="Juan" ></label>
<label>Prize Description <input type="text" name="prizedesc" id="prizedesc"
value="Description" ></label>
<label>Comment <textarea name="comment" id="comment" rows="4"
>Comment</textarea></label>
<div class="button-section">
<input id="save_button" type="submit" name="submit" value="Save">
</div>
JS: (The first bit executes on page load and the second part is listening for the change event on the checkbox)
if($('#square').not(':checked').length > 0){
document.getElementById('prizename').disabled = true;
document.getElementById('prizedesc').disabled = true;
document.getElementById('comment').disabled = true;
} else {
document.getElementById('prizename').disabled = false;
document.getElementById('prizedesc').disabled = false;
document.getElementById('comment').disabled = false;
}
const checkbox = document.getElementById('square');
checkbox.addEventListener('change', (event) => {
if (event.target.checked) {
document.getElementById('prizename').disabled = false;
document.getElementById('prizedesc').disabled = false;
document.getElementById('comment').disabled = false;
} else {
document.getElementById('prizename').disabled = true;
document.getElementById('prizedesc').disabled = true;
document.getElementById('comment').disabled = true;
}
})
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.
I really can't find a solution anywhere on the web because my problem is a bit unique.
I am made two radio buttons, Division and External. When it is clicked, the Division radio button displays drop down list and the External one displays an input text box.
This is the code I Html made.
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<select name="client_details" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<input type="text" name="client_details" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
This is the php code.
<?php
require("config.php");
if(isset($_POST['submit']))
{
$client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
$sql = "SELECT * FROM contracts";
$query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
The external radio button and the input text box is working fine as both of the value successfully inserted in the database.
But for the division, it inserts only the value Division.
What is it that I do wrong?
Try this :
I have put the condition for type in the start of the code and change the name of the dropdown.
your php code
<?php
require("config.php");
if(isset($_POST['submit']))
{
echo $client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
if($client_type == 'Division'){
$client_details = isset($_POST ['client_details1']) ? $_POST['client_details1'] :null;
}
else{
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
}
echo $query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
Your HTML code
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<select name="client_details1" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<input type="text" name="client_details" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Version by prakash tank is correct and maybe even better. I post this solution so you know there is also other way to go around and in notes I explained to you what you did wrong.
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<!-- client_details has to be changed to client_detailsDiv as after clicking "submit" data from Division and External were put in to the same variable "client_details" so even if External was empty PHP though that it's suppose to be empty and as long as external
DO NOT MIX TWO TYPES OF FORM TYPES AS ONE VARIABLE = DON'T GIVE THEM THE SAME name - in other words you can't give same name for SELECT and TEXT and so on.-->
<select name="client_detailsDiv" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<!--client_details has to be changed to client_detailsExt for reason described above-->
<input type="text" name="client_detailsExt" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
require("config.php");
if(isset($_POST['submit']))
{
$client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
/*
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
above functions was wrong as I already explained it got $_POST['client_type'] for the External - PHP works the way that it gets variable from the first $_POST['same_name'] and then from second $_POST['same_name'] and then overwrites value of first $_POST['same_name'] and for this reason it displayed only value for External and none for Division as when user set External, Division was empty. So if you would switch form for External as first and put form for Division as second then you wouldn't get variable from External but from Division.
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
so what we need to do is to to put this code:
*/
if(!empty($_POST['client_detailsDiv'])) {$client_details = $_POST['client_detailsDiv'] ? $_POST['client_detailsDiv'] :null;}
else {$client_details = $_POST['client_detailsExt'] ? $_POST['client_detailsExt'] :null;}
// at fist we make sure that client_detailsDiv is not empty, if it's not than we set client_detailsDiv as $client_details. But if it's empty we use else statement to
$sql = "SELECT * FROM contracts";
$query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
Below is the HTML/PHP code, in which i need to validate any of the checkbox out of 5 before submit the Form.
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
i=0;
while(i=5){
?>
<input type="checkbox" name="users[]" value="<?php echo i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>
I think you are trying to do this
function checkAddress(checkbox) {
if (checkbox.checked) {
document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
document.frmUser.action = "#";
alert("checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php $i=0; while($i<=5){ ?>
<input type="checkbox" name="users[]" onClick="checkAddress(this);" value="<?php echo $i; ?>">
<?php $i++;} ?>
<input type="submit" name="update" class="button" value="Update" />
</form>
</div>
Some errors in your code
you have not used $ while denoting the variable i
you are taking the button inside the while loop so it also repeating with the checkboxes.
You are calling onClick="checkAddress(this);" from your button, so this refers to the button and not a checkbox, so then in your function checkbox.checked is testing if the button is checked - which obviously it never will be.
To test whether at least one checkbox is checked you could loop through them testing them in turn, but you can also do it in one step as follows:
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
// at least one is checked
}
The .querySelector() method returns the first matching element (which is a truthy value for use in an if test), or returns null if no matching elements are found (which is a falsey value for use in an if test).
(If the page has only one form with one group of checkboxes then you could simplify the selector to something like .querySelector(':checked'), but I think it is better to be explicit about which items you're testing.)
In context:
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<input type="checkbox" name="users[]" value="1" >
<input type="checkbox" name="users[]" value="2" >
<input type="checkbox" name="users[]" value="3" >
<input type="checkbox" name="users[]" value="4" >
<input type="checkbox" name="users[]" value="5" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress();" />
</form>
</div>
There was another problem with the code posted - the variable i wasn't correctly defined ~ it should have been $i
Rather than assigning the function directly to the button you can create an event listener like this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function validate(e){
var form=e.target.parentNode;
var col=form.querySelectorAll('input[type="checkbox"]');
var checked=[];
if( col )for( var n in col )if( col[n].nodeType==1 ){
if( col[n].checked ) checked.push( col[n].name );
}
if( checked.length > 0 ){
form.action='edit_user.php';
form.submit();
} else {
alert('You MUST tick at least one checkbox');
}
}
function bindEvents(){
var bttn=document.forms['frmUser'].querySelectorAll('input[type="button"]')[0];
bttn.addEventListener( 'click', validate, false );
}
document.addEventListener('DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while( $i <= 5 ){
echo "<input type='checkbox' name='users[]' value='{$i}' >";
$i++;
}
echo "<input type='button' name='update' class='button' value='Update' />";
?>
</form>
</div>
</body>
</html>
<html>
<head>
<script language="javascript" type="text/javascript">
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while($i<=5){
?>
<input type="checkbox" name="users[]" value="<?php echo $i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>
I've been having a problem calling a function declared in an external .js file.
I've made an include of the .js file in the main page, but apparently it works in part (Just one function it is called correctly, the others generate an "Uncaught ReferenceError: function is not defined ")
Here's the Js file:`
<script type="text/javascript">
var maxAmount = 170;
// Modify the counter textField by given the textField to control and his counter
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount){
countDisplay.value = maxAmount - nameLenght;
}
else{
countDisplay.value = "0";
}
function titleShow(){
theTitle = val('title').replace(/^\s+|\s+$/g,"");
get('out_title').innerHTML = theTitle;
if(get('check_bold').checked == true){
highlightTerms('out_title');
}
}
function snippetShow(){
console.log("I've entered here");
theSnippet = val('description').replace(/^\s+|\s+$/g,"");
if(theSnippet.length + dateLength <= 156){
get('out_snippet').innerHTML = theSnippet;}
else{
var snipLimit = 153 - dateLength;
snippetSpace = theSnippet.lastIndexOf(" ",snipLimit);
get('out_snippet').innerHTML = theSnippet.substring(0,snippetSpace).concat(ellipsis.bold());}
}
function urlFunction(){
var theURL = val('in_url');
theURL = theURL.replace('http://','');
theURL = theURL.replace(/^\s+|\s+$/g,"");
get('out_url').innerHTML = theURL;
if(get('check_bold').checked == true){
highlightURL();}}
And here's the Main page: '
<?php
include('Code/Php_code.php');
include('Code/Js_code.js');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<form action="Database_Interface.php" method="post"><br>
Title:<br>
<input type="text" id="title" name="title" size="150" maxlength="150" value="<?php echo $title ?>" onKeyUp='textCounter("title","countDisplay");'><br>
<input readonly type="text" id="countDisplay" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Description:<br>
<input type="text" id="description" name="description" size="150" value="<?php echo $tags['description'] ?>" onKeyUp='textCounter("description","countDisplay2");'><br>
<input readonly type="text" id="countDisplay2" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Keywords:<br>
<input type="text" id="keywords" name="keywords" size="150" value="<?php echo $tags['keywords'] ?>" onKeyUp='textCounter("keywords","countDisplay3");'><br>
<input readonly type="text" id="countDisplay3" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
<input type="submit" value="Carica sul database">
<input type="button" value="see" onclick='snippetShow();'>
</form><br>
<div style="background-color:#f2f2f2; border:1px solid; border-color: black; position:relative;">
<h3><span id="out_title"></span></h3>
<div>
<cite><span id="out_url" ><?php echo $site ?></span></cite>
</div>
<div>
<span id="out_snippet">sdsdsdfvbfbf</span>
</div>
</div>
The answer is: why just the first method is called successfully while the other two generate an error?
Your first function seems to lack a closing } bracket. The last bracket is from the else block. Fixed:
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount) {
countDisplay.value = maxAmount - nameLenght;
}
else {
countDisplay.value = "0";
}
}
First of all close <script> tage at end of your js.php file byv </script>
Do not include js file before <doctype> tag.
include it in <head> tag OR before </body>