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.
Related
<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
I don't really know how to word this question so I am sorry if this seems a bit ambiguous. I have a situation where I am generating a bunch of check boxes within a cfloop. Each checkbox has the same class name of check, but they represent a value within a database. Originally I was hoping that I can just check to see if the checked property exists using jQuery, but that doesn't work as I'd hoped. The issue it brings is that if there is one checkbox that is checked and if I check or uncheck a different checkbox the class still returns a true value which makes sense logically.
Here is the ColdFusion which sets the checked value and the loop which generates the html:
<cfloop>
<cfif ContainsSic.HasSiC EQ 1 >
<cfset CheckedResult = "checked=""checked""" >
<cfelse>
<cfset CheckedResult = "" >
</cfif>
<cfoutput>
<tr>
<td align="center">#Passed_CustomerName#</td>
<td align="center">#Passed_LotNumber#</td>
<td align="center">#Passed_SubLot#</td>
<td align="center">#Passed_CarbonAvg#</td>
<td align="center"><input type="button" onclick="location.href='';" value="Amend" /></td>
<td align="center"><input type="checkbox" onclick="ajax(#Passed_CustomerID#, #Passed_LotNumber#, #Passed_SubLot#)" #CheckedResult#/></td>
<td align="center">Red Tag Page</td>
</tr>
</cfoutput>
</cfloop>
And here is the jQuery which handles the ajax call and the checked value:
function ajax(CustomerID, LotNumber, SubLot) {
if ($("input:checkbox").is(":checked")) {
var Checked = true;
}
else {
var Checked = false;
}
var passed_data = {
method: 'UpdateHasSiC',
CustomerID : CustomerID,
LotNumber: LotNumber,
SubLot: SubLot,
Checked: Checked
}
console.log(passed_data);
$.ajax({
type: 'POST',
url: 'LecoXMLRead_Ajax.cfc',
data: passed_data,
dataType: 'JSON',
success: function(data) {
},
error: function(e){
}
})
}
The workflow behind this is when the page loads, it grabs values from a database which determines whether or not the checkbox should be selected. It writes the values given from the database into rows with its designated checked or unchecked checkbox. The user should then be able to alter the checkbox and when doing so, update the value within the database with a 1 or 0. 1 representing it was checked of course.
I hope this makes sense, I can provide clarification or whatever else is needed.
Thank you
You can add custom data attribute at checkbox and then used that attribute value to pick checkbox
<input type="checkbox" data-customerId="#Passed_CustomerID#" onclick="ajax(#Passed_CustomerID#, #Passed_LotNumber#, #Passed_SubLot#)" #CheckedResult#/>
In function you can use that customer id to identify that specific checkbox.
I am considering customer id as unique value.
function ajax(CustomerID, LotNumber, SubLot) {
if ( $('[data-customerId="'+CustomerID+'"]:checkbox').is(":checked")) {
var Checked = true;
}
else {
var Checked = false;
}
}
Get rid of the onclick action, and change your markup/js to:
HTML:
<input type="checkbox" data-customerid="#Passed_CustomerID#" data-lotnumber="#Passed_LotNumber#" data-sublot="#Passed_SubLot#" #CheckedResult# />
JS:
<script>
$(document).ready(function () {
$('input[type="checkbox"][data-customerid]').on('click', function(e) {
ajax($(this).data('customerid'), $(this).data('lotnumber'), $(this).data('sublot'), $(this).is(':checked'));
});
});
</script>
Then you would add the checked argument to your ajax function.
(I didn't test this, so look for syntax errors. LMK and I'll correct if found.)
I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481
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);
});
How can I perform the following action using jquery?
I have a table with three rows and a header row. something like this:
When a user enters Data in "StudentId" field, "StudentFirstName" and "StudentLastName" are populated from database using jquery-Ajax. What I want to achieve is, Once a studentId is entered in first row textbox, I want to clone the first row and append it as second row and then clear the data from first row.
Hers is my Table structure:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%# Import Namespace="MyModel.Model" %>
<div>
<table id="MyTableHeaders">
<tr>
<th>
StudentId
</th>
<th>
StudentFirstName
</th>
<th>
StudentLastName
</th>
</tr>
</table>
</div>
<div>
<table id="MyTableData">
<tr>
<td>
<input name="StudentId"/>
</td>
<td>
<input name="StudentFirstName"/>
</td>
<td>
<input name="StudentLastName"/>
</td>
</tr>
</table>
</div>
Here is my jquery:
$('input[name="StudentId"]').focusout(function (e) {
e.preventDefault();
var link = '/Student/DisplayStudentDetails';
$.ajax({
type: 'POST',
url: link,
data: { id: $('input[name="StudentId"]').val() },
dataType: 'json',
success: function (result) {
$('input[name="StudentFirstName"]').val(result.FirstName);
$('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData tr:first").clone().appendTo("#MyTableData");
$("#MyTableData tr:first").find("input").attr("value", "").blur();
},
error: function (result) {
alert("Failed")
}
});
});
I am struggling with clearing data from first row and keeping data in the cloned row. With my code it clears all the rows.
Also, I noticed that cloned rows have the same field names, hence it will update all cloned "StudentFirstName" and "StudentLastName" fields with the studentId entered in first row. How should I approach this?
Any help would be appreciated.
success: function (result) {
var clone = $("#MyTableData tr:first").clone();
clone.find('input[name="StudentId"]').val(result.FirstName);
clone.find('input[name="StudentFirstName"]').val(result.FirstName);
clone.find('input[name="StudentLastName"]').val(result.LastName);
$("#MyTableData ").append(clone);
},
-edit-
although, when i've attempted tasks such as this in the past, i've created template rows.
a row that already exists but has display:none. that way if your table has no values you can always know the template row exists.
-edit-
if you want to add the new row at the begining, you can just use prepend instead of append.
or the second row would be $("#MyTableData tr").first().after(clone)