javascript jquery errors unable to resolve - javascript

I've been getting some errors with my javascrript and i can't figure out
what is wrong. I just made a simple jQuery statement to check if an email field
had a default value and if so, clear the field
Here is the jsFiddle link to the code i am working with: http://jsfiddle.net/qLfBH/
I can't figure out why the jslint is complaining about the line 5 "missing semicolon" and such.
$(document).ready(function () {
var email_default = "Enter your email address...";
$(':input').filter('[type="email"]').attr('val', email_default).focus({
if ($(this).val() == email_default) ;{
$(this).attr('val', ' ');
}
});
});
I have also tried using firebug to debug, but the javascript would not show in the scripts panel- probably because of some syntax error. Any help would be much appreciated.
UPDATE
I edited the code but its still complaining about a "missing semicolon" (see link to fiddle http://jsfiddle.net/qLfBH/3/)
$(document).ready(function () {
var email_default = "Enter your email address...";
$(':input').filter('[type="email"]').attr('value', email_default).focus({
if ($(this).val() == email_default) {
$(this).attr('val', ' ');
}
});
});
FIXED
Ok thanks for the help everyone. I forgot the "function" under the focus. I corrected the errors below and its working :)
$(document).ready(function () {
var email_default = "Enter your email address...";
$(':input').filter('[type="email"]').attr('value', email_default).focus(function () {
if ($(this).val() == email_default) {
$(this).attr('val', ' ');
}
});
});

Several issues. Here's a cleaned up version:
var email_default = "Enter your email address...";
$(':input[type="email"]').val(email_default).on('focus', function () {
if ($(this).val() == email_default) {
$(this).val(' ');
}
});
jsFiddle example
Note, you could also forgo the jQuery and use HTML5's placeholder attribute with just:
<input type="email" placeholder="Enter your email address...">

Remove the semi colon after you if statement
FROM
if ($(this).val() == email_default) ;{ // <----SHOULDNT BE THERE
$(this).attr('val', ' ');
}
TO
if ($(this).val() == email_default) {
$(this).attr('val', ' ');
}

See updated :
$(document).ready(function () {
var email_default = "Enter your email address...";
$('input[type="email"]').val(email_default).focus(function () { //<-- add function()
if ($(this).val() == email_default) { //<-- removed semicolon here
$(this).val(' '); //<-- either .attr('value',' ') or .val(' ')
}
});
});
Sample

Replace your JavaScript code with this
$(document).ready(function () {
var email_default = "Enter your email address...";
$('input').filter('[type=email]').val(email_default).focus(function() {
if ($(this).val() == email_default) {
$(this).val('');
}
});
});

Related

Jquery/php form have to click Submit Twice Why?

I have a simple form with jquery and php
whenever someone clicks the submit button they have to click it twice
Heres my jQuery
$('#submit_btn').on('click', function(){
var post_data, proceed, user_email, user_message, user_name, user_phone;
user_name = $("input[name=name]").val();
user_email = $("input[name=email]").val();
user_phone = $("input[name=phone]").val();
user_message = $("textarea[name=message]").val();
proceed = true;
if (user_name === "") {
$("input[name=name]").css("border-color", "red");
proceed = false;
}
if (user_email === "") {
$("input[name=email]").css("border-color", "red");
proceed = false;
}
if (user_phone === "") {
$("input[name=phone]").css("border-color", "red");
proceed = false;
}
if (user_message === "") {
$("textarea[name=message]").css("border-color", "red");
proceed = false;
}
if (proceed) {
post_data = {
userName: user_name,
userEmail: user_email,
userPhone: user_phone,
userMessage: user_message
};
$.post("contact_me_test.php", post_data, (function(response) {
var output;
if (response.type === "error") {
output = "<div class=\"error\">" + response.text + "</div>";
} else {
output = "<div class=\"success\">" + response.text + "</div>";
$('#contact-form-container').fadeOut(function(e){
$('#form-success-message').fadeIn();
});
$("#contact_form input").val("");
$("#contact_form textarea").val("");
}
$("#result").hide().html(output).slideDown();
}), "json");
}
});
Heres my jQuery
Is there something that requires to thing to be pressed twice here? I looked around online for hours and some people were saying you need to take the validation out of it but I've tried that and i get the same results.
Everything regarding the form is working fine the only thing is that you have to click TWICE
Try with this code:
$('#submit_btn').on('click', function(evt){
evt.preventDefault();
... //Rest of code
}

Using focus() in JavaScript

I am trying to use JavaScript to Make Focus on Text Box.But It does't works,Please tell the way to Using focus() and set null value for that text Box.
Script:
<script type="text/javascript">
$(document).ready(function ()
{
var str = ('#ViewData["ControlView"]'); //alert(str);
if (str == "1")
ShowProduct();
else
ShowGrid();
});
var message = ('#ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
document.getElementById("Item_Code").value ="";
document.getElementById("Item_Code").focus();
}
View:
#Html.TextBox("Item_Code", "", new { #Maxlength = "10", id = "Item_Code" });
The code for focus() in Javascript is:
var message="message";
if(message=="")
{
document.getElementById("Item_Code").focus();
document.getElementById("Item_Code").value=="";
}
Jquery solution
<script type="text/javascript">
$(document).ready(function ()
{
var str = ('#ViewData["ControlView"]'); //alert(str);
if (str == "1")
ShowProduct();
else
ShowGrid();
});
var message = ('#ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
$("#Item_Code").val("");
$("#Item_Code").focus();
}
Try using jQuery it's easier and clean
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#Item_Code').focus();
});
});
</script>
In this script block
<script type="text/javascript">
$(document).ready(function ()
{
var str = ('#ViewData["ControlView"]'); //alert(str);
if (str == "1")
ShowProduct();
else
ShowGrid();
});
var message = ('#ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
document.getElementById("Item_Code").value ="";
document.getElementById("Item_Code").focus();
}
declaration and using message variable and document.getElementById function call not in ready function, so if declaration of yours textbox after this then in call document.getElementById("Item_Code") return null, because element with this id has not yet been rendered
for solve put code
var message = ('#ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
document.getElementById("Item_Code").value ="";
document.getElementById("Item_Code").focus();
}
in ready function like this:
$(document).ready(function ()
{
var str = ('#ViewData["ControlView"]'); //alert(str);
if (str == "1")
ShowProduct();
else
ShowGrid();
var message = ('#ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
document.getElementById("Item_Code").value ="";
document.getElementById("Item_Code").focus();
}
});

Trying to do email validation but it isn't working as intended

I'm just making some form validation with jQuery, this is the part for the email:
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = $('#user_email');
$('#user_email').on('keyup change', function() {
if ((email.val().length <= 6) && (re.test(email.val()))) {
$('#alert_user_email').text('Email cannot be blank or invalid formation');
submit_btn.disabled = true;
$('#alert_user_email').show();
} else {
$('#alert_user_email').text('');
submit_btn.disabled = false;
$('#alert_user_email').hide();
}
});
But for some reason it isn't working, everything works fine if I remove the && re.teststuff from the if statement but isn't working as intended, any enlightenment would be great!
Your if statement is incorrect. Try:
if ((email.val().length <= 6) || !(re.test(email.val()))) {
// your code
}

how i do extract .text(data) value to put it inside conditional statement

What I'm trying to do here is to disable a button when a username exists. otherwise, the button is enabled. i'm not adept at javascript/jquery, so I might need a tiny help. any would be appreciated:
$('#username2').keyup(function() {
var username = $(this).val();
$('#username_status').text('searching....');
if(username2 != "") {
$.post('username_check.php',{username2:username}, function(data) {
$('#username_status').text(data);
});
}
else {
$('#username_status').text('Nothing');
}
if ($('#username_status').text(data) != 'Username available!') {
$("#btnSignUp").prop("disabled", false);
} else {
$("#btnSignUp").prop("disabled", true);
}
});
i'm guessing the way i did my conditional statement is wrong.
It should be.
$('#username_status').text()
This will give you the correct textual content
if ($('#username_status').text() != 'Username available!') {
$("#btnSignUp").prop("disabled", false);
} else {
$("#btnSignUp").prop("disabled", true);
}
You need to do the check inside the AJAX request:
$('#username2').keyup(function() {
var username = $(this).val();
if(username != "") {
$('#username_status').text('searching....');
$.post('username_check.php',{username2:username}, function(data) {
$('#username_status').text(data);
$("#btnSignUp").prop("disabled", data != 'Username available!');
});
}
else {
$('#username_status').text('Nothing');
$("#btnSignUp").prop("disabled", true);
}
});
You can keep the button disabled by default.
<input id="btnSignUp" name="btnSignUp" disabled="disabled" type="button" value="Sign Up" />
If the user name is available, you can enable it by
$("#btnSignUp").removeAttr('disabled');
Also you can get compare Strings as below
$("#username_status").val() != 'Username available!'

replace span text (error) after retyping vars jquery javascript

Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.

Categories

Resources