Require that the input is in the datalist - javascript

I have an form input of type datalist, in this list is about 5000 options, because of the large amount of options a select form just is not practical as you are allowed to type and it suggests what you want with a datalist.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2><label class='control-label' style="font-size: 20px;">Product code</label></h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
This is what i have now, however the user can type and submit things that are not in the list and i can not allow this. How can i stop this from happening?

Alert the user if the field has a incorect value
$('input[type="submit"]').on('click',function(e) {
$datalistval= $('#ItemSelect').val();
if ($('option[value="'+$datalistval+'"]').length == 0) //if no option is found alert the user
{
alert('incorect datalist value');
e.preventDefault();
}
});
jsfiddle: https://jsfiddle.net/ev63ghwk/

If you're willing to use jQuery UI's autocomplete this would work:
<?php // tweak the below to use your data
$arr = array( array('Name' => 'one'), array('Name' => 'two'), array('Name' => 'three') );
$optsArr = array();
foreach ($arr as $a) {
array_push( $optsArr , '"'.htmlentities( $a["Name"] ).'"' ); ;
}
$options = implode(",", $optsArr)
?>
var availableTags = [<?php echo $options ?>];
$(function() {
$( "#ItemSelect" ).autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// ui.item property is null if the input was not found in the list
$("#ItemSelect").val("");
}
}
});
});
Here's a working Demo

Related

Jquery Codeigniter - Autocomplete not working

I am facing a problem with autocomplete in codeigniter. When inserting some text on input, it shows a dropdown but no value in there. Looks like this: Screenshot
Viewing error on console : Screenshoot
Here is my code :
Model
var $unit_table = "sales_unit";
public function getUnit($searchTerm)
{
$this->db->like('nopol', $searchTerm, 'both');
$this->db->order_by('nopol', 'ASC');
$this->db->limit(10);
return $this->db->get($this->unit_table)->result();
}
Controller
function jsonUnitAutocomplete()
{
if (isset($_GET['term'])) {
$result = $this->m_admin->getUnit($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}
View
<input type="text" class="form-control" name="npl" id="drop-npl"><br>
<input type="text" class="form-control" name="tyunit"><br>
<input type="text" class="form-control" name="kg"><br>
<input type="text" class="form-control" name="seat"><br>
<script>
$(document).ready(function() {
$("#drop-npl").autocomplete({
source: "<?php echo site_url('control_admin/jsonUnitAutocomplete') ?>",
select: function(event, ui) {
$('[name="npl"]').val(ui.item.nopol);
$('[name="tyunit"]').val(ui.item.type);
$('[name="kg"]').val(ui.item.kategori);
$('[name="seat"]').val(ui.item.seat);
}
});
});
</script>
Isn't you just read incorrect query param name? and in the Controller you not declare else statement for your if-else, so the result will be undefined
From what I noticed, I assumed No.Polisi is input text with the name "npl". So you can change 'term' on your controller into 'npl', like below:
function jsonUnitAutocomplete()
{
if (isset($_GET['npl'])) {
$result = $this->m_admin->getUnit($_GET['npl']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}

CodeIgniter process multi input fields added with jQuery

I have a form adding data into db. I have single input field and button which add more input fields on click. My question is how to grab in controller all inputs and send it to model. My code so far is:
jQuery:
<script>
$('a').click(function(e){
$('#inp').append('<div><input class = "new_input" type=text name="name[]"/><a class="remove_field "href="#"> X</a><div><br/>');
$('.remove_field').click( function(e){
e.preventDefault();
$(this).parent('div').remove();
})
});
</script>
form:
<?php
// Forma za unos podataka
echo $this->session->flashdata('item');
echo '<h4>Unesite podatke</h4>';
echo '<div id="warning"></div>';
$att = array('name'=>'form','onsubmit'=>" return validation()");
echo form_open('admin/crud/adding/',$att);
echo form_label('Novi podatak:', 'input_data_info') . br() . br();
$data = array(
'name' => 'input_data_info',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
echo form_input($data) . br() . br();
echo '<div id="inp"></div>';
echo "<a href='#'>".'Novi unos'."</a>" .br() .br();
echo form_submit('save', 'Snimi') . br() . br();
echo form_submit('add', 'Dodaj').br();
echo form_close();
?>
controller:
$input_data_info = (string)$this->input->post('input_data_info', TRUE);
//model za dodavanje podataka
$this->load->model('Data');
$query = $this->Data->add($input_data_info);
The first input field name is 'input_data_info' and then JQuery adds input fields with 'name[ ]'
As you want to pull the data from all the input fields, they , first need to have a common name.
So, rename the input field that you have created initially in the form to name= 'name[]' that makes your code:
$data = array(
'name' => 'name[]',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
Then in you controller use something like this:
$all_input_data = $this->input->post('name');
//the $all_input_data is an array containing all your input values.

how to create an autocomplete textbox in wordpress?

Hi i am developing a plugin in wordpress.
i tried code for create autocomplete text box in my customized form.
Ajax Calling function
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
foreach($result as $dis)
{
$data.=$dis->city."<br>";
}
echo $data;
die();
}
add_action( 'wp_ajax_city_action', 'city_action_callback' );
add_action( 'wp_ajax_nopriv_city_action', 'city_action_callback' );
Shortcode function
function my_search_form() {
?>
<script>
jQuery(document).ready(function($) {
jQuery('#city').keyup(function() {
cid=jQuery(this).attr('val');
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
//alert(response);
});
});
});
</script>
<input type="text" id="city" name="city" autocomplete="off"/>
<?php
}
this code return related results perfectly in variable response.
But i don't know how create a text box look like a autocomplete box.
Please explain me how to do that in wordpress?
Just add a div under the input tag
HTML Code:
<input type="text" id="city" name="city" autocomplete="off"/>
<div id="key"></div>
replace the div after the success on you ajax.
Ajax Code:
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
$('#key').html(response);
});
PHP Code:
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
echo '<ul>'
foreach($result as $dis)
{
echo '<li>'.$dis->city.'</li>';
}
echo '</ul>'
die();
}

copy value of jquery UI auto-complete in select function to a textfield?

I created this javascript wherein it will create a row of textfield for multiple insertion purposes.. My problem is I'd like to add an auto complete wherein it will query the data inserted on the text field from the database and fill its remaining data record on other textfield. It seems I having a problem in putting the data on the textfield since its id is incremented.
here's my code:
HTML
<form name="zxc" method="POST">
<div id="sit" align="center"><label><input type="text" id="set" name="set" placeholder="Set number of rows..."></label>
<button type="button" id="cret" class="btn btn-warning btn-sm" onClick="createinput();hide();autoComp();">Add rows</button></div>
<br>
Javascript
function autoComp(){
$(function(){
var id2=0;
var num = parseInt(document.forms["zxc"]["set"].value);
if(!num) return;
for(var count=1;count<=num;count++, id2++){
$("#unit"+id2).autocomplete({
source:'search2.php',
minLength:1,
select:function(evt, ui) {
this.form.description+id2.value = ui.item.description;
this.form.unit_value+id2.value = ui.item.unitValue;
}
});
}
});
}
PHP
include '../core/database/config.php';
$term= $_GET["term"];
$rs= mysql_query("SELECT unit,description,unitValue FROM csr_inventory where unit like '%".$term."%' order by unit");
$data = array();
if ( $rs && mysql_num_rows($rs) ) {
while( $row = mysql_fetch_array($rs) )
{
$data[] = array(
'value' => $row['unit'] ,
'description' => $row['description'] ,
'unitValue' => $row['unitValue']
);
}
}
echo json_encode($data);
flush();
please help me solving this problem... :(

Autocomplete empty if don't select

What I need to know how to clear the textbox if the user type only 1 character and don't select on the list? I also have a ajax in autocomplete.php which I need to get the value send to textbox.
This what I have right now.
</script>
function changeAutoComplete (val) {
$( "#tags" ).autocomplete({
mustMatch: true,
source: 'autocomplete.php?selected='+val,
response: function(event, ui) {
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
$(this).val("");
return false;
$("#empty-message").css({display:'', overflow: 'hidden'});
} else {
$("#empty-message").empty();
$("#empty-message").css({display:'none', overflow: 'hidden'});
}
}
});
}
</script>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="demo-frame">
Tags
<input id="tags" name="items">
<div id="empty-message" style="display:none;"></div>
</div>
autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["term"]);
$selected = $mysqli->real_escape_string($_GET["selected"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND cat_code='$selected' GROUP BY id ORDER BY item" );
if($sql)
{
$str = array();
while($row=mysqli_fetch_array($sql))
{
$str[] = $row['item'];
}
echo json_encode($str);
}
?>
In your case it better to do this with blur event. Here go with this
$('#tags').on('blur', function () {
if ($(this).val().length === 1) { //check for no. of characters entered
$(this).val(''); // clear the textbox
}
});
JSFiddle
Updates:
As from your comments, it would be better to go with change event,
change: function (event, ui) {
if (!ui.item) {
$(this).val("");
$('#empty-message').show();
} else {
$('#empty-message').hide();
}
}
JSFiddle

Categories