2016-07-20 5 views
0

Использование Jquery Autocomplete, если вы наберете несколько букв (вы можете использовать выпадающее меню «Shawn», «Vinnie», «Lisa»), и вы можете выбрать его. Когда вы это сделаете, оно выдает имя в текстовом поле ниже. Однако, если вы выберете имя и выберите его, и поймите, что это было неправильное имя и вручную удалили его из текстового поля, оно, похоже, нарушит функциональность (т. Е. Если вы попытаетесь снова выбрать имя, вы можете, но это будет НЕ отображается в текстовом поле).Почему вручную удаляется мой автозаполнение JQuery?

Есть ли что-то очевидное, что я делаю неправильно?

Кроме того, обратите внимание, существует ли способ, чтобы только одно имя помещалось в текстовое поле, так как всегда должен быть только один диспетчер?

Вот полный код:

<?php 
session_start(); 
require_once('includes/databaseconfig.php'); 
//Get employees to put in the availablePlayers array for autocomplete 
    $sql = "SELECT * FROM users 
      ORDER BY lname"; 
      $allemployees = mysqli_query($con, $sql); 
      if (!$allemployees) { 
      die("Database query failed: " . mysqli_error($con)); 
      } else { 
        while ($row = mysqli_fetch_assoc($allemployees)) { 
         $supervisordata .= "{ value: \"" . $row['fname'] . " " . $row['lname'] . " \", 
             label: \"" . $row['fname'] . " " . $row['lname'] . "\", 
             icon: \"<img src='" . $row['picture'] . "'>\"},"; 
        } 
      } 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
<meta name="robots" content="noindex, nofollow"> 
<title>Reporting Request</title> 
<link href="style1.css" media="all" rel="stylesheet" type="text/css" /> 
<script src="https://use.fontawesome.com/4cb79c3742.js"></script> 
<link href='https://fonts.googleapis.com/css?family=Lato:400,400italic,700' rel='stylesheet' type='text/css'> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
<script> 
$(function() { 

     var availableSupervisors = [    
      <?php 
       echo $supervisordata; 
      ?> 
     ]; 

     function log(message) { 
      $("<div>").text(message).prependTo("#log"); 
      $("#log").scrollTop(0); 
     } 

     $("#supervisor").autocomplete({ 
      source: availableSupervisors, 
      html: true, 
      minLength: 2, 
      select: function(event, ui) { 
       log(ui.item ? 
        "" : 
        ""); 
      $('#log-supervisor').append(ui.item.value); 
      ui.item.value=""; //blank out input search field 
      } 
     }); 
});         
</script> 
</head> 
<body> 
<div class="wrapper"> 
<h1> Request Form</h1> 
<form id="submitRequest" action="" method="post"> 
    <div class="always heading"> 
    <i class="fa fa-users"></i>&nbsp;&nbsp;<span class="section-heading">Communication</span><br/><br /> 
    </div> 
    <div class="ui-widget always"> <span class="question">Requester Supervisor:</span> 
    <span class="toolwrapper"><i class="fa fa-question-circle-o"></i> 
    <span class="tooltip">Please enter the name of your supervisor.</span> 
    </span><input name="supervisor" id="supervisor" type="text" value="" class="textfield" placeholder="Type at least 2 letters of employee's name" /> 
       </div> 
      <div class="ui-widget always"> 
      <textarea name="supervisorlist" id="log-supervisor" class="ui-widget-content" placeholder="Names will appear here, separated by comma"></textarea> 
      <input type="hidden" name="hidden" value="hidden"/> 
    </div> 
</form> 
</div> 
</body> 
</html> 

ответ

1

Вы хотите обновить это:

$('#log-supervisor').append(ui.item.value); 

Для этого

$('#log-supervisor').val($('#log-supervisor').val() + ui.item.value); 

Потому что, когда вы делаете Append вы настраиваете текст узла и значений. Когда вы удаляете что-то в текстовой области, это просто узел, а значения не изменяются. Поэтому jQuery очистит область, и вы ничего не увидите.

1

Правильный способ установки содержимого текстового поля - это установить его значение, а не его HTML. HTML используется только как начальное значение, пока вы его не отредактируете. Поэтому используйте $('#log-supervisor').val(), а не $('#log-supervisor').append().

var availableSupervisors = [{ 
 
    value: "Mustafa Alsalihi ", 
 
    label: "Mustafa Alsalihi", 
 
    icon: "<img src='https://lh3.googleusercontent.com/-Yw5kveAfFm4/AAAAAAAAAAI/AAAAAAAAAAA/oUCWS4Gz_sQ/photo.jpg'>" 
 
}, { 
 
    value: "Annamarie Antonucci ", 
 
    label: "Annamarie Antonucci", 
 
    icon: "<img src='https://lh3.googleusercontent.com/-gPCKbvx1z5Y/AAAAAAAAAAI/AAAAAAAAAj8/rcU-c5GnWWI/photo.jpg'>" 
 
}, { 
 
    value: "Lisa Anzivino ", 
 
    label: "Lisa Anzivino", 
 
    icon: "<img src='https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg'>" 
 
}, { 
 
    value: "Lisa Barger ", 
 
    label: "Lisa Barger", 
 
    icon: "<img src='https://lh5.googleusercontent.com/-N6w14X7DIuw/AAAAAAAAAAI/AAAAAAAAAAA/lavHdb2Db9Q/photo.jpg'>" 
 
}, { 
 
    value: "Jane Barger ", 
 
    label: "Jane Barger", 
 
    icon: "<img src='https://lh6.googleusercontent.com/-E2YipzmL0WA/AAAAAAAAAAI/AAAAAAAAADo/Kz_NYSaGYyM/photo.jpg'>" 
 
}, { 
 
    value: "Simon Barrell ", 
 
    label: "Simon Barrell", 
 
    icon: "<img src='https://lh4.googleusercontent.com/-jkvQnB0249U/AAAAAAAAAAI/AAAAAAAAAA0/hhCIiI-XLS0/photo.jpg'>" 
 
}, { 
 
    value: "David Battino ", 
 
    label: "David Battino", 
 
    icon: "<img src='https://lh5.googleusercontent.com/-G0XfnLcjk8g/AAAAAAAAAAI/AAAAAAAAAYI/DZmBTIjjxA4/photo.jpg'>" 
 
}, { 
 
    value: "Danielle Bertini ", 
 
    label: "Danielle Bertini", 
 
    icon: "<img src='https://lh6.googleusercontent.com/-C2TiaG4pewU/AAAAAAAAAAI/AAAAAAAAABU/inTAogOkT3c/photo.jpg'>" 
 
}, { 
 
    value: "Riccardo Bocci ", 
 
    label: "Riccardo Bocci", 
 
    icon: "<img src='https://lh3.googleusercontent.com/-ZS7iS0BnleI/AAAAAAAAAAI/AAAAAAAAAAA/fbwFVjZyRsI/photo.jpg'>" 
 
}, { 
 
    value: "Kim Bostick ", 
 
    label: "Kim Bostick", 
 
    icon: "<img src='https://lh5.googleusercontent.com/-3_10CsSFh9Q/AAAAAAAAAAI/AAAAAAAAAAo/5sih1AiQvgE/photo.jpg'>" 
 
}, { 
 
    value: "Michael Brandsema ", 
 
    label: "Michael Brandsema", 
 
    icon: "<img src='https://lh4.googleusercontent.com/-h7Pskz9xEYo/AAAAAAAAAAI/AAAAAAAAAaQ/Ar5CA-SktFI/photo.jpg'>" 
 
}]; 
 
$(function() { 
 

 

 
    function log(message) { 
 
    $("<div>").text(message).prependTo("#log"); 
 
    $("#log").scrollTop(0); 
 
    } 
 

 
    $("#supervisor").autocomplete({ 
 
    source: availableSupervisors, 
 
    html: true, 
 
    minLength: 2, 
 
    select: function(event, ui) { 
 
     log(ui.item ? 
 
     "" : 
 
     ""); 
 
     $('#log-supervisor').val(function(i, oldvalue) { 
 
     return oldvalue + " " + ui.item.value; 
 
     }); 
 
     ui.item.value = ""; //blank out input search field 
 
    } 
 
    }); 
 
});
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
 
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
 
<div class="wrapper"> 
 
    <h1> Request Form</h1> 
 
    <form id="submitRequest" action="" method="post"> 
 
    <div class="always heading"> 
 
     <i class="fa fa-users"></i>&nbsp;&nbsp;<span class="section-heading">Communication</span> 
 
     <br/> 
 
     <br /> 
 
    </div> 
 
    <div class="ui-widget always"> <span class="question">Requester Supervisor:</span> 
 
     <span class="toolwrapper"><i class="fa fa-question-circle-o"></i> 
 
    <span class="tooltip">Please enter the name of your supervisor.</span> 
 
     </span> 
 
     <input name="supervisor" id="supervisor" type="text" value="" class="textfield" placeholder="Type at least 2 letters of employee's name" /> 
 
    </div> 
 
    <div class="ui-widget always"> 
 
     <textarea name="supervisorlist" id="log-supervisor" class="ui-widget-content" placeholder="Names will appear here, separated by comma"></textarea> 
 
     <input type="hidden" name="hidden" value="hidden" /> 
 
    </div> 
 
    </form> 
 
</div>

Смежные вопросы