2014-05-15 17 views
-1

我正在爲我的網站創建一個表單,並且我想將自定義屬性設置爲「required」。我有幾個輸入ID「必需」。類似於:Javascript - 用特定Id編輯第一個空輸入

<input type="text" id="required"> 
<input type="text" id="required"> 
<input type="text" id="required"> 

我有一個腳本,它給出了一些屬性並初始化彈出窗口。但是這是一個問題。我想創建一個腳本,它將搜索沒有文本的輸入,並將首先在數組中執行。這是有效的,但只在第一次輸入。如果我在那裏寫東西,腳本不起作用,什麼都不會發生。

下面是代碼(我知道它也不適用於第一次輸入,但我希望這會幫助您理解我想實現的目標)。

$('#check').click(function() { 
var x = $("input").filter(function(){ 
    return $("#required").val().trim() == ''; 
}); 
x[0].val(''); 
x[0].addClass("input-error"); 
x[0].attr({ 
    "data-toggle": "popover", 
    "data-container": "body", 
    "data-content": "Wypełnij to pole", 
    "data-trigger": "manual" 
}); 
x[0].popover('show'); 
$('html, body').animate({ 
    scrollTop: $("#required").offset().top-100 
}, 200); 

}); 
x[0].keypress(function() { 
x[0].removeClass("input-error"); 
    x[0].popover('destroy'); 
}); 
+7

第一條規則,絕不重複的ID。 –

+2

使用class而不是id來對元素進行分組 –

回答

1

的Javascript:

$('#check').click(function() { 
    var x = $("input[id=required]").filter(function() { 
     return $(this).val().trim() == ''; 
    }); 

    $(x).each(function (index) { 
     $(this).val(''); 
     $(this).addClass("input-error"); 
     $(this).attr({ 
      "data-toggle": "popover", 
      "data-container": "body", 
      "data-content": "Wypełnij to pole", 
      "data-trigger": "manual" 
     }); 
     $(this).popover('show'); 
     $(this).keypress(function() { 
      $(this).removeClass("input-error"); 
      $(this).popover('destroy'); 
     }); 
    }); 

    if(x.length > 0) { 
     $('html, body').animate({ 
      scrollTop: $(x[0]).offset().top-100 
     }, 200); 
    } 

}); 

的jsfiddle HTML俱樂部 http://jsfiddle.net/GnRdH/4/