2017-01-09 9 views
0

リスト項目を表示する検索ボックスがあり、ユーザーがボタンをクリックすると検索フィールドがクリアされますが、ユーザーは再び検索する予定でしたか?だから、ページが唯一の新しい検索結果が表示され、別の検索がaction'dのときに検索結果をクリアする方法

var noNameFound = true; 
var searchedStudent = []; 

// Stores names in an array where names can be pulled and shown when button is clicked 
var studentArr = []; 

$('.student-list').children().each(function(){ 
    studentArr.push(this); 
}); 

// this will search through the array to locate the student. 
$('.userSearch').on('click', function(){ 
    //stores users search into a variable 
    var searchRequest = $('#search-input').val(); 

    //search through array here... 
    for (var i = 0; i < studentArr.length; i++) { 
     var studentstr = studentArr[i].innerText; 

     if (studentstr.indexOf(searchRequest) !== -1) { 

      console.log('YAY!! the name:: ' + searchRequest + ' ::is in our list'); 
      $(".student-list li").css("display","none"); // removes all students from the list. 

      searchedStudent.push(studentArr[i]); 
      $(searchedStudent).show(); // displayes the searched student. 

      noNameFound = false; 
     } 
    } 

    // removes stundent-item if no user can be found, and asks user to click buttont to refresh page. 
    if (noNameFound) { 
     var errorMessage = $('<p class="errMessage">Sorry but we were unable to locate the name you were looking for, <br> please click <button class="refresh">here</button> to refresh the page and try again.</p>'); 
     $(".student-list").prepend(errorMessage); 
     $('.student-item').css('display', 'none'); 
     $('.refresh').on('click', function(){ 
      location.reload(); 
     }); 
    } 

    if(noNameFound){ 
     //stops users searching an empty search field. 
     $('.userSearch').prop('disabled',true); 

     $('#search-input').keyup(function(){ 
      $('.userSearch').prop('disabled', this.value === ""? true : false); 
     }); 
    } 

}); 

以前ませんこれは、私はあなたがクリックイベントハンドラでforループの前にsearchedStudent配列をリセットする必要があり、これまで

+0

私は、あなたがクリックした後に配列を削除しないと思うより多くのコードを必要とします$( '。userSearch')の後に追加してみてください。on( 'click'、function()... searchedStudent = [ – riso

+0

heres my fiddle https://jsfiddle.net/qvk8rzpm/ – mrpbennett

+0

あなたはそれにもhtmlコードを追加する必要があります – riso

答えて

0

持っているものです。

// rest of the code 

// this will search through the array to locate the student. 
$('.userSearch').on('click', function(){ 
    //stores users search into a variable 
    var searchRequest = $('#search-input').val(); 

    searchedStudent = []; // <<<<<<<<<<<<<<< HERE 

    //search through array here... 
    for (var i = 0; i < studentArr.length; i++) { 
     var studentstr = studentArr[i].innerText; 

// rest of the code 

実は、あなたは完全にsearchedStudent配列を削除し、まだ機能を実現する。..それを試してみることができます。

+0

よく、簡単に、私は関数内で配列を宣言しなければならなかったのですが、なぜ私は理解できますか?しかし、この1人のメイト...助けてくれてありがとう – mrpbennett

関連する問題