How can I use autocomplete textbox in a dynamic textbox
In the image below, the first textbox is working, autocomplete is showing but the second and third or 4th textbox autocomplete does not work. The textbox/input should show autocompletion of names.
Is there a way to fix this?
My Input texts
<td><input type="text" name="name[]" id="autouser" placeholder="Enter Signatory Name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
Dynamically add inputs - I have tried to place #autouser in the script codes but still it does not work
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td>'+
'<input type="text" name="name[]" id="autouser" placeholder="Enter Signatory Name" class="form-control name_list" />'+
'</td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button>'+
'</td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
Autocomplete input code.
<script type='text/javascript'>
$(document).ready(function(){
// Initialize
$("#autouser").autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url: "<?php echo base_url(); ?>users/userList",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autouser').val(ui.item.label); // display the selected text
$('#userid').val(ui.item.value); // save selected id to input
return false;
}
});
});
</script>
If ever needed:
Controller:
Use for autocomplete
public function userList(){
// POST data
$postData = $this->input->post();
// Get data
$data = $this->user_model->getUsers($postData);
echo json_encode($data);
}
Model
function getUsers($postData){
$response = array();
if(isset($postData['search']) ){
// Select record
$this->db->select('*');
$this->db->where("username like '%".$postData['search']."%' ");
$records = $this->db->get('employees')->result();
foreach($records as $row ){
$response[] = array("value"=>$row->employee_id,"label"=>$row->username);
}
}
return $response;
}
Related
I'm trying to put a Select2 box inside a while loop. But it only works the first select tag. Although loop works fine, the select tag is not working after the first 1. how can I fix this issue?
I also tried adding printing PHP unique id to fix it. but nothing happened.
<select type="text" name="city" id="city-<?php echo $id; ?>" class="form-control"></select>
This is the javascript part:
<script type="text/javascript">
$('#city-<?php echo $id; ?>').select2({
placeholder: 'Select city',
ajax: {
url: 'processes/cities.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
I'm expecting all the select boxes to work fine. But actually, only first 1 works.
It would be helpful if you provided the loop in your code example.
The most likely problem is that your id's are not unique. If you have multiple tags with the same id then javascript will only recognize the first one.
Here's an example to demonstrate.
https://jsfiddle.net/n8vxjoc1/1/
<div id="city-1">Content</div>
<div id="city-1">Content</div>
<script>
jQuery( '#city-1' ).html( jQuery( '#city-1' ).length );
</script>
Only the 1st element will change and it will display the number 1.
From the W3C specs:
The id attribute specifies its element's unique identifier (ID).
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
You should give the select dropdowns a class and target that instead.
E.g.
https://jsfiddle.net/n8vxjoc1/1/
<select name="city" class="select2 form-control">…</select>
<select name="city" class="select2 form-control">…</select>
<script type="text/javascript">
$('select.select2').select2({});
</script>
You can take help from this link: Demo
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
PHP:
<?php
include 'config.php';// add your config details on that file
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
JS
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
The issue I am having is that I need the search results to be displayed in a link or a . Right now they display into a text input field. When I try to change it to a link or div no text is generated. I am almost certain it has to do with the java/jquery script I have. The script I am using is an open source script that I need for simple reasons.
What I have tried is changing the element in which the script calls for from an input to a div or a href. I have googled and tried to find some sort of reference to which the script selects what elements to display the code into and the only thing I can identify as being the problem is, "userid = ui.item.value; // selected id to input".
index.php - Script
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.username', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var name = response[0]['name'];
var displayid = response[0]['displayid'];
document.getElementById('name_'+index).value = name;
document.getElementById('displayid_'+index).value = displayid;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function(){
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='username' id='username_"+index+"' placeholder='Enter username'></td><td><input type='text' class='name' id='name_"+index+"' ></td><td><input type='text' class='displayid' id='displayid_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
</script>
index.php - Html
<div class="container">
<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Search</th>
<th>Name</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<tr class='tr_input'>
<td><input type='text' class='username' id='username_1' placeholder='Enter username'></td>
<td><input type='text' class='name' id='name_1' readonly></td>
<td><input type='text' class='displayid' id='displayid_1' readonly></td>
</tr>
</tbody>
</table>
<br>
<input type='button' value='Add more' id='addmore'>
</div>
getDetails.php
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM item_template WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['entry'],"label"=>$row['name']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM item_template WHERE entry=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['entry'];
$name = $row['name'];
$displayid = $row['displayid'];
$users_arr[] = array("entry" => $userid, "name" => $name,"displayid" => $displayid);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I except the selector is wrong in the script, where it selects where to copy the text to.
You just need to use innerHTML instead of value.
document.getElementById('name_'+index).innerHTML = name;
document.getElementById('displayid_'+index).innerHTML = displayid;
and change the input tag to div tag. You might want to read more about innerHTML.
I have a list of elements which are gotten from a xml file and I write them down in a table. In every row, I have a form which send the input field values to a jquery script, but it always pass the first value of the table, Does anyone knows how to pass the selected value?
This is my html and php code:
<?php
$licenseElement = "";
foreach ($xml->xpath("/Resultado/Registro") as $licenseElement):?>
<form>
<input type="hidden" id="desactivate" name="desactivate" value="" />
<input type="hidden" id="name" name="name" value="<?php echo $licenseElement->nombre; ?>" />
<input type='button' value='Desactivate' onclick='myCallDesactivate(desactivate,name);' />
</form>
<?php endforeach; ?>
And this is the jquery script:
<script>
function myCallDesactivate(desactivate,name) {
var val1 = $('#desactivate').val();
var val2 = $('#name').val();
var request = $.ajax({
url: "mypage.php",
data: { desactivate: val1, name: val2 },
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#mybox2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
}
</script>
I am having some trouble with passing a javascript value to php and back.
The idea is that I have a form where a user fills out a postal code and is then (onBlur) presented with the correct street and city in two different input fields. The street and city are collected by POST method from an external php file (getAddress.php).
I know that the php script returns the correct values and the complete() function is called onBlur, but I don't know whether the value gets passed onto the php script and back.
Javascript
<script language="javascript">
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if(postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "html",
data: dataString,
success: function(results) {
var json = JSON.parse(results);
document.getElementById("street").value = json.street;
document.getElementById("city").value = json.city;
}
});
}
}
</script>
getAddress.php
<?php
$postalCode = $_POST['postalCode'];
$postalCode = substr_replace($postalCode, ' ', 4, 0);
$sql = 'SELECT * FROM postalCodes WHERE postalCode="'.$postalCode.'"';
$res = $con->query($sql);
$res->data_seek(0);
while($row = $res->fetch_assoc()) {
$ID = $row['ID'];
$street = $row['street'];
$city = $row['city'];
$results[] = array('ID' => $ID, 'street' => $street, 'city' => $city);
}
echo json_encode($results);
?>
HTML
<input name="postalCode" type="text" maxlength="6" onBlur="complete()" /><br />
<input name="street" id="street" type="text" disabled /><br />
<input name="number" type="text" maxlength="6" /><br />
<input name="city" id="city" type="text" disabled /><br />
Change dataType: "html", to dataType: "json", and your $results is array so you need to use index
Try this:
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if (postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "json",
data: dataString,
success: function(results) {
document.getElementById("street").value = results[0].street;
document.getElementById("city").value = results[0].city;
}
});
}
}
As you are getting 500 internal server error message one of the reason can be that
$con->query($sql) is failing, make sure $con is initialized and table and field name are correct.
I have a table and a script that makes each cell an input field when clicked on the edit button at the end of a row.
I submit the edited data via Ajax, but I want to make the input field back to normal text after I have edited it.
Here is the code:
//// EACH CELL INTO INPUT FIELD ////
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
var submit = "<input type='button' name='Submit' value='Submit' />";
tr.find(".button").html(submit);
});
});
//// END ////
//// ONCLICK SUBMIT SEND DATA VIA AJAX ////
$(".button input[type=button]").live('click', function() {
var data = $('form#muuda').serialize();
// post data using ajax
$.ajax({
type: "POST",
url: "index.php?leht=kast",
data: data,
success: function(data) {
alert("Andmed muudetud"); // show response from the php script.
}
});
});
//// END ////
HTML:
<form id="muuda" method="post" action="#">
<table>
<?PHP
$sql="SELECT * FROM nimed";
$result = mysql_query($sql)or die(mysql_error());
WHILE ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr class="row">';
echo '<td class="td" title="id">'.$row["id"].'</td>';
echo '<td class="td" title="eesnimi">'.$row["eesnimi"].'</td>';
echo '<td class="td" title="perenimi">'.$row["perenimi"].'</td>';
echo '<td class="button" title="button"><button class="edit">Edit</button></td>';
echo '</tr>';
}
?>
</table>
</form>
Here is a picture of the preview:
https://lh6.googleusercontent.com/-vVnabdBzFlA/UBjTRhifpWI/AAAAAAAACAo/RvAgpi7x2ik/s488/Ajax%2520submit.jpg
You can just reverse the process you use to turn it from text to an input box:
tr.find('.td').each(function () {
var value = $(this).find('input').val();
$(this).html(value);
});
You will have to set the variable tr to the right row, of course.