views:

112

answers:

2

I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.

This is the existing form

 <form id = "submit" method="post">
  <label for="link_website_url">Create a short url</label>
  <input id="link_website_url" name="link" size="30" type="text" />
  <input class="go" name="commit" type="submit" value="Go!" /></form>
A: 
$('#submit').submit(function(){
  var url = $('#link_website_url').value();
  var val = <do your processing here>;
  $('#link_website_url').value(val);
  return false; 
});
andylei
A: 
$('#submit').submit(function(){
  var url = $('#link_website_url').val(); //http://example.com/12345
  var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
  if(num > -1){
    $('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
  }else{
    $('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
    return false; //error, so cancel this submit
  }
});

 

If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:

var checkFailed = false;
$('#submit').submit(function(){
  var url = $('#link_website_url').val(); //http://example.com/12345
  var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
  if(num > -1){
    $('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
    $('#error_link_web_url').remove();
  }else{
    $('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
    checkFailed = true;
  }

  /*Other checks...*/    

  if(checkFailed){
     return false; //cancel submit
  }
});
micahwittman