0

I have two radio buttons connected to a search-field that controls what type of search the user wants.
One for regular keyword search, and another for license plate search.

The "keyword" radio button is pre-selected, but when a license plate pattern is detected, I would like to have it switched over to "licence plate" automatically using jQuery if that's possible...

The license plate pattern will allways start with two letters (A-Z), followed by five numbers (0-9) like this: "AZ12345". Possibly sepparated with a space like this: "ZA 98765".

Form method is _GET.

ThomasK
  • 2,210
  • 3
  • 26
  • 35
  • Do you want it to happen client- (javascript) or serverside (PHP)? Please choose, and show us the relevant markup – Bergi Aug 27 '12 at 09:45

2 Answers2

3

Following your instructions you can use this pattern to detect license plates

 [A-Za-z]{2}\s?\d{5}

If you want to match only plates (eg not liasdjfaAG 00212lkfla) use ^[A-Za-z]{2}\s?\d{5}$ instead.

You can use the textchanged event (look at this answer), then you can change the "checked" state of the radio button if the pattern is matched.

EDIT:

Implemented in jsfiddle, basically the code looks like this

var rege = /^[A-Za-z]{2}\s?\d{5}$/;

$('#inpt').keyup(function(event) {
    if (rege.test($('#inpt').val())) {
        $('#plate').attr('checked', true);
    } else {
        $('#nonplate').attr('checked', true);
    }
});

with an html like this:

<input type="text" id="inpt"/><br/>
<input type="radio" name="group1" id="plate" value="Plate"> Plate<br>
<input type="radio" name="group1" id="nonplate" value="NotPlate"> Not Plate

EDIT 2:

In response to your request I suggest you to read this question. Basically with setInterval() you can check the state of the input every 1 or 2 seconds to select the correct radio button. You might shorten this interval as well (setting it to ~100 ms)

Community
  • 1
  • 1
Gabber
  • 5,152
  • 6
  • 35
  • 49
  • didn't get it. How do I use the expression with jquery? Tried `if ($('#Search').val().match('^[A-Za-z]{2}\s?\d{5}$')){ // if there's a match, then make licens plate radio button checked }`... – ThomasK Aug 28 '12 at 09:46
  • I edited my question, however if you need a more precise answer post your html code with the textinput and radio buttons, I think it's going to work :) – Gabber Aug 28 '12 at 11:56
  • When I copy/paste it doen't register the text. Is there a way to check for that aswell? – ThomasK Aug 28 '12 at 14:09
0

I believe what you need is this:

function checkPlate($s) {
  $match = false;
  $s = strtoupper($s);
  $s = str_replace(" ","",$s);
  if (strlen($s) == 7) {
    preg_match(/[A-Z]{2}[0-9]{5}/, $s, $matches);
    if (count($matches) == 1) {$match = true;}
  }
  return $match;
}
ipoga
  • 394
  • 2
  • 12