Been struggling with this for a couple days now. Here's the set up - I have a parent page "support.php" there are tabs, and when you click a tab it brings in the appropriate form via ajax.
(the relevant code for each section:)
form input's on the AJAX page
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" value="" readonly>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
The parent page - support.php calls for "validation.js" which is my jQuery.validate script.
...
SupportMath: {
required: true,
equal: "<?php echo $randomNumTotal; ?>"
}
There is a .get command on the parent page for a file "random.php"
$.get('PHP/random.php', function (data){
$("#SupportNumbers").val(data);
});
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
echo $randomNum ."+". $randomNum2;
$randomNumTotal = $randomNum + $randomNum2;
?>
which generates two random numbers so you can add them together. The validation checks to make sure
the two numbers that are generated are added correctly. I just can't seem to get all these pieces to use the same numbers, i can get the text box "SupportNumbers" to populate with two random numbers say "2 + 5" but when I enter "7" into "#SupportMath" it displays the error msg. It should be $randomNumTotal but I can't get that to the page, and have the validation script check against that.
HELP.
I realize this is clear as mud so ill try and explain more
I have 5 forms on my support page. To reduce the chaos, I have them in a vertical tab set. I don't want my js validation script on the page and I don't want all 5 forms hidden/displayed on the page due to some issues we've had with some bots. So my solution was to bring in the forms with AJAX (done) and just link to the validation script (done) all is good except for our "random math captcha" I can put it in a file and use the ".get" command to populate the box that holds the two random math questions, but can't get the answer to validate. Hope this helps, code below.
EXPLANATION: ( step by step )
we use your method to generate two random number from 1 to 9 at page load
we have added an extra input <input type="hidden" name="math" id="math"/> this field is needed since you are using a readonly field, now the readonly fields are not submitted...by forms, this way we have the one shown to user and another one hidden, this one will be submitted;
we get the #math value that is a string ex: 5+2 so we need to transform this into two int and sum it.
finally we make the check the SUM against the user input #SupportMath
DEMO: https://so.lucafilosofi.com/php-jquery-validation/
PHP ( that check the match against... )
if ( isset($_POST['post']) ) {
$math = explode('+',trim($_POST['math']));
$sum = ( (int)$math[0] + (int)$math[1] );
$message = 'error';
if ( (int)$sum === (int)$_POST['SupportMath'] ) {
$message = 'success';
}
echo $message;
}
jQuery ( pseudo code...)
$(function() {
$.get('random.php',function(data) {
$("#SupportNumbers,#math").val(data);
});
$('#form').submit(function(e) {
e.preventDefault();
var query = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: "post=post&" + query,
success: function(msg) {
if (msg.indexOf('success') == -1) {
alert('error');
} else {
alert('cURL');
}
}
});
});
});
HTML
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" readonly>
<input type="hidden" name="math" id="math"/>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
Here's a self-sufficient version of what I was referring to.
<?php
session_start();
if (isset($_GET['validate']))
{
$passed = (session_is_registered('validate') && (int)$_GET['validate'] == $_SESSION['validate']);
header('Content-Type: application/json');
echo sprintf('{"validation":"%s"}', $passed?'OK':'FAIL');
exit;
}
function generate_check()
{
// generate a result (incompleted)
$result = Array(
'num1' => rand(0,10), // first random number
'num2' => rand(0,10), // second random number
'problem' => null, // actual math problem
'answer' => null // the answer
);
// random method
switch (rand(0,999) % 3)
{
case 0: // addition
$result['problem'] = sprintf('%d + %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] + $result['num2'];
break;
case 1: // subtraction
$result['problem'] = sprintf('%d - %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] - $result['num2'];
break;
case 2: // multiplication
$result['problem'] = sprintf('%d * %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] * $result['num2'];
break;
}
return $result;
}
$check = generate_check();
session_register('validate');
$_SESSION['validate'] = $check['answer'];
?>
<html>
<head>
<title>Sample Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<Script type="text/javascript">
$(function(){
$('#check').click(function(){
$('#result').css('color','').text('Checking...');
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{'validate':$('#answer').val(),'_':(new Date()).toString()},function(data){
if (data.validation=='OK')
$('#result').css('color','green').text('PASSED!');
else
$('#result').css('color','red').text('FAILED!');
});
});
});
</script>
</head>
<body>
<p>What is <b><?php echo $check['problem']; ?></b>?</p>
<input type="text" name="answer" id="answer" /><input id="check" type="button" value="Check" />
<p id="result"></p>
<br /><br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"><input type="submit" value="New problem" /></form>
</body>
</html>
I used to do pages like this until I found this wonderful inline Jquery validator You simply add a class with relevant information to your form objects and it does the rest. There's no need to fool around with redirecting or sessions for that matter. I've had it in production on about 25 sites for nearly a year without any issues whatsoever.
Edit: looks like you're trying to do a Captcha of sorts, maybe? Perhaps look at ReCaptcha which not only verifies a user is correct, but also helps improve OCR. Alternatively, you could do a slidelock
As we say in my shop, "No reason to go off and write a minivan...."
Related
I'm currently building a system using ExpressionEngine that allows users to answer questions in exchange for points, they can then use these points to claim prizes.
I've been writing the functionality to claim a prize, it needs to do the following:
Check the prize is in stock
Check the user has enough points
If in stock and enough points submit a form which lets the admin know to send the prize out
I have the following code which I think is nearly there however I'm struggling with the last bit, the actual success/failure parts. I've used jQuery Ajax:
<script type="text/javascript">
$(function() {
$("#prizeClaim").submit(function() {
var data = "entry_id={entry_id}&member_id={logged_in_member_id}&prize_title={title}&prize_points={prize_points}";
$.ajax({
url: "/prizes/prize_validation/",
data: data,
success: function(html) {
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
</script>
This code currently just outputs the html of prize_validation in an alert, this is the code used on the validation page so far:
<?php
// All data required made into vars
$entry_id = ($_GET['entry_id']);
$member_id = ($_GET['member_id']);
$prize_title = ($_GET['prize_title']);
$prize_points = ($_GET['prize_points']);
// Select the stock column
$query = ee()->db->query("SELECT field_id_6 FROM exp_channel_data WHERE entry_id = $entry_id");
if ($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
// define stock_total
$stock_total = $row['field_id_6'];
// If stock more than 0 go ahead
if($stock_total > 0) {
//remove 1 stock item
ee()->db->query("UPDATE exp_channel_data SET field_id_6 = field_id_6 - 1 WHERE entry_id = $entry_id");
//update users points
$data = array('member_id' => $member_id, 'prize_points' => $prize_points, 'prize_id' => $entry_id);
$sql = ee()->db->insert_string('exp_rmdy_member_prize_data', $data);
ee()->db->query($sql);
}
}
}
?>
{exp:freeform:form form_id="1" return="thanks"}
<input type="hidden" name="name" value="{username}" id="freeform_name" maxlength="150">
<input type="hidden" name="email" value="{email}" id="freeform_email" maxlength="150">
<input type="hidden" name="company" value="{exp:channel:entries channel='company' dynamic='no'}{if {member_code} == {company_code}}{title}: {company_address}{/if}{/exp:channel:entries}" id="freeform_company" maxlength="200">
<input type="hidden" name="prize" value="<?php echo $prize_title ?>" id="freeform_prize" maxlength="150">
<p><input type='submit' name='submit' value='Process order'></p>
{/exp:freeform:form}
This code checks the stock and if the item is in stock it then removes the amount of points from the users total points, this works. However once this has happened I want to submit the Freeform, I'm not 100% sure if this should be within the prize_validation file or in a third location. But after lots of experimentation I'm still not sure how to go about either!
Any hints/tips much appreciated!
Pjacks answer in the above comment helped me fix this.
Do you want to use ajax to submit or a normal form submit. This should submit the form if you put $("#freeform").submit(); in your call back instead of the alert. Thats assuming the id of your form is called freeform. If you want to do ajax, it's done a bit differently.
I have a form which I want to show the response in div via AJAX. Here is the form image from funds_transfer.php.
I test it with manual method=post and submit with the form and it works nicely. Here is the partial PHP code from funds_transfer_backend.php:
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
echo "Please complete the form!";
$response = -1;
}
else {
// other code goes here..
$display = array('response' => $response); // for ajax response later
echo json_encode($display);
PHP gave me this output:
Please complete the form!{"response":-1}
Now I want to implement it with AJAX and it's currently not working. Here is my current no working html + jQuery code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
//other code goes here..
<p>Transfer your funds to other account
<script type="text/javascript">
// Pre populated array of data
var myData = new Array();
<?php
$sql="SELECT * FROM `account` WHERE client_id='$id'";
$result=mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "myData.push('".$row['funds']."');";
$result_array[] = $row['id'];
}
?>
</script>
<form id="example" name="example">
Select your account<select id="selector" name="index_num" style="margin-left: 10px;">
<option value="-1">Account Number</option>
<?php //echo $result_array[0];
$num = count($result_array) - 1;
$i=0;
while($i<=$num)
{
echo "<option value=\"$i\">$result_array[$i]</option>";
$i++;
}
?>
</select>
<br />
Funds : RM <input type="text" id="populateme" name="funds" disabled/><br>
Recipient Account Number <input type="text" id="recipient_box" name="recipient" /> <br>
Amount : RM <input type="text" id="amount_box" name="amount"/><br>
<input type="button" value="Submit" onclick="update();">
<input type="reset" value="Reset">
</form>
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<script type="text/javascript">
document.example.selector.onchange = updateText;
function updateText() {
var obj_sel = document.example.selector;
document.example.populateme.value = myData[obj_sel.value];
}
</script>
</p>
The SQL query above will fetch data from db and populated it in the select box and disabled text box. No problem with that it's currently works nicely.
The problem is there's no response in div id="stage after submit and validation data.response==-1 . I'm not sure what's the problem here probably the form didn't submit at all. Please help and thanks in advance.
Add id
<select id="index_num" name="index_num" style="margin-left: 10px;">
because you index_num value is not sending and you get a notice as response with your
json. Also remove from funds_transfer_backend.php this line -> echo "Please complete the form!"
Remove the comma on this line:
amount : five,
I think you should use $('form[name=YourFormName]').serialize();
....
var posted = $('form[name=YourFormName]').serialize();
$.post("funds_transfer_backend.php", posted ,function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
...
if you're using chrome, launch the Developer Tools (ctrl+shift+I), go to the Network tab, then submit your form. if the form is in fact being submitted, you'll be able to inspect both the request and response to see exactly what is being submitted to and returned from the server. if your form is not being submitted, due to a JavaScript error for example, the error will appear in the Console tab.
similar debugging tools exist for FireFox as well.
a couple other things to note:
1) your JavaScript is populating the "two" variable incorrectly. it references an element with id "index_num", however the id on that element is "selector". that being said, you should in fact just use the serialize() approach that Vu mentioned.
2) your PHP code is echoing a raw error message before later on echoing the actual JSON response. this results in invalid JSON. you should store the error into a variable and push that error onto the associative array with a proper key (e.g. "message"). then you can display that on your page like so:
$('#stage').show().html(data.message);
First you are echoing the error in the PHP and you are expecting a JSON in the response in the AJAX success. So first remove the following line in the server/PHP script, or say don't echo anything other than the JSON.
echo "Please complete the form!";
And ensure that your PHP output is as follows on the correct scenario.
{"response":-1}
Now your data variable in the AJAX success will contain json format only. Do a parseJSON before checking if (data.response==-1) as follows.
function(data){
data = $.parseJSON(data);
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
}
Ok, I've been looking and looking for about 2 weeks now and I've yet to find exactly what I need to figure out, so now is the time to ask the experts!
I'm working on an advertising management system and one of the parts of the request form is to select start and end dates for an ad. The user is given an option of adding more dates.
So, there are two inputs that are there initally...
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Then, under that is an option to dynamically add more inputs.
When the user adds more inputs, it just copies those initial inputs, so we end up with more instances. For example:
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Is there a way to send the results of these inputs as an array using .load()?
I have it sending and displaying the info for one set of inputs with the code below...
var startDate = $("#startDateInput").val();
var endDate = $("#endDateInput").val();
$("#adBooking").show().load('../scripts/checkSpots.php', { startDate: startDate, endDate: endDate});
I guess I just don't 100% understand how to do this. I've been racking my brain for the past two weeks but I can't find anything totally relevant to what I'm doing.
But, what I need to do is make an array of data out of all the startDate and endDate inputs and then throw it through the .load() and into the checkSpots.php page and have it display the information for each set of start/end dates.
Is there a different way of doing this? Maybe a more efficient way? Or, if anyone can shed a bit of light on this broken jQuery noob, I'd greatly apprecaite it! :D
demo: http://jsbin.com/etihaw/3
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP
<?php
foreach($_POST['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_POST['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>
First things first, ID's need to be unique, so when a new date pair is added, append a qualifier on the end of the id:
<input type="text" name="startDate[]" id="startDateInput1">
<input type="text" name="enddate[]" id="endDateInput1">
<input type="text" name="startDate[]" id="startDateInput2">
<input type="text" name="enddate[]" id="endDateInput2">
Or better yet, use a class:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you can apply some jQuery voodoo whenever you'd like (button click, submit, etc):
$('#myButton').click(function(){
// Our ajax post data. For example, $_POST['startDates'][2] would
// give you the 3rd start date in your php file.
var data = {
startDates: new Array(),
endDates: new Array()
};
// Loop through each date pair, extract its value, and add it to our post data
$('.startDateInput').each(function(){
data.startDates.push(this.val());
});
$('.endDateInput').each(function(){
data.endDates.push(this.val());
});
// Load it!
$('#result').load('doSomething.php', data);
});
Note: Above code is not tested, just an example of one possible solution.
Hope that helps. Oh, and obligatory Family Guy reference.
There is a major flaw in your logic: Any id attribute must be unique in the document. As you use several id's more than once, it will not work or give unexpected results at best.
First, you shouldn't use the same id on multiple elements within a single html page. That's going to cause all sorts of unpredictable behavior. Use class instead so:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you need to query for all the input elements using jquery loop through each element and assign its value to the appropriate array.
var myEndDateArray = [], myStartDateArray = [];
$(".endDateInput").each(function() {
myEndDateArray.push($(this).val())
});
$(".startDateInput").each(function() {
myStartDateArray.push($(this).val())
});
Finally, you must post the array data to your page in a compatible post format.
$("#adBooking").show().load('../scripts/checkSpots.php', { 'startdate[]': myStartDateArray, 'enddate[]': myEndDateArray});
I bumped int this problem lately, and I found aSeptik solution is very useful.
But there is a mistake in it. From jQuery documentation:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Since the result of the .serialze() function is string the .load() methode will use GET.
JS code (same):
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP script with _GET:
<?php
foreach($_GET['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_GET['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>
what to do in order to make the form remember the previous input or the current input of the user even after he/she refreshed the page ?
should I do ,
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_SESSION['messenger']; ?>"/>
</div>
or
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_POST['messenger']; ?>"/>
</div>
or
there's a trick to do it ?..how ?
on the page where your form is submitting do something like this
session_start();
$_SESSION['data'] = $_POST['data'];
$_SESSION['data_another'] = $_POST['data_another'];
and than you can access those session variables any where like this
session_start(); // this should be at the top of the page before any html load
<input type="text" name="name" value="<?php echo $_SESSION['data'];?>"/>
refresh your page on success call like this
$.ajax({
type: "POST",
url: "yourfile.php",
data: 'data='+ data,
success: function(){
location.reload();
}
});
I had similar issue at one of my project so I wrote some js to handle this using cookies.
First I found two simple functions to set and get cookies values:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
Than I wrote two other functions to set and get input values:
function saveValue(input) {
var name = input.attr('name');
var value = input.val();
setCookie(name,value);
}
function getValue(input) {
var name = input.attr('name');
var value = getCookie(name);
if(value != null && value != "" ) {
return value;
}
}
And using jQuery I save user's input value to session cookie
$('input[type=text]').each(function(){
var value = getValue($(this));
$(this).val(value);
}).on('blur', function(){
if($(this).val() != '' ) {
saveValue($(this));
}
});
I hope it'll help ;)
That quite depends on where the data in the fields is coming from.
If your scenario is that you are presenting a blank form, the user enters some data and then without submitting it, refreshes the page, there is nothing you can do. That's up for the browser to handle.
You might be able to do some very weird JavaScript hacking there, but I would not suggest that.
On the other hand, if your data is coming from a previous page or something like that, that's a different story. But then you need to tell us where the data is coming from, so I can give you a reasonable answer.
If you mean, filling out form fields and clicking refresh, then there is no direct way, as the data isn't submitted. That sort of behavior is up to the browser.
The only thing you could do is post the data via AJAX back to your server as the fields change. Your PHP script receiving the data would set some session variables. When the form loads, you would set their default values to the appropriate session values.
Rarely though is there a need for this kind of behavior. There will be many requests sent back and forth to your server.
Session is a good way to store and remember data but why complicate things? Consider if the form has many fields, developer has to store lots of values in session. Why not simply print or echo.
Example:
Form is submitted with input ssName and hidden field ssAct with value of send
Get the ssName and ssAct on form submit
$ssAct=$_REQUEST["ssAct"];
$ssName=$_REQUEST["ssName"];
and the form
<input type="text" name="ssName" value="<?php if($ssAct=='send' && $ssName!='') { echo "$ssName"; } ?>">
<input type="hidden" name="ssAct" value="send">
On submit name will be echoed if it was submitted and was not empty.
None of your suggestions will help you "remember" data after a refresh (action that not send data to the server). What you need is to grab data via javascript (maybe with onkeyup events type) and grab it using cookies. With jquery is very easy.
There are some main issues to check in order to get the data appear after refresh or any event handler:
1) Be aware of the signature. it must contain the method="post" attribute as follows:
<form method="post"/>
else the using of the $_POST['messenger'] will not work.
The default value of the method attribute in the form is get.
<form> equals to <form method="get">
2) Many programmers mix between the attributes id vs name.
Be aware of using the correct attribute. The $_POST associative array is using the name to get data from it. That is why the next example will not work correctly:
<input type="text" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
To get it work right you must add the attribute name="data" as follows:
<input type="text" name="data" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
Good luck
You could also do without session like the below code:
<input type="text" name="Fname" value="<?php if(isset($_POST['Fname'])){ echo $_POST['Fname']; } ?>" /><br/>
This will keep the typed data inside the input box!
after posting your details to session, write like this in value
<?php print $_SESSION['messenger'] ?>
if you are writing both php and HTML in same file then you can do like this
<?php print $messenger] ?>
try the attribute autocomplete, maybe it will work on some browsers...
<input type="text" autocomplete="on" />
You can use autocomplete for a form too.
how can I check if the user filled some textboxes upon submit? My textboxes have different id and name.
If the user did not fill the required like password the form is not continued.
Thank you.
You can do this using JavaScript or within the script itself.
If using javascript, you simply check the form fields against your requirements before allowing the form to submit. However, you may still need to implement this in the script in case ofr some reason they have javascript turned off.
Basically, in the script, you check the values of the form when they submit:
if($_GET['field_name']) !== 'the value I expect') {
// show the form again with errors
}
// continue
Hope that helps.
Try the below. Naturally you can tweak the form and id's and such, but the basic principle should work. also shown here: http://jsfiddle.net/j3nSB/2/
<form>
<input type="text" id="username" value=""/>
<input type="password" id="password" value="" />
<input type="submit" id="submitButt" value="Go" />
</form>
document.getElementById("submitButt").onclick = function () {
if(document.getElementById("username").value.length == 0 |document.getElementById("password").value.length == 0) {
return false;
}
}
Assuming you have one form, here is the most simple/generic way I can think of, using plain JavaScript.
<script type="text/javascript">
var arrRequiredFields = [ "txtPassword", "txtEmail" ];
window.onload = function() {
document.forms[0].onsubmit = function() {
for (var i = 0; i < arrRequiredFields.length; i++) {
var field = document.forms[0].elements[arrRequiredFields[i]];
if (field && field.value.length == 0) {
alert("Missing required value");
field.focus();
return false;
}
}
return true;
};
};
</script>
Just put the names (not ID) of the required elements, put the code in your page and you're all set.
Live test case: http://jsfiddle.net/kf7pL/
use this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Its very easy to use, and you can just add a class of 'required' to each required input field.
its as easy as $('#form').validate();
It also supports things like integer and date. Highly recommend it to anyone