tags:

views:

31

answers:

2

I'm trying to use JQuery to check upon submission if a field input has the default value, and, if it does, to stop submission and alert the user. What I have works up to a point. But no matter what I put into the input field, submission is stopped and the text is changed to the alert text.

Here is the JQuery:

$('#submitQuestion').submit(function() {
if($('#topic').val('at least one topic, separated by commas')
{
   $('#topic').removeClass('inactive');
   $('#topic').addClass('notice');
   $('#topic').val('Please include at least one topic');
   return false;
}
return false;
});

The other problem I have is blanking out the default text once the text has been changed to notify the user. Right now I just have strings instead of variables, and for some reason it only works (partially) if I use '==' in certain places. Right now, the first if condition in the focus function works, but not the elseif condition. Currently I have this code:

$('#topic').focus(function(){
  if(this.value=='at least one topic, separated by commas')
  {
$(this).val(' ');
  } elseif(this.value=='Please include at least one topic')
  {
$(this).val(' ');
$(this).removeClass('notice');
  }
 });

 $('#topic').blur(function(){
   if(this.value==' ')
   {
   $(this).val('at least one topic, separated by commas');
   $(this).addClass('inactive');
   }
 });

Obviously, my mastery of JQuery is, well, not as such. But I appreciate any help.

+1  A: 

To submit a form in else part retrun true not false Answer to first question `

submit form : http://api.jquery.com/submit/

$('#submitQuestion').submit(function() {
if($('#topic').val('at least one topic, separated by commas')
{
   $('#topic').removeClass('inactive');
   $('#topic').addClass('notice');
   $('#topic').val('Please include at least one topic');
   return false;
}
else
 return true;
});

Answer 2 :

store string values in variable and use === syntax for equal operation and its else if not elseif so the updated script is

var defaultTextFocus = 'at least one topic, separated by commas';
var defaultTextVal = 'Please include at least one topic';
$('#topic').focus(function(){
  if(this.value=== defaultText)
  {
     $('#' +this.id).val(' ');
  } else if(this.value=== defaultTextVal)
  {
     $('#' +this.id).val(' ');
     $('#' +this.id).removeClass('notice');
  }
 });
Pranay Rana
Your answer to Q2 worked like magic, but I still can't get the form to do anything on the submit event. I can get it to blank out the default text or switch it out. Any other tips?
tchaymore
for the first question check this link :http://api.jquery.com/submit/ which might help you to resolve issue
Pranay Rana
A: 

With jQuery you SET a form value like so:

$('#topic').val('text here')

But if you want to GET the value, such as to check it against a value, you would use the val() function with no parameters, like so:

if ( $('#topic').val() == 'at least one topic, separated by commas' ) {
    ...
}
babtek