jQuery Autocomplete with dynamic textfield generated - php

i'm trying to use jquery autocomplete with dynamic textfield generated, autocomplete works but the main problem is i cant populate textfield with name 'alamat' properly. How to set current textfield 'alamat' value properly in autocomplete ?
HTML
<form id="myForm" name="myForm" method="post">
<table id="myTable" border="1" cellpadding="1" cellspacing="1">
<thead>
<th>No</th><th>Nama</th><th>Alamat</th>
</thead>
<tbody></tbody>
</table>
<input id="addButton" name="addButton" type="button" value="Add an input" />
<input id="removeButton" name="removeButton" type="button" value="Remove an input" />
</form>
JS
<script type="text/javascript">
var counter = 1;
$(function() {
var options = {
source: 'autocomplete.php',
minLength: 2,
focus: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
},
select: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
}
};
$('input.searchNama').live("keydown.autocomplete", function() {
$(this).autocomplete(options);
});
var addInput = function() {
if (counter > 1){
$('input#removeButton').removeAttr('disabled');
}
var inputHTML = ' <tr><td><div id="' + counter + '">'+ counter +'</div></td><td><input type="text" id="nama_' +counter + '" class="searchNama" name="nama_' + counter +' " value="" /></td><td><input type="text" id="alamat_' + counter + '" class="searchAlamat" name="alamat_' + counter + '" value="" /></td></tr>';
$(inputHTML).appendTo("table#myTable tbody");
$("input.searchNama:last").focus();
counter++;
};
var removeInput = function() {
counter--;
if(counter == 1){
$('input#removeButton').attr('disabled','disabled');
counter++;
console.log('Jika Counter == 1 :' + counter);
} else {
$("table#myTable tbody tr:last").remove();
console.log('Jika Counter != 1 :' + counter);
}
};
if (!$("table#myTable tbody").find("input.searchNama").length) {
addInput();
}
$("input#addButton").click(addInput);
$("input#removeButton").click(removeInput);
});
</script>
my autocomplete.php generate JSON result
[{
"label": "Aditya Nursyahbani - Jl. Bratasena IX Blok U6 No. 7",
"value": "Aditya Nursyahbani",
"alamat": "Jl. Bratasena IX Blok U6 No. 7"
},
{
"label": "Slamet Aji Pamungkas - Jl. Melati 2 No. 3",
"value": "Slamet Aji Pamungkas",
"alamat": "Jl. Melati 2 No. 3"
}]
I upload my script on fiddle in this link!
thanks in advanced.

$('input.searchAlamat').val(ui.item.alamat);
Your selector will populate all inputs with class='searchAlamat' that are contained in the page.
WIthin the select callback, this will be the current input instance that autocomplete is bound to so you can traverse within the row it is in:
$(this).closest('tr').find('input.searchAlamat').val(ui.item.alamat);
DEMO
Note that I removed focus functionality

Related

jquery variable in php echo

I have this jquery script (slider):
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function(event, ui) {
$("#amount").val(ui.value);
}
});
$( "#amount" ).val( $("#slider-range-max").slider("value") );
});
</script>
This is my html outout:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
I want the value of my slider stored as a php variable.
To call upon a php code that might have some logic in it, you need to have your html and javascript in a file, then your php code in a different file, like so :
html_file.php (contains only html template and javascript).
html part:
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range-max"></div>
Javascript part:
<script>
$( function() {
$( "#slider-range-max" ).slider({
range: "max",
min: 1,
max: 25,
value: 1,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
},
change: function(event, ui) {
$.post('php_file.php', {slider_val: ui.value}).done(
function(result) {
//your php code sends result back here.
//do something with result.
console.log(result);
}
);
}
});
$( "#amount" ).val( $( "#slider-range-max" ).slider( "value" ) );
});
</script>
php_file.php (contains the php code and logic).
you then retrieve the value in your php code like so:
<?php
//$slider_val contains the value of your slider
$slider_val = $_POST['slider_val'];
//you can output the value back to your javascript like so
echo $slider_val;
You can send the input value to php like this
HTML
<input type="text" placeholder="Amount" onkeyup="send(this.value)">
SCRIPT
<script>
function send(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("value").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "send.php?value=" + str, true);
xmlhttp.send();
}
</script>
PHP
$value = $_REQUEST["value"];
echo $value;
Try this. Hope it helps to solve your problem.

Assinging numeric number to rows and after delation come back to proper order

I have some issues with my code:
first is row assigning number. It does not assign the numeric number
to first row
secondly how to pre-assign the Discount to 0 and it can be editable if I want to change.
The images of my problems are attached below.
Doesn't assign the numeric number to first row
On delete some row it doesn't automatically , in a proper numeric order e.g on deleting 2 & 4 it does not come back to 1, 2, 3
My jquery code is
a
<script type="text/javascript">
$(document).ready(function() {
$('#data').DataTable( {
"scrollY": "460px",
"scrollCollapse": true,
"paging": true
} );
} );
$(function(){
$('body').delegate('.discount,.quantity,.price','keyup',function(){
var tr = $(this).parent().parent();
var dis = tr.find('.discount').val();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var total = (qty*price) -(dis);
tr.find('.amount').val(total);
totals();
});
$('.pay').change(function(){
var pay = $(this).val()-0;
var subtoal = $('.subtotal').val()-0;
$('.payback').val(pay-subtoal);
});
$('.datavalue').click(function(){
var id =$(this).data('id');
var name =$(this).data('name');
var price =$(this).data('price');
addrow(id,name,price);
});
$('body').delegate('.remove','click',function(){
var tr = $(this).parent().parent();
tr.remove();
totals();
});
});
function addrow(id,p,p2)
{
$('.count').each(function(idx){
$("td:first", this).html(idx+1);
});
var tr = '<tr class= count>'+
'<td></td>'+
'<td><input type="text" name="product_name[]" value=" '+ p +' " class="form-control product_name"><input type="hidden" name="product_id[]" value=" '+ id +' " class="form-control product_name"></td>'+
'<td><input type="text" name="quantity[]" value="1" class="form-control quantity"></td>'+
'<td><input type="text" name="price[]" value=" '+ p2 +' " class="form-control price"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="amount[]" class="form-control amount"></td>'+
'<td>Del</td>'+
'</tr>';
$('.details').append(tr);
}
function totals()
{
var tt = 0;
$('.amount').each(function(e,i){
var amt = $(this).val()-0;
tt += amt;
});
$('.subtotal').val(tt);
}
function OpenPopupCenter(pageURL, title, w, h) {
var left = (screen.width - w) / 2;
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3
var targetWin = window.open(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}
</script>
To number your rows, you can use jQuery each:
$('tr').each(function(row_number) {
$(this).find('td').first().text(row_number + 1);
});
Call this when you add or delete a row and it will correct your problem.

JQUERY autocomplete get id instead of value

I have a mysql database where I would like to use the autocomplete one.
So far I am able to receive the results of the query.
For example this is the result: [{"LNAME":"Napoleon","id":"1"}]
But I want the id of the customer in this case to be filled in another input field of my form. (so in Napoleons case I want the "1" to be filled in to my clienteID field of the form)
At the moment the field does not get updated.
Here's the HTML part:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
minLength: 3,
select: function(event, ui) {
$('#clienteId').val(ui.item.id);
},
});
});
</script>
<form name='form_update_details' id='form_update_details' method='post' action=''>
<input type='text' name='clienteName' id='tag'>
<input type='text' name='clienteId' id='clienteId'>
</form>
Then the php part:
<?php
include("include/db.php");
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$sql="SELECT ID, CONTACTS_LNAME, CONTACTS_FNAME FROM CRM_CONTACTS WHERE CONTACTS_LNAME LIKE '%$my_data%' or CONTACTS_FNAME LIKE '%$my_data%' ORDER BY CONTACTS_LNAME";
$result = mysqli_query($coni,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
$data[] = array(
'LNAME' => $row['CONTACTS_LNAME'],
'id' => $row['ID']
);
}
echo json_encode($data);
flush();
}
?>
Try with a sample data:use label and value as keys instead of LNAME and id. Use event.preventDefault(); to set the label in #tag field otherwise by default it will set the value.
var data = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$(document).ready(function(){
$("#tag").autocomplete( {
source: data,
minLength: 3,
select: function(event, ui) {
event.preventDefault();
$("#tag").val(ui.item.label);
$('#clienteId').val(ui.item.value);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<form name='form_update_details' id='form_update_details' method='post' action=''>
<input type='text' name='clienteName' id='tag'>
<input type='text' name='clienteId' id='clienteId'>
</form>
Try this:
$( function() {
var projects = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
});
Html:
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id">
Demo Fiddle

AJAX not working within form and instantly sending me to PHP script? PHP/AJAX

I've currently got a feature on my web application where you can add your skills by clicking the "Add a Skill" button, very simple and worked up until I tried to add something else into the mix. The error is the fact that when I click the "Add a Skill" button it acts as if that were the submit button and try's to execute the php script skills/add
I'm currently trying to make it so that my application constantly checks whether the text which the user is typing exists within the database which is represented with a green tick or red cross if it doesn't exist.
What I'm asking is can anyone see why this is not working as it should be?
VIEW
<form method="post" action="skills/add" id="container">
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill-' + $num + '" name="skill-' + $num + '" placeholder="What\'s your skill?"></div><img id="tick" src="/images/tick.png" width="16" height="16"/><img id="cross" src="/images/cross.png" width="16" height="16"/>');
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
console.log($('#autoskill'));
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('.inputField').keyup(skill_check);
function skill_check(){
var skill = $('.inputField').val();
if(skill == "" || skill.length < 4){
$('.inputField').css('border', '3px #CCC solid');
$('#tick').hide();
}else{
jQuery.ajax({
type: "POST",
url: "skills/auto",
data: 'name='+ skill,
cache: false,
success: function(response){
if(response == 1){
$('.inputField').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('.inputField').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>
<button class="addNew submitButton"> Add a Skill </button><br>
<div id="newFields"></div>
<input type="submit" class="submitButton" value="Save Skills">
</form>
Thanks for your help in advance.
You should use absolute path to your php script..
jQuery.ajax({
type: "POST",
url: "full-path-to-your-script",
If you are sending the form via AJAX you don't want this:
<input type="submit" class="submitButton" value="Save Skills">
You want this:
<input type="button" class="submitButton" value="Save Skills" onClick="SomeAJAXFunction()">
You can add return false to one of your functions.
<input type="button" class="submitButton" value="Save Skills" onClick="return FunctionWithReturnFalse()">
As you pointed out in your comment above, you have a JS error on the page. If you were to indent your code correctly, you would discover that it is probably due to a missing } to close the else after your ajax call:
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill-' + $num + '" name="skill-' + $num + '" placeholder="What\'s your skill?"></div><img id="tick" src="/images/tick.png" width="16" height="16"/><img id="cross" src="/images/cross.png" width="16" height="16"/>');
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
console.log($('#autoskill'));
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('.inputField').keyup(skill_check);
function skill_check(){
var skill = $('.inputField').val();
if(skill == "" || skill.length < 4){
$('.inputField').css('border', '3px #CCC solid');
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "skills/auto",
data: 'name='+ skill,
cache: false,
success: function(response){
if(response == 1){
$('.inputField').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('.inputField').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
// MISSING } HERE
}
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>

Posting and retrieving Multiple Text box values using Jquery and PHP

I have Jquery code that can create multiple text boxes .Now, i want to submit my text boxes' values so that i could get them using PHP on next page.I want to submit text box in the same way as ( )
and on the second page,i could get values using POST method.How can i i post multiple text values in this case and how can i retrieve them on the next page using php?? Plz help as i am a new bee.
CODE:
<head>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--; $("#TextBoxDiv" + counter).remove(); });
$("#getButtonValue").click(function ()
{
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
Try to giving name for text boxes as array
e.g. input type='textbox' name='textbox[]' id='textbox1'
and access it on PHP page as array
$arrayRequest = $_REQUEST['textbox'];

Categories