access a specific input in an input array - javascript

<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

Related

Send hidden input data using AJAX

I am using AJAX live search plugin.
It passes input data to backend-search.php
backend-search.php selects data from the database and return to the search page.
Now I want to pass one hidden input value with the search query.
Hidden Input
<input type="hidden" name="group" value="<?php echo $grp_id; ?>" />
Following is my html in search.php
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search..." />
<div class="result"></div>
Javascript
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
How do I send the data of the hidden input field with above js?
You could use $.post instead of $.get like this:
$.post( "backend-search.php?query="+ term, { hidden_key: "hidden_value"})
.done(function(data) {
alert( "Data Loaded: " + data );
});
So, customizing it for your code,
if(term.length) {
// get value of hidden field
var hidden_value = $('[name="group"]').value();
// make a post request, but also pass query params
$.post("backend-search.php?query=" + term, { group: hidden_value})
.done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
Here, everything after the ? mark is passed as a query string (i.e. via get method) whereas the hidden field is passed by the Post method.
In your Php script, use print_r($_REQUEST) to verify that you get the 2 parameters as desired.
Also, you should encode URI parameters like this encodeURIComponent(term) to make sure your javascript does not break if the user enters special characters

Newbie to Javascript: how to avoid sending data that have not changed?

I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

Take input from html field and store it in JSON object (lots of input fields)

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

Setting value of item in jquery

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);
});

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.

Categories