1

你能看看这个链接,让我知道为什么当它被包装在一个<form> ... </form>标签中时我不能验证它吗?
正如您从代码中看到的那样,我可以在仅在内部声明 is 时对其进行验证,<fieldset> </fieldset>我试图将其移动id="contact_form"到 form 标记中:

<form id="contact_form"> 

但它也没有用!正如我所说,我可以在没有的情况下完成这个过程,<form>但我必须从 Bootstrap 3 框架中添加我的样式:

<form class="form-inline" role="form" id="contact_form">

这是我的整个 HTML 代码:

<form class="form-inline" role="form" id="contact_form">
<fieldset id="contact_form">
<legend>My Contact Form</legend>
    <div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>

    <label for="email"><span>Email Address</span>
    <input type="text" name="email" id="email" placeholder="Enter Your Email" />
    </label>

    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" placeholder="Phone Number" />
    </label>

    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>

    <label><span>&nbsp;</span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    </label>
</fieldset>
</form>
4

1 回答 1

1

您必须防止表单标签内提交按钮的默认行为。我想这就是你要找的:

http://jsfiddle.net/9LFVX/1/

        $("#submit_btn").click(function(e) { 
            e.preventDefault();
            //get input field values
            var user_name       = $('input[name="name"]').val(); 
            var user_email      = $('input[name="email"]').val();
            var user_phone      = $('input[name="phone"]').val();
            var user_message    = $('#contact_form textarea').val();

            //simple validation at client's end
            //we simply change border color to red if empty field using .css()
            var proceed = true;
            if(user_name==""){ 
                $('input[name="name"]').css('border-color','red'); 
                proceed = false;
            }
            if(user_email==""){ 
                $('input[name="email"]').css('border-color','red'); 
                proceed = false;
            }
            if(user_phone=="") {    
                $('input[name="phone"]').css('border-color','red'); 
                proceed = false;
            }
            if(user_message=="") {  
                $('#contact_form textarea').css('border-color','red'); 
                proceed = false;
            }
于 2013-11-11T20:06:08.510 回答