Validate form fields in sequences - php

I have a multi-step order form built in this manner:
Step 1: Choose category via radio button
The "Next" button is just an image that has an onclick function hides the current div with the radio buttons, and displays a new div with the next step in the process.
Step 2: Textarea, checkbox -> Dynamic price
Contains a textarea, a dynamic price, and four checkboxes. The price changes depending on the number of characters in the textarea and the choices in the checkboxes. JQuery script is used in order to do that. Again, the "Next" button is just an image that upon activating the onclick function hides the current div, and displays the div containing the next step in the form.
Step 3: Personal Data
And here is my problem. Here where the user inserts name, email and so on. The "Next" button is again just an image that upon activating the onclick function hides the current div and displays the div containing the next step. How do i make the form fields in this step required in order to allow the user to advance to the next step. The code i have for hiding and showing the divs is as follows:
<script type="text/javascript">
function toggleDiv(id, flagit) {
if (flagit == "1") {
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else`if (flagit == "0") {
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"`
}
}
//-->
</script>

That is a horrible (and wrong) piece of old code.
here is an update that actually still handles Netscape4 (the layers part)
You need to show me the rest of the script where you toggle. You need to add validation to
THAT part, not the toggle.
For example, using
<form onsubmit="return validate(this)">
and
<input type="image" src="next.png" />
you can do this (plain JavaScript, the show and hide in jQuery is shown elsewhere on the page):
var currentStep=1;
function toggleDiv(id,flagit) {
if (document.getElementById) document.getElementById(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.all) document.all(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.layers) document.layers[id].visibility = (flagit)?"show":"hide";
}
function validate(theForm) {
if (currentStep == 1) {
if (theForm.category.value....) {
alert("Error in category");
return false;
}
currentStep++;
toggleDiv("part1",0);
toggleDiv("part2",1);
return false; // do not submit
}
if (currentStep == 2) {
if (theForm.price.value....) {
alert("Error in price");
return false
}
currentStep++;
toggleDiv("part2",0);
toggleDiv("part3",1);
return false; // do not submit
}
if (currentStep == 3) {
if (theForm.name.value....) {
alert("Error in name");
return false
}
return true; // submit
}
}

Well, since you have tagged your question with jQuery, why not actualy use it and let jquery handle all platform specific issues.
function toggleDiv(id,flagit) {
if( flagit ) {
$("#"+id).show();
} else {
$("#"+id).hide();
}
}
Let me know if this works.

Related

button will disable until all the input is not filluped is not working properly

Here above is my form input filled. I create a script if input filled is fillup then button will enabled until button is disabled.
But on Card Number input box it is not effected with other input. without card number button shows enabled but i want it must be disabled if all filled is not fillup..
Here is my jQuery script:
jQuery(document).on('change keyup', '.required', function(e){
let Disabled = true;
jQuery(".required").each(function() {
let values = this.value;
if ((values)&&(values.trim() !=''))
{
Disabled = false;
}else{
Disabled = true;
return false;
}
});
if(Disabled){
jQuery('#submit_button').prop("disabled", true);
}else{
jQuery('#submit_button').prop("disabled", false);
}
});
These card number input field is come from stripe payment api.
<div id="card-element" class="inputText gdcard">
<!-- a Stripe Element will be inserted here. -->
</div>
I can't use stripe card element input field with my .required class. Please sort me out this bug?
The recommended way to manage this is to listen to events on Stripe Elements. In particular, you could listen to the change event on a card element (doc) and inspect the value of event.complete to see if the form is filled out. If it is (and your other fields are too) you can enable the Pay button.
function checkIfCardComplete(elementsEvent) {
if (elementsEvent.complete) {
$("#pay-now").removeAttr("disabled")
} else {
$("#pay-now").attr("disabled", "disabled")
}
}
card.on('change', function(event) {
checkIfCardComplete(event);
});
You can see an example implementation of this here (which only looks at the card input being complete, it ignore the other fields): https://jsfiddle.net/nolanhawkins/dhjybsnr/3/
edit:
If, for example, you refactored your code to make the check on your custom fields a function:
function areAllMyFieldsValid() {
let Disabled = true;
jQuery(".required").each(function() {
let values = this.value;
if ((values)&&(values.trim() !='')) {
Disabled = false;
} else {
Disabled = true;
return false;
}
});
return !Disabled; // really you should invert your logic, not the result
}
then you could change the check in the event handler to just look at this additionally:
if (elementsEvent.complete && areAllMyFieldsValid()) { ...}
you could try this:
$("#card-element").prop(disabled, true);
jQuery(document).on('change keyup', '.required', function(e) {
//uncomment if this item has required class
//($("#card-element").removeClass(".required");
var isItOk = jQuery(".required").toArray().every((e) => $(e).val().trim() != '');
$("#card-element").prop(disabled, isItOk);
isItOk = isItOk && $("#card-element").val().trim() != '';
jQuery('#submit_button').prop("disabled", isItOk);
});
jQuery(".required").toArray().every((e) => $(e).val().trim() != ''); means all items which have the class .required are not empty

IE8+, when submitting form with jQuery it does not post data with it

I have a multi page form (pages separated with hidden divs)
All of it is wrapped in form tags, with a submit button. However when the user clicks the submit button at the end, it will check certain criteria on the form. If all good, it will allow the form to submit, else it will preventDefault().
However in IE8+ (maybe lower too), it simply never submits the form. I have console.log'd the JS, and it fires where it should, just IE doesn't submit the form.
I then added a $('#form').submit() call to manually submit it, which it did, but no data got sent...
Any ideas? Sorry if this is a bit vague.
Html
<form method="POST" action="/members/transfer_manager.php" name="f1" id="TM_MainForm">
** Loads of form fields & table structure **
<input type="submit" class="TM_Button" id="TM_submitTransfer" name="save" value="Transfer my account{if $isclientaresellerVAL}s{/if} »" />
</form>
JavaScript
$('#TM_submitTransfer').click(function(e)
{
console.log($.TM_submitTransferERR);
// Submit the form? Let's check first matey.
$.TM_submitTransferERR = false;
if(($('#TM_Movedate').val() == '') && (!$('#TM_MoveNow').is(':checked')))
{
$('#TM_MoveDate_ERR').html($.ObjectER + "Please choose");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check we have some…
// Set the # of xfers
var rsxfers = $("#TM_UsernamesSubACCTSTAGC").tagit("assignedTags");
var fsxferssplitLGNTH = rsxfers.length;
var OnlySubAccts = $('#TM_only_sub_accounts').prop("checked");
console.log($.TM_submitTransferERR);
if((OnlySubAccts == true) && (fsxferssplitLGNTH < 1))
{
alert("You have not chosen any accounts to transfer");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check TOS
if(!$('#TM_Tos').is(':checked'))
{
// Show error?
$('#TM_Tos').focus();
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Error, return false.
if($.TM_submitTransferERR === true)
{
console.log("Don't do it!");
console.log($.TM_submitTransferERR);
e.preventDefault();
return false;
}
console.log($.TM_submitTransferERR);
console.log("do it!");
$('#TM_MainForm').submit();
return true;
});

computing result based on two different ajax request

i have a simple form with two fields whose data are being validated against a database on keyup with jquery. I am also having a button which is currently enabled or disabled based on the number of characters entered in these two fields. THe two jquery functions return an "accept" or "cancel" image for the two fields. I want to enable the button only if both the functions return the accept image or i can even make them return true along with it, which will not be a problem. I just wanna know how to compute a local result based on the returned value from two different ajax requests.
These are two functions that validate teh field against a database.
$("#agentName").keyup(function(){
var agentName = $("#agentName").val();
if(agentName.length > 3)
{
$("#agt-name-result").html(ajax_load).load(loadUrl, "val="+agentName+"&fld=agent_name");
}
else{
$("#agt-name-result").html("<img src=\"images/cancel.png\" />");
}
});
$("#agentSource").keyup(function(){
var agentSource = $("#agentSource").val();
if(agentSource.length > 9)
{
$("#agt-src-result").html(ajax_load).load(loadUrl, "val="+agentSource+"&fld=agent_url");
}
else{
$("#agt-src-result").html("<img src=\"images/cancel.png\" />");
}
});
This is the function that validates the button
$("#agentName,#agentSource").keyup(function(){
var validate;
var agentName = $("#agentName").val();
var agentSource = $("#agentSource").val();
if((agentName === "") || (agentSource === "") || (agentName.length < 3) || (agentSource.length < 10))
{
validate = false;
}
else { validate = true; }
if(validate === true) {
$("#addAgntBtn").removeAttr("disabled");
$("#addAgntBtn").removeClass("dialog-btn-disabled").addClass("dialog-btn");
}
else {
$("#addAgntBtn").attr("disabled", "disabled");
$("#addAgntBtn").removeClass("dialog-btn").addClass("dialog-btn-disabled");
}
});
Any ideas?
I would use a setInterval to poll a $.data() value in which the two ajax calls put their results. You have to pay attention to concurrent accesses, but it should work

Form that removes WWW. and prints result on input?

I need to make a form similar to the one "shorten link" sites use. It should simply remove WWW. and echo the result so I later add my code around it.
For example if the user types www.pizza.com/blablabla clicking on input should display: pizza.com/blablabla
Thanks
You can do lots of fancy stuff with regular expressions. For example, this javascript will do what you want:
// Event for enter click
$("#url").keypress(
function(e) {
if(e.keyCode == 13) {
$("#output").html(cleanURL($("#url").val()));
}
}
);
// Event for button click
$("#submit").click(
function() {
$("#output").html(cleanURL($("#url").val()));
}
);
// Function to clean url
function cleanURL(url)
{
if(url.match(/http:\/\//))
{
url = url.substring(7);
}
if(url.match(/^www\./))
{
url = url.substring(4);
}
return url;
}
Works on enter click, button click and removes both http:// and www
You can try it out here: http://jsfiddle.net/Codemonkey/ydwAb/1/

What's wrong with this PHP/JavaScript form validation?

I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.

Categories