Setting value of item in jquery - javascript

I have a code that will grab the value from a text box once a button is clicked, run it through an external database and then return a result to me. That result will then be placed into another text box.
My issue is that the coding I have takes a little bit too long (At least I think this is the issue) to get a result from the external database, and sets the value of the text box when it is not ready.
<script type="text/javascript">
// Declaring the variable.
var mname = "";
$('#btnMN').click(function() {
//Pull data from name
var name = $(this).closest('tr').find(':input[type="text"][name="name[]"]').val();
//Run through database
$.post('test1.php', { name: name}, function(data){
mname = data;
});
//Set text box with return data
$(this).closest('tr').find('.master').val(mname);
mname = "";
});
</script>
I cannot put the "Set text box with return data" part in another function, because I will then lose the "this" selector telling it exactly which text box to set, because I have a dynamic form that I can add/remove rows to.
<tr id="input_11" style="margin-bottom:4px;" class="clonedInput">
<td valign="top" align="right" style="padding-right: 10px;"><span style="color:#00CD00;"><BR>Victim:</span></td>
<td valign="top">Name:<input type="text" name="name[]" size="35"/><input type="button" id="btnMN" value="Mastername Check" /></td>
<td class="master">Mastername:<textarea readonly class="master" name="master[]" rows="8" cols="28"></textarea></td>
<td>Statement:<textarea name="statement[]" rows="8" cols="28" placeholder="Paste statement here."></textarea></td>
</tr>

$.post() is an asynchronous (that's the "a" in "ajax") call. So it sends a request but continues processing the rest of the function while it waits for a response. Anything based on that response must go in the callaback.
$('#btnMN').click(function() {
//Pull data from name
var name = $(this).closest('tr').find(':input[type="text"][name="name[]"]').val();
//Store element we want to update
var master = $(this).closest('tr').find('.master');
//Run through database
$.post('test1.php', { name: name}, function(data){
master.val(data);
});
});

Set the value in your callback function.
$.post('test1.php', { name: name}, function(data){
$(this).closest('tr').find('.master').val(data);
});

Related

access a specific input in an input array

<td><input type="text" name="product_code[]" id="product_code1" class="form-control input-sm" /></td>
I have been creating an invoice system ... how can I access a specific input to get its text ( product code ) and load the description from the database???
I know how to access all the elements but cannot access the specific one the user is typing text :(
using the below code trying to get the value returns all the values of the product code text inputs and only works for the first one
$('[name="product_code[]"]').keyup(function() {
var values = $("input[name='product_code[]']")
.map(function(){return $(this).val();}).get();
alert(values);
});
#AlexisGarcia lets say user types product code I want to access the db and retrieve product description for that product code ... how do I get through javascript or jquery the value of the specific input the user is typing???
You have to use AJAX to get that from Database.
First you need to get what the user has typed (input value), and then send it to AJAX. Here is an example:
$('#product_code1').keyup(function(){
var user_text = $(this).val();
$.ajax({
method: 'post',
url: 'link_to_your_controller',
data: {text: user_text},
dataType: 'json',
complete: function(data) {
//..DO SOMETHING WITH RESULT FROM DB
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<input type="text" name="product_code[]" id="product_code1" class="form- control input-sm" />
</td>
You need to learn about AJAX to do what you need.
You can start by reading https://www.w3schools.com/xml/ajax_intro.asp
$('.input-sm').keyup(function() {
var values = $(this).val();
alert(values);
});
Try this code, you will get what you want

SQL lag with jquery variables

I have this strange issue, which is hard for me to describe to be honest.
For testing purposes I have set up a SQL db containing id (autoincrement), first name, last name.
I have 2 entries there.
I call the db and list the entries in inputs like this:
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<div id='$id'>
<form method='post'>
<p>ID: <input type='text' name='id' id='id".$id."' value='$id' /></p>
<p>New first name: <input type='text' name='fname' id='fname".$id."' placeholder='$fname' /></p>
<p>New last name: <input type='text' name='lname' id='lname".$id."' placeholder='$lname' /></p>
<input type='submit' name='update' class='update' value='ID = $id' />
</form>
</div>";
}
Works perfectly fine and I get a page with both entries and a button to update them.
I am updating them with this function
$('.update').click(function(){
var row = $(this).parent().parent().attr('id'); // I've stored the SQL id in the parent div
// construct the input ids so i know where I am getting the data from
var idSource = '#id'+row;
var fnameSource = '#fname'+row;
var lnameSource = '#lname'+row;
// store the input values in variables
var id = $(idSource).val();
var fname = $(fnameSource).val();
var lname = $(lnameSource).val();
// use ajax to update sql table
$.ajax({
url : 'aiai.php',
method : 'post',
data : {id: id, fname: fname, lname: lname},
success: function(response){
console.log(response);
}
});
});
I am doing this so that every entry can be edited & updated on it's own.
An while this basically working I am getting a strange lag.
Example:
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am
getting the old value again
When I refresh the page I get the name update I just saved
Lag continues until I refresh the page
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am getting the old value again
When I refresh the page I get the name update I just saved.
Lag continues until I refresh the page.
It's like that info gets cached in the browser.
BUT, and this confuses me:
When I hardcode the inputs where I am calling the values from, everything works perfect.
So when I use
var id = $('#id2').val();
... instead of
var id = $(idSource).val();
... I am not experiencing this lag.
Anyone got an idea what I am doing wrong?

change id attr's value using jquery

I have a table whose data is fetched from the database, and this table's each td's id is also dynamically unique ( td's id value is equal to database's table value ). In each td, when anyone double click on it, an input field is appeared, when the user edits an input field, I have made an Ajax call (using onblur), and update this td's field in the database. which will be worked I guess, Now I want to change that td's id value, which will come from database (Ajax call).
for example::
My table code ::
<td id="2*Name>Engr._C.F._Zaman" class=" "> Engr. C.F. Zaman </td>
this td's id is generated from database, where first 2 is id of the table's id, after (*) is the db table's column name [Name] and after (>) is the value of that column's whose id is 2
when anyone click on this td, he/she will get an input field just like as given below::
<td id="2*Name>Engr._C.F._Zaman" class=" ">
<input type="text" class="form-control" id="sabbir" value="Engr._C.F._Zaman" name="Name" onblur="AjaxChange('2', 'Name', 'Engr._C.F._Zaman', '2*Name>Engr._C.F._Zaman');">
</td>
this is generated using jquery onclick event.
Now if any change of above input field, AjaxChange is called. and my AjaxChange code is ::
function AjaxChange( id, Attr, tdValue, td ) {
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
// first I want to change the id of td, which value will be data
// td's id format is id*Attr>data
// next show data in the td with out input field
// <td id="id*Attr>data"> data </td>
}
});
}
Now How can I change this td's id attribute?
Solution to immediate problem.
<td id="2*Name>Engr._C.F._Zaman" class=" ">
<input type="text" class="form-control" id="sabbir"
value="Engr._C.F._Zaman"
name="Name"
onblur="AjaxChange('2', 'Name', 'Engr._C.F._Zaman', '2*Name>Engr._C.F._Zaman', this);">
</td>
Script function
function AjaxChange( id, Attr, tdValue, td, element ) {
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
//Set ID
$(element).closest("td").prop('id', YourNewID)
}
});
}
However, I would strongly recommend you to refactor your code and use data-* attribute. Heres example
HTML
<td class="" data-value="2*Name>Engr._C.F._Zaman" data-id="2" data-attr="Name" data-name="Engr._C.F._Zaman" >
<input type="text" class="form-control name-txt"
value="Engr._C.F._Zaman"
name="Name">
</td>
JavaScript
$('.name-txt').on('blur', function(){
var self = $(this);
var cell = self.closest("td");
var id = cell.data('id');
var Attr= cell.data('Attr');
var name= cell.data('name');
var tdValue = cell.data('value');
$.ajax({
url: "ajax_call.php", // this is just update the db
type: "POST",
data: { table: "life", id=id, name=Attr, value=tdValue }, //
dataType: "html",
done: function(data) {
//Update values using
cell.data('id', YourNewID)
}
});
})
I suppose you meant using javascript/jquery, meaning the easiest way to reach the id would be using jqueries "attr"-function.
Now the question is what selector you should use, I guess in this case that your input fields id ("sabbir") is sufficient enough. You will have to decide this on your own.
$("#sabbir").closest("td").attr("id", yourNewId);
As answer to the other question in your comment:
$("#"+yourNewId).html(data);
Should work to replace the tds HTML.
your's ID 2*Name>Engr._C.F._Zaman which come from Database, is bad. Because special char is not always give result what you want, you should avoid this special char. You can use data-* to store your Database information then you don't have to change your ID every time.

Passing values into a function via JQuery Onclick

AIM
I'm trying to create a form that lets users select an item, and then displays the item's details once the user has selected an item. However, before i do that, i am trying to test if it would be possible by creating a simple testpage which replaces the item details to be displayed with a simple alert
Code(JQuery):
<!--Function to display item details upon selection-->
<script type="text/javascript">
function LoadDetails(cat,subcat,item)
{
return function(){
alert("Values are passed through successfully.Category is"+cat+", subcategory is"+subcat+"and item is"+item);
}
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#itemsubcat").hide();
$("#item").hide();
$("#submititem").hide();
$("#itemcat").load("getcategory.php");
$("#itemcat").change(function(){
var cat=$("#itemcat").val();
$("#itemsubcat").show();
$("#itemsubcat").load('getsubcategory.php?cat='+cat);
});
$("#itemsubcat").change(function(){
var cat=$("#itemcat").val();
var subcat=$("#itemsubcat").val();
$("#item").show();
$("#item").load('getitem.php?cat='+cat+'&subcat='+subcat);
});
$("#item").change(function(){
$("#submititem").show();
});
var cat=$("#itemcat").val();,
var subcat=$("#itemsubcat").val();,
var item=$("#item").val();,
$("#submititem").bind('click',{param:cat,subcat,item},LoadDetails);
});
});
</script>
Code(Html):
<table>
<tr>
<td><select id="itemcat" /></td>
<td><select id="itemsubcat" /></td>
<td><select id="item" /></td>
<td><input type="button" id="submititem" name="submititem" value="Get Item" /></td>
</tr>
</table>
Problem
When i click 'submititem', the alert pops up successfully, but the values cat,subcat and item are shown as undefined instead of the values that were supposed to be passed through.How would i pass data/values through to the function LoadDetails?
Solutions tried:
I've tried using .bind(), but to no avail.
E.g
var cat=$("#itemcat").val();,
var subcat=$("#itemsubcat").val();,
var item=$("#item").val();,
$("#submititem").bind('click',{param:cat,subcat,item},LoadDetails);
Question:
Would it be possible to use the function LoadDetails to retrieve the item details form my database(through PHP) and then echo it out ?
To pass a value to a function with an event, the syntax is :
$("#submititem").bind('click', LoadDetails(cat, subcat, item));
jsFiddle for exemple.
For your question, your code seems to be only client-side but if you want to load data from your server I suggest you to read this learn jQuery ajax
To get the values selected in the drop downs, you can just do this:
function LoadDetails()
{
var cat=$("#itemcat").find(":selected").text();
var subcat=$("#itemsubcat").find(":selected").text();
var item=$("#item").find(":selected").text();
alert("Values are passed through successfully.Category is"+cat+", subcategory is"+subcat+"and item is"+item);
}
This is strictly client-side, it doesn't talk to the server.

Pass two values of input fields to script and combine for searching

In my current project, i have two text fields in which user will input requirement and area respectively. Grabbing those values, i have to do an ajax call and fetch the necessary data from the database and return it. The ajax call has to be made as and when the input exceeds 4 characters in any of the text fields. As long as there was only one text field i didn't have any problem.
<input type="text" value="requirement" onkeyup="function1(this.value)" />
<input type="text" value="area" onkeyup="function2(this.value)" />
<script>
function function1(valuetosearch)
{
//make the ajax call
}
</script>
<script>
function function2(valuetosearch2)
{
//make the ajax call
}
</script>
How can i combine the two scripts and pass the data in ajax as an array? P.S The main reason for scripting is to do a search combining the two input fields. For example if someone enters house, vehicle in requirement field and place1,place2 in area field. The result search should display the result for the following1) place1 house2) place1 vehicle3) place2 house4) place2 vehicle
you can set id for each elemnt and get the other's value using
document.getElementById("id1").value
and then make the ajax request
http://jsfiddle.net/JMpgU/
$("input").keyup( function () {
var str = $(this).val() + " " + $(this).siblings().val();
alert(str);
//make the ajax call
});
with any number of inputs:
http://jsfiddle.net/JMpgU/2/
$("input").keyup( function () {
var strings = $(this).
siblings().
addBack().
map(function () {
return $(this).
val();
}).
toArray();
//make the ajax call
});
Try this
<input type="text" value="requirement" onkeyup="functionABC()" id="First" />
<input type="text" value="area" onkeyup="functionABC()" id="Second" />
<script>
function functionABC()
{
var searchString=$("#First").val()+" "+$("#Second").val();
//make the ajax call
}
</script>
Pass "searchString" as a param.

Categories