1

I have a problem with loaded form. It doesn't trigger any events. Here's the form:

<form id ="form1" method="post" action="newjsp.jsp">
<h2>Form1</h2>
<p>
<span style="margin-left: 4px">Number:</span>
<input type="hidden" name="form_number" value="1"/>
<input class="textBox" type="text" name="number" value=""/>
</p>
<p>
<input id="the_button" type="submit" name="submit_button" value="Set"/>
</p>
</form>

I've tried basic examples with .on(), .live() and .delegate(), but none of those seems to work. I want to validate if number is 11 digits long. If not, stop submitting. Here's jQuery:

$("#form1").submit(function e(){
if($(".textbox").length != 11)
    {
        e.preventDefault();
        $("#output").append("<p style='color:red;'>Please enter a valid number!</p>");
    }
});

Thanks!

4

2 回答 2

1

Use event delegation with .on() because the form is dynamically created. Also you have the e argument in the wrong place so your preventDefault() call would fail.

$(document).on('submit', '#form1', function(e){
    if($(".textBox").val().length != 11)
    {
        e.preventDefault();
        $("#output").append("<p style='color:red;'>Please enter a valid number!</p>");
    }
});

Also you have a problem with your textBox class name, in the form you use textBox but in the Javascript you use textbox. Finally, use $('.textBox').val().length to get the length not $('.textBox').length. The latter will only give you the number of elements that were selected, not the number of characters in the input value.

于 2013-08-20T12:29:00.540 回答
-1

Move "e" inside the parenthesis and it works:

$("#form1").submit(function(e){
if($(".textbox").length != 11)
    {
        e.preventDefault();
        $("#output").append("<p style='color:red;'>Please enter a valid number!</p>");
    }
});
于 2013-08-20T12:28:42.240 回答