0

I'm creating a contact form and I'm validating it with jQuery. However, if I use class .control-group, my code isn't doing anything. But it works fine if I don't use .control-group with it. Here's the html:

<form class="form-horizontal" id="contact">
    <div class="control-group" id="nimi">
        <label class="control-label">Nimi</label>
        <div class="controls">
            <div class="input-prepend"> <span class="add-on"><i class="icon-envelope"></i></span>
                <input type="text" placeholder="Nimi" name="nimi">
            </div>
        </div>
    </div>
    <div class="control-group" id="sposti">
        <label class="control-label">Sähköposti</label>
        <div class="controls">
            <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span>
                <input type="text" placeholder="Sähköposti" name="sposti">
            </div>
        </div>
    </div>
    <div class="control-group" id="viesti">
        <label class="control-label">Viesti</label>
        <div class="controls">
        <textarea name="viesti"></textarea>       
        </div>
    </div>
    <div class="control-group">
        <label class="control-label"></label>
        <div class="controls">
        <input type="submit" class="btn btn-success sendbutton" value="Lähetä">       
        </div>
    </div>
</form>​

And the javascript:

$(document).ready(function(){
    $('.sendbutton').click(function(){
        var nimi = $('input[name=nimi]').val();
        var viesti = $('input[name=viesti]').val();
        $('.control-group').removeClass("error");

        if(nimi == ""){
          $('.control-group #nimi').addClass("error");
          return false;    
        }
        if(viesti == ""){
          $('.control-group #nimi').addClass("error");
          return false;    
        }
    });
});​

And a fiddle about this: http://jsfiddle.net/GDXCE/ And a fiddle if I don't use class control-group: http://jsfiddle.net/WgAZC/1/

What I'm doing wrong with the selectors?

4

3 回答 3

2

改变这个:

$('.control-group #nimi').addClass("error");

至:

$('.control-group#nimi').addClass("error");

#nimi不是您的.control-group元素的后代之一。

<div class="control-group" id="nimi">

http://jsfiddle.net/tTBRx/

由于您通过 ID 选择元素并且 ID 是唯一的,因此无需使用其他选择器。

$('#nimi').addClass("error")
于 2012-10-07T15:47:31.770 回答
1

你在选择器之间放置一个空格

.control-group #nimi

表示有一个 id = nimi 的元素是具有类 .control-group 的元素的后代

正确的版本应该是

.control-group#nimi

如果 class 和 id 都属于同一个元素。

于 2012-10-07T15:47:14.110 回答
0

.control-group在您的选择器中,在和之间放置一个空格#nimi将查找#nimi是 的子元素.control-group,而不是进一步定义.control-group您想要的。尝试这个:

if(nimi == ""){
    $('.control-group#nimi').addClass("error");
    return false;    
}

CSS 选择器参考

于 2012-10-07T15:51:48.553 回答