Apply value to a jquery generated input field - javascript

my TD's are generated by grid object on a fly
i'm trying to change value of the fist empty input that is positioned inside :
$("#get_isrc").click(function(){
$.ajax({
url: 'xtras/isrc.php',
success: function(data){
$("#new_isrc").val(data);
$("#get_isrc").val('Apply');
$("#get_isrc").addClass('apply');
}
}).error(function(){
alert('Error');
});
});
$(".apply").live("click", function(){
var s = $("td[col=ISRC] input").val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
html - static:
<h3>Generate next ISRC</h3>
<input id="new_isrc" type="text" />
<input id="get_isrc" type="button" value="Get next ISRC" />
html generated by jquery:
<tr id="4"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="1"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="2"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="3"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
tr's 1 and 2 have ISRC values from database, tr 3 is empty, but positioned last
tr 4 - is newly added empty line and i want a generated isrc applied to it...
code i provided above doesn't work. why?

You are calling .val() into an array of inputs, do this:
$("td[col=ISRC] input").each(function() {
// each iteration function
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
return false; // stops each iteration
}
});
Edit:
If you want to add the same value to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
If you want to add dynamic values to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(getNextValue());
}
});
function getNextValue() {
// your business implementation here
}

Related

How to show the variable in a input field using jquery?

I have a table and i want to update the values of the table cell on click .
I want to show an input field containing current value .
Current value is showing but when i click on input filed to edit then suddenly the input field become empty .
$('td#11').click(function(event){
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" +valuee+ "></form>");
});
An alternative other solutions:
$('td#11').click(function(event){
if($('td#11').find('form, input').length == 0) {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input id='txt11' style='color:black;' value=" +valuee+ "></form>");
}
});
You can add another snippet with above snippet to remove text-box on losing focus to it as below:
$(document).on('blur', 'input#txt11', function() {
$('td#11').html($('input#txt11').val());
});
Working demo
jsFiddle
The problem is that your click event fires again and again and so on.
To avoĆ­d this, use event.target.tagName And check if it does not match "INPUT"
$('td#11').click(function(event) {
if (event.target.tagName != "INPUT") {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>");
}
});
Working Demo below
$('td#11').click(function(event) {
if (event.target.tagName != "INPUT") {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="11">text</td>
</tr>
</table>

$().each(function() not getting proper dynamic data

I have an existing table with data coming from the database inside <input></input>. If I want to click the Add button or press Enter key, it should append a new row.
Once I enter a data in the newly added row, I compare it with my existing array or previously added data on the same table. If there's an existing data in either my array or in the same table, the <input></input> shall remain empty until I enter a data that is unique and automatically appends a new row and so on.
Currently, only the first Enter keypress is working.
Here's my HTML:
<table id="datatable-boxes" class="table table-hover table-bordered table-striped forex-datatable">
<thead>
<tr>
<th>Courier Tracking #</th>
<th>Courier</th>
<th>Vendor</th>
<th width="20%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" form="edit-boxes-form" class="form-control input-sm retrieve_track_no from_db" name="retrieve_courier_tracking_no[]" id="retrieve_courier_tracking_no_1" value="4987176601285" /></td>
<td><input type="text" form="edit-boxes-form" class="form-control input-sm from_db" name="retrieve_courier_name[]" id="retrieve_courier_name_1" value="Philpost" /></td>
<td><input type="text" form="edit-boxes-form" class="form-control input-sm from_db" name="retrieve_vendor_name[]" id="retrieve_vendor_name_1" value="Ebay" /></td>
<td class="box-action"><button class="btn btn-danger btn-xs clear-data" data-toggle="tooltip" data-toggle="modal" title="Delete Box data" data-target="#delete_box_modal_1"><span class='glyphicon glyphicon-trash' aria-hidden="true"></span></button></td>
</tr>
</tbody>
</table>
My JS:
$(function(){
// GET ID OF last row and increment it by one - Edit Boxes
var $lastRetChar = 1, $newRetRow;
$get_lastRetID = function(){
var str = $('#datatable-boxes tr:last-child td:first-child input').attr("id");
var index = str.lastIndexOf("_");
var result = str.substr(index+1);
var prev_char = $lastRetChar = parseInt(result);
var courier_name = $('#retrieve_courier_name_'+prev_char).val();
var vendor_name = $('#retrieve_vendor_name_'+prev_char).val();
$lastRetChar = $lastRetChar + 1;
$newRetRow = "<tr><td><input type='text' form='edit-boxes-form' class='form-control input-sm retrieve_track_no' name='retrieve_courier_tracking_no[]' id='retrieve_courier_tracking_no_"+$lastRetChar+"' autofocus='true'/></td><td><input form='edit-boxes-form' type='text' class='form-control input-sm' name='retrieve_courier_name[]' id='retrieve_courier_name_"+$lastRetChar+"' value='"+courier_name+"'/></td><td><input form='edit-boxes-form' type='text' class='form-control input-sm' name='retrieve_vendor_name[]' id='retrieve_vendor_name_"+$lastRetChar+"' value='"+vendor_name+"' /></td><td class='box-action'><button class='btn btn-danger btn-xs del_RetrieveBox'><span class='glyphicon glyphicon-trash' data-toggle='tooltip' title='Delete row'></span></button></td></tr>";
return $newRetRow;
}
$('#datatable-boxes').on('keypress','input[name^="retrieve_courier_tracking_no[]"]:last',function(e){
console.log(this);
$get_lastRetID();
if (e.which == 13) {
var seen = {};
$('input[name^="retrieve_courier_tracking_no[]"]').each(function() {
var ret_txt = $(this).val();
alert(ret_txt);
found = findItem(boxes_array, ret_txt);
if (seen[ret_txt] || found){
if($(this).hasClass("from_db")){
checker = true;
return true;
} else {
$('.alert-batch-box-data').css('visibility', 'visible');
if(seen[ret_txt]){
$('.alert').append('<p class="text-left">You scanned <strong>'+ret_txt+'</strong> more than once.</p>');
}
if (found) {
$('.alert').append('<p class="text-left"><strong>'+ret_txt+'</strong> already exists in Batch # <strong>'+found.batch_no+'</strong>.</p>');
}
$(this).val('');
box_qty = parseInt($('#datatable-boxes tbody>tr').length);
$('#retrieve_box_qty').val(box_qty);
checker = false;
return false;
}
} else{
if(ret_txt == ''){
alert('eto ata yun');
checker = false;
return false;
}
seen[ret_txt] = true;
if($('#retrieve_courier_tracking_no_1').val() == ''){
$('#add_RetrieveBox').css('visibility', 'hidden');
$('#update_RetrieveBox').css('visibility', 'hidden');
checker = false;
return false;
} else {
checker = true;
return true;
}
}
});
if(checker == true){
$('#datatable-boxes tbody').append($newRetRow);
$(this).closest('tr').next().find('input.retrieve_track_no').focus();
e.preventDefault();
$('#retrieve_box_qty').val($lastRetChar);
$('#add_RetrieveBox').css('visibility', 'visible');
$('#update_RetrieveBox').css('visibility', 'visible');
}
}
});
//Append new row on edit boxes > receive
$('#add_RetrieveBox').on("click", function(){
$get_lastRetID();
$('#datatable-boxes tbody').append($newRetRow);
$('#retrieve_box_qty').val($lastRetChar);
});
//Delete newly added row on frontend - Edit boxes-form
$('#datatable-boxes').on('click','tr .del_RetrieveBox',function(e){
e.preventDefault();
$(this).closest('tr').remove();
$lastRetChar = $lastRetChar-1;
$('#retrieve_box_qty').val($lastRetChar);
});
});
When I tried to alert() the current value that's being called on the second row, it just calls the first row and then returns empty twice. Since empty already showed twice, it will return false so there will be no new row.
Example:
1st data = 4987176601285 (This is from the database)
2nd data = 123 (This is in frontend)
After hitting enter to have a 3rd row, the alerts are these:
4987176601285
*blank*
*blank*
eto na yun
I'm not sure why my newly entered data is not being picked up. Any help is highly appreciated. Thanks!
I changed my each() function with filter(). I'm not entirely sure why this one worked and the other one did not.
$('#datatable-boxes input[name^="retrieve_courier_tracking_no[]"]').filter(function() {
value = $(this).val();
ret_found = findItem(boxes_array, value);
if (existing.indexOf(value) >= 0) {
// console.log($(this).val());
ret_checker = false;
if(ret_found){
$('.alert-batch-box-data').css('display', 'visible');
$('.alert').append('<p class="text-left"><strong>'+value+'</strong> already exists in Batch # <strong>'+ret_found.batch_no+'</strong>.</p>');
} else if((ret_checker == false) && (!ret_found)){
frontend_duplicate = true;
if($(this).val() == ''){
frontend_duplicate = false;
}
} else {
frontend_duplicate = false;
}
$(this).val('');
} else {
ret_checker = true;
frontend_duplicate = false
}
existing.push(value);
});
Then I modified it to fit with my previous code.

How to get value of dynamically generated textbox with same id using AJAX/PHP?

In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)

Multiple inputs with duplicate value check

I have a button to create input tags. When user click submit button I want to find inputs with duplicate values and change border to red.
I'm not using jquery validate plugin
html code:
<form>
<table>
<tr>
<td><input type="text" name="text[]" id="1"> <button class="add">add</button></td>
</tr>
</table>
<input type="submit" id="submit" value="check">
</form>
jQuery code:
// add input
var i = 2;
$('.add').click(function(e){
e.preventDefault();
$('table').append("<tr><td><input type="text" name="text[]" id="'+i+'"> <button class="add"></td></tr>");
i++;
});
$('#submit').click(function(){
// I do not know how to write ...
});
Here is what you want
$('#submit').click(function () {
var valid = true;
$.each($('input[type="text"]'), function (index1, item1) {
$.each($('input[type="text"]').not(this), function (index2, item2) {
if ($(item1).val() == $(item2).val()) {
$(item1).css("border-color", "red");
valid = false;
}
});
});
return valid;
});
If somebody is after this, with a lot of inputs, and is concerned with efficiency, this yields the same result (duplicates besides the first occurrence are marked):
$('#submit').click(function(){
var values = []; //list of different values
$('table input:text').each(
function() {
if (values.indexOf(this.value) >= 0) { //if this value is already in the list, marks
$(this).css("border-color", "red");
} else {
$(this).css("border-color", ""); //clears since last check
values.push(this.value); //insert new value in the list
}
}
);
});
fiddle:
https://jsfiddle.net/4s82L4vg/

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

Categories

Resources