1

This is my html button code

<div class="form-group">
    <label>Name</label>
    <input type="text" class="form-control" name="name" />
    <div class="help-block with-errors" style="font-size:12pt">Input Only Alphabet</div>
</div>
 <input class="btn btn-primary" type="submit" value="SUBMIT" id="button1 style="height:50px; width:100px" />

This is my jQuery

<script type="text/javascript">
    $("#button1").click(function(){
        if($("#name").val() == null)
            alert("haha");

        if($("#name").val() == [a-z])
            alert("zzzz");
    });
</script>

My problem is i only can validate the first condition. Everytime i try 2nd condition it wont work. Anyone can help see what is my problem??

Ron
  • 37
  • 5

1 Answers1

3

This is invalid syntax*:

if($("#name").val() == [a-z])

You could do what you want with a regular expression:

if($("#name").val().test(/^[a-z]$/))

The additional ^ and $ require the element's value to be just that one character, with nothing before nor after it.

Secondly, your input does not have an id attribute, so jQuery will not find anything with $("#name"). For that to work your input element must have id="name":

<input type="text" class="form-control" name="name" id="name"/>
                                                    ^^


* technically, it is in fact correct syntax, but for something entirely different: it would look up variables a and z, subtract them, and use the result for a single-element array literal, which would not give the expected result.
trincot
  • 317,000
  • 35
  • 244
  • 286
  • [*Use `.test()`*](http://stackoverflow.com/a/10940138/645186). Also, probably that character set should have the starting `^` and ending position `$` specifiers. So, the check would actually make more sense with the equality. – Shef Apr 30 '16 at 19:16
  • i tried but i still keep show me HAHA no matter what i type – Ron Apr 30 '16 at 19:18
  • @Ron, could you add to your question the HTML of the `name` element? Does it have the `id='name'` attribute? – trincot Apr 30 '16 at 19:20
  • It does not have the `id` attribute. You need that. When you reference `$('#name')`, jQuery does not find your input, unless it has that `id` (not `name`). Could you please also fix the error in the other HTML? There is a closing double quote missing after `button1`. – trincot Apr 30 '16 at 19:36
  • @Ron, did this solve your issue? Could you give some feed-back? – trincot May 02 '16 at 06:53