I have an input field that asks for an email address followed by a submit button. Here is the code associated with that:
HTML
<div class="email">
<form action="handler.php" method="post" id="hgb-signup">
<input type="text" name="email" id="email" value="Enter your email address">
<input type="submit" name="submit" id="submit" value="ยป" />
</form>
</div>
JAVASCRIPT
Event.observe(window, 'load', function() {
jQuery('#email').focus(function() {
jQuery(this).val('');
});
jQuery("#hgb-signup").submit(function(e){
var dataString = jQuery(this).serialize();
jQuery('#email').val('Sending... please wait...');
jQuery.getJSON('handler.php?callback=?', {
"sent_data": dataString },
function(received_data) {
jQuery('#email').val(received_data.message);
}
);
e.preventDefault();
});
});
Right now, when the page loads the #email input field reads "Enter your email address". When you click on the submit button, it overwrites the #email value with "Sending... please wait..." and depending on whether there's been a problem or the submission was successful, there will be a respective message inside the #email field indicating such. Now, when I click inside the input field, the "Enter your email address" text disappears .val(''), and when I click outside the field, that message is still gone. I initially had a .blur() that put the message back, which is the desired result, however, when users would enter their email address and hit submit, it would submit "Enter your email address" and not the actual email address, because when you hit the submit button .blur() was called.
Now knowing what the goal is, is there a .blur() alternative and if not, how do I best handle this situation?
Basically, here's what I'm looking for:
The #email field should read "Enter your email address" at any given time when the cursor is not inside the field and should come back when the cursor leaves the field, but I would like the error/success message to stay in there after the form has been submitted, unless the user clicks back inside the field and leaves, then it can say "Enter your email address" again.
Thanks!
Use .blur(), but check the val() first. Replace with "Enter your email" only when it's empty
jQuery('#email').blur(function() {
var $this = jQuery(this);
if ($this.val() == '') $this.val('Enter your email');
});
Here's a jsfiddle for you, you can check it out. I also added a check to focus() handler so it would not remove contents when you click on an input field after entering your email.
Related
I have a php registration form and one of the fields on the form is a password field and I want the form to check the password against a database table list of passwords before allowing the form to submit the user's info. So pretty much the user needs a password to register. I have been looking for a solution for this and have not come across one.
HTML
<input type="text" name="promo" required>
PHP
<?php
$promo_codes = ['code1', 'code2'];
if(in_array($_POST['promo'], $promo_codes) {
//in array, continue
} else {
//not in array, exit gracefully
}
Basically create a form entry for the promo code in the html and something like the above to validate the promo codes.
Pseudo code:
<form>
<input name="username" />
<input name="email" />
<input name="promo_code" id="promo" />
<input type="submit" value="Register" />
</form>
<script>
+ use jQuery to fire off an AJAX call with the value in the #promo input of the form
+ if a match is found in the database enable the form or the button on the form so that they can register
+ delete the promo code from the database once the registration takes place
</script>
I'm having a problem for doing my form .
When I click the button generate , I'm attempting to redirect to an error page but it stills redirect to the correct page even in the form it's empty.
if(isset($_POST['Generate'])) {
if(!empty($_POST['aid'])) {
$gen_link = "www.correctlink.com";
$_SESSION['active'] = $aid;
header("Location: http://$gen_link") ;
} else {
header("Location : http://error404.com");
}
}
Even when I click the generate button it stills redirect to www.correctlink.com
I want the user to type something in the form
Form Code:
<input type="text" name="aid" id="aid" value="Enter Your Active Here" onfocus=" if (this.value == 'Enter Your Active Here') { this.value = ''; }" onblur="if (this.value == '') { this.value='Enter Your Active Here';} "/><br /><br />
<input type="submit" class="button" value="Generate" name="Generate" id="Generate"/>
The problem here is that you have set a default value of "Enter Your Active Here" in your textbox. If the user simply submits the form without even trying to enter anything in the textbox, the value of $_POST['aid'] becomes "Enter Your Active Here".
So what do you do? Simple, instead of checking for empty, check for
if($_POST['aid'] != "Enter Your Active Here" && ! empty(trim($_POST['aid'])))
Another solution would be to use a placeholder but since that's a HTML5 feature, the compatibility of that across browsers is limited.
EDIT: The second condition is added to make sure the code works in case javascript is disabled on the client machine and the user mischievously tries to submit form by emptying the textbox
If you have the value attribute set to something in the form, it will submit that as the value, therefore it won't be empty. Instead of checking if it's empty, check if it equals Enter Your Active Here.
If you need a placeholder text, you could use the attribute placeholder instead of value.
The $_POST['aid'] is not empty because you set value for this as Enter Your Active Here
Use something like this
<input type="text" name="aid" id="aid" placeholder="Enter Your Active Here" .......
OR
<label>Enter Your Active Here</label><input type="text" name="aid" id="aid" .....
replace
if(!empty($_POST['aid']))
by
if($_POST['aid']!="" && $_POST['aid']!="Enter Your Active Here")
Thanks.
I was wondering if someone could help me out as I have googled for quite a while today, and haven't found anything to solve my problem.
The websites I've looked at mentioned it's because it's returning JSON, but they are getting it on all the fields, not just the one.
But what I can't understand, is why isn't the first two fields as well? Hence my confusion
I am submitting a login form, using Jquery and AJAX (I'm knew to this).
The first two fields (email and pass) submit, and return as expected.
For testing purposes I simply return their values in <span id="loginresponse"></span>.
I have a third field, to prevent CSRF, called 't' (named it random names, to see if this was the problem - I still get [object Object] returned). <input type="hidden" name="t" value="RandomToken"/>
When submitting the form, I expect it to return what I entered into the fields - "Email,Pass and RandomToken".
Instead, I get Email,Pass,[Object Object].
Here is my DoLogin function, which is called when the form is submitted.
function DoLogin()
{
var Email = $("#email").val();
var Pass = $("#pass").val();
var LoginResponse = $("#loginresponse");
var T = $("#t");
var EmailPlaceholder="Email address";var PassPlaceholder="Your password here";
$.get('path/to/login_ajax.php?email='+Email+'&pass='+Pass+'&t='+T, function(data)
{
$('#loginresponse').html(data);
});
/*if(Email != EmailPlaceholder && Pass != PassPlaceholder && Email != "" && Email != " " && Pass !="" && Pass != " ")
{
}*/
}
Here is my HTML form:
<form action="javascript:DoLogin();" method="post"><!--Also tried changing method to GET, still got the same problem -->
<input id="email" class="inputemail" type="text" name="email" size="40" value="Email address" onclick="$(this).val('');"/><span>Your email</span><br/>
<input id="pass" class="inputpassword" type="password" name="pass" size="40" value="Your password here" onclick="$(this).val('');"/><span>Your password</span><br/>
<input id="t" type="hidden" name="t" value="RandomToken"/>
<input class="indexsubmit" type="submit" value="Login"/>
</form>
<span id="loginresponse"></span>
And finally, login_ajax.php
<?php
echo $_GET['email'].$_GET['pass'].$_GET['t'];
?>
As mentioned above - I am only echoing the results, for know, as I'm knew to Jquery and AJAX, so I want to check if all fields are returning the values as expected, and one isn't...The token field.
You are chaining the object T of the input element and not the element's value to the query string of your GET request.
You should change this line
var T = $("#t"); // The object of the input element
to this
var T = $("#t").val(); // The value of the input element
Maybe what you want is:
var T = $("#t").val();
im using javascript validation to check for values within each form field before the form sends to the database but when i click submit the form still sends even without any values.
To test it i clicked on each of the fields to clear them and then tried submittin the button
here is the form
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/sbmit-button.png" name="submit" height="49" width="190" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres the javascript
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
im also linking to a jquery file:
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
ive tested it on its own and it seems to work but something seems to be over riding it and skipping past the validation in this page
==================================================================================
i still not working... basicallly do u think it might have something to do with the jquery UI datepicker that im also using with the form?? ive not included that in the form validation as i only wanted to make sure the firstname, lastname and email was filled out
i have this included in my form page:
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
</script>
would this be having an effect of it submitting even though there are no values in the fields?
something is definatley overriding the validation and submitting it
It's working for me! (but it's probably not working how you imagine it should)
Once you enter a valid email, the form is sent if you hit submit. Why? Because you have already filled in firstname and lastname for the user - with the strings First Name and Last Name!
So you shouldn't just check for empty or error string filled first and last names, but you should also trigger an error if the first name is First Name or the last name is Last Name.
// Check for empty value, the error string
// OR the default values of "First Name" and "Last Name"
if ((input.val() == "") ||
(input.val() == emptyerror) ||
(input.val() == "First Name") ||
(input.val() == "Last Name")) {
input.addClass("needsfilled");
Working example
(I assume you use server side validation as the final check, since people like me just love NoScript. )
(Also you declare 5 global variables at the top of your code and one more global in your for loop (i)... don't forget var.. just like you used for input)
What if I disabled JavaScript? You should (also) validate on the server side.
Also refactor your code! You can start with extracting methods.
You need to cancel the submit event. It looks like you're trying to do this with a return false or a return true. However, with jQuery you'll need to do it a slightly different way.
First, you'll need to have an argument name for the JavaScript event. I typically use e.
$("#theform").submit(function(e){
Then you'll need to update the following code as follows:
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
The e.preventDefault() stops the event from being processed. In this case, that means the form will not be submitted.
I'll try to explain this as best as I can.
I have a form that accepts multiple fields, and in the end, e-mails all the fields to a specific e-mail address.
So for example, I have three text boxes, one list box and two submit buttons.
Two of the text boxes are first name, and e-mail address
The third text box is used to populate the list box. So if I enter, NIKE, into the third text box and push the first submit button. Nike will now be in the listbox.
I want to be able to populate the list box with as many entries as needed, then push the second submit button to send all information (first name, e-mail address and all items in list box).
The problem is, pushing the first submit button always triggers the e-mail sent, since I'm "POST"ing.
I have everything working right now. The third text box submits the new data to a table in mysql, and then retrieves all the data and puts it in the list box.
What's the best way to fix this scenario? Could I stop the Post variable from validating, until the second submit button is used?
Also, I'd like to avoid Javascript, thanks
Make sure the two submit buttons have names. I.E: <input type="submit" name="command" value="Add"> and <input type="submit" name="command" value="Send">. Then you can use PHP to determine which one was clicked:
if($_REQUEST['command'] == 'Add')
{
// Code to add the item to the list box here
}
elseif($_REQUEST['command'] == 'Send')
{
// Code to send the email here...
}
BONUS: For extra credit, make the commands variables so they can be easily changed, and map them to functions...
<?php
$commands = array(
'doSendEmail' => 'Send Email',
'doAddOption' => 'Add Option',
);
function doSendEmail()
{
// your email sending code here...
}
function doAddOption()
{
// your option adding code here...
}
function printForm()
{
global $commands;
?>
Name: <input type="text" name="name"><br>
Email: <input type="text" name="name"><br>
<input type="text" name="add">
<input type="submit" name="command" value="<?= $commands['doAddOption'] ?>">
<select>
<?php /* some code here */ ?>
</select>
<input type="submit" name="command" value="<?= $commands['doSendEmail'] ?>">
<?php
}
if(isset($_REQUEST['command']))
{
$function = array_search($_REQUEST['command'],$commands);
if($function !== -1)
call_user_func($function);
}