Name of the field increment issues which is dynamically generating - javascript

I am using Codeigniter but my issue is not related to Codeigniter. I am getting some issues in my jQuery.
On page load, I am displaying the Add more button so when the user clicks on Add more then it will display the dropdown dynamically. (Note: The second dropdown will display from ajax success. So now I am displaying only text for understanding).
Below are the two dropdowns.
Now if you choose from the dropdown then it will display dynamically input field some think like this
The user can add more one the dropdown field only clicking on Add more.
check below image
Now my main issue is, I increment the name of the input field but not getting increment value. I am getting the below output
For example
First dropdown
<select name="pp_fileStatus2" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled="" selected="">Status</option>//dropdown option</select>
<input type="text" name="reasonDate2" class="form-control datetimepicker" placeholder="Date">
Second dropdown
<select name="pp_fileStatus2" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled="" selected="">Status</option>//dropdown option</select>
<input type="text" name="reasonDate2" class="form-control datetimepicker" placeholder="Date">
Notice here every time i am getting name="pp_fileStatus2" for every dropdown and name="reasonDate2" for every input field.
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
var addrm = '';
$.ajax({
type: "POST",
async: false,
url: "/access_control/getRMname",
//data: {},
dataType: 'json',
success: function(response) {
addrm += '<select name="addrm' + numberIncr + '" class="form-control multipleselect dynamicVal"><option value="" selected disabled>Select</option>';
$.each(response, function(key, data) {
addrm += '<option value="' + data.rmid + '">' + data.rmfirstname + ' ' + data.rmlastname + '</option>';
//rm_details.push(addrm);
});
addrm += '</select>';
}
});
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select><p>One more dropdown. It will come from ajax</p>' + addrm);
}
count++;
});
$(document).on('change', '.pp_fileStatus', function(event) {
if (($(this).val() == '1') || ($(this).val() == '3')) {
$(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '" class="form-control commnumber" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '" class="form-control" placeholder="Remark">');
} else {
$(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '" class="form-control" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
}
});
numberIncr++;
});
<div id="clicktoadd">Add More</div>
<div class="row">
<div class="medication_info">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

You need to increment value inside the .click callback since you are generating form name inside the .click event.
Increment numberIncr when you trigger a click. Also remove numberIncr++ at the end script.
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
var addrm = '';
$.ajax({
type: "POST",
async: false,
url: "/access_control/getRMname",
//data: {},
dataType: 'json',
success: function(response) {
addrm += '<select name="addrm' + numberIncr + '" class="form-control multipleselect dynamicVal"><option value="" selected disabled>Select</option>';
$.each(response, function(key, data) {
addrm += '<option value="' + data.rmid + '">' + data.rmfirstname + ' ' + data.rmlastname + '</option>';
//rm_details.push(addrm);
});
addrm += '</select>';
}
});
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
// CHECK: Added this to increment number on click
numberIncr++;
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select><p>One more dropdown. It will come from ajax</p>' + addrm);
}
count++;
});
$(document).on('change', '.pp_fileStatus', function(event) {
if (($(this).val() == '1') || ($(this).val() == '3')) {
$(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '" class="form-control commnumber" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '" class="form-control" placeholder="Remark">');
} else {
$(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '" class="form-control" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
}
});
// CHECK: remove the below numberIncr logic
// numberIncr++; --> remove this
});
<div id="clicktoadd">Add More</div>
<div class="row">
<div class="medication_info">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Related

How to save data values from JQuery to PHP

This is a Javascript file that creates new table row when add new button is clicked however I have no Idea on how to save data coming from the HTML file passed on the JQuery going into the database
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add-new").click(function(){
$(this).attr("disabled", "disabled");
var index = $("table tbody tr:last-child").index();
var row =
'<tr id="tables" onload="add()">' +
'<td><input type="text" class="form-control" name="studentID" id="studentID"></td>' +
'<td><input type="text" class="form-control" name="lastname" id="lastname"></td>' +
'<td><input type="text" class="form-control" name="firstname" id="firstname"></td>' +
'<td><input type="text" class="form-control" name="middleInitial" id="middleInitial"></td>' +
'<td><input type="text" class="form-control" name="course" id="course"></td>' +
'<td><input type="text" class="form-control" name="section" id="section"></td>' +
'<td><input type="text" class="form-control" name="studentNo" id="studentNo"></td>' +
'<td><input type="text" class="form-control" name="schoolYear" id="schoolYear"></td>' +
'<td><input type="text" class="form-control" name="existingViolation" id="existingViolation"></td>' +
'<td><input type="text" class="form-control" name="existingCommunityService" id="existingCommunityService"></td>' +
'<td><input type="text" class="form-control" name="existingCommunityServicetime" id="existingCommunityServiceTime"></td>' +
'<td><input type="text" class="form-control" name="remainingCommunityServicetime" id="remainingCommunityServiceTime"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table").append(row);
$("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function(){
let empty = false;
let input = $(this).parents("tr").find('input[type="text"]');
input.each(function(){
if(!$(this).val()){
$(this).addClass("error");
empty = true;
} else{
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if(!empty){
input.each(function(){
var array = [$(this).val()]
array.push
$(array.push).parent('td').html(array.push)
console.log(array)
localStorage.setItem('result', (array));
console.log(localStorage.getItem('result'))
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}});
$(document).on("click", ".edit", function(){
$(this).parents("tr").find("td:not(:last-child)").each(function(){
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function(){
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
There is a row that adds the value but never been saved into the database I know how to incorporate from HTML to PHP by using form action but JQuery is a different level for me so can you help me please? THANK YOU!

without click append 3 rows, then click 1 row per click

I want to open 3 row defult after addrow and remove row and apply remove defult 3 row using javascript
please share valuable idea sir
I have need example:-
$(document).ready(function (){
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><input type="text" required="" class="form-control input-sm title" placeholder="Medicine" name="medicine[]"></td>' +
'<td><input type="text" name="medicine_qty[]" placeholder="Potency" class="form-control input-sm"></td>' +
'<td><input type="text" name="medicine_time[]" placeholder="Description" class="form-control input-sm"></td>' +
'<td><input type="text" name="remark[]" placeholder="Add/Note" class="form-control input-sm"></td>' + '<td><button class="btn btn-sm btn-warning btn-remove-detail-row"><i class="glyphicon glyphicon-remove">Remove</i></button> </td>'+
'</tr>';
$("#table-details").append($html);
});
You can wrap the function in a for loop and edit the for loop limit according to your needs.
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var rows = $(".jdr1").length;
var limit = 1;
// In the first click append 3 rows, then 1 row per click
if (rows < 3) limit = 3;
for (let i=0; i<limit; i++) {
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><input type="text" required="" class="form-control input-sm title" placeholder="Medicine" name="medicine[]"></td>' +
'<td><input type="text" name="medicine_qty[]" placeholder="Potency" class="form-control input-sm"></td>' +
'<td><input type="text" name="medicine_time[]" placeholder="Description" class="form-control input-sm"></td>' +
'<td><input type="text" name="remark[]" placeholder="Add/Note" class="form-control input-sm"></td>' + '<td><button class="btn btn-sm btn-warning btn-remove-detail-row"><i class="glyphicon glyphicon-remove">Remove</i></button> </td>'+
'</tr>';
$("#table-details").append($html);
}
})
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<table id="table-details"></table>
<button class="btn-add-more">Add Rows</button>
</html>

Using Jquery to add a Checkbox vaue to a Field

Hello I am trying to add a result of a checkbox into my array to add to a database when submitted.
Another user kindly changed my original code but I can't work out how to add the result of my checkbox to my array.
It now shows on the screen properly but I cant get it to copy to a field to be able to save the field to my database so that when I open the page again it will then load from the database and show if it is overtime on my hours recorded.
I want to save a Value of checked = Y and when not checked = N to the array I think I might need to copy the value to a hidden field but I can't get it to work.
<!-- this next section is to dynamically add the parts fields to the jobsheet page so more parts can be added on the page without it starting out too large. -->
<!-- this ext section is the Adding Hours on the jobsheet -->
var rownumhours = 0;
function addhours(obj, e) {
rownumhours++;
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[' + rownumhours + ']" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[' + rownumhours + ']" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> Overtime: <input type="checkbox" name="add_overtime_hours[' + rownumhours + ']" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' + Overtime: <input type="checkbox" name="add_overtime_hours[' + rownumhours + ']" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '1') +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
</script>
Hello I finally finished the solution to my problem.
I have split the jobs out by showing the Checkbox and then also having a hidden text box of the same name that contains a value of either 1 or 0 and then this is the value i put into the Mysql Database.
var rownumhours = 0;
function addhours(obj, e) {
var hoursrow = '<p id="rownumhours' + rownumhours + '">Start Time: <input type="time" name="add_start[]" size="4" value="' +
$(obj).closest('span.headings').find('[name="add_start"]').val() + '"> Finish Time: <input type="time" name="add_finish[]" value="' +
$(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[]" value="' +
$(obj).closest('span.headings').find('[name="add_date"]').val() + '"> <input type="hidden" name="show_overtime_hours[]" size="1" value="' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[]" size="1" value="' +
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
(($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
' "> <input type="button" value="Remove" onclick="removeRow(' +
rownumhours + ');"></p>';
jQuery('#hoursrow').append(hoursrow);
rownumhours++;
$(obj).closest('span.headings').find('[name="add_start"]').val("");
$(obj).closest('span.headings').find('[name="add_finish"]').val("");
$(obj).closest('span.headings').find('[name="add_date"]').val("");
$(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
$(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
}
function removeRow(rnum) {
jQuery('#rownumhours' + rnum).remove();
}
</script>

Phone Number Input - Focus on Next Input when Current is Full

I am looking to make a set of 3 form inputs for a phone number that automatically focuses on the next set of digits when the first is full.
My form is this string of HTML:
myLayer.eachLayer(function(layer) {
// here you call `bindPopup` with a string of HTML you create - the feature
// properties declared above are available under `layer.feature.properties`
var content = '<div class="tooltip-header">Store Name<\/div>' +
'<div class="tooltip-address">' + layer.feature.properties.address1 + '<div\/>' +
'<div class="tooltip-address">' + layer.feature.properties.address2 + '<div\/>' +
'<br>'+
'<div class="tooltip-phoneLabel">' + layer.feature.properties.phoneLabel + '<div\/>'+
'<br>'+
'<div class="phone-input">'+
'<input class="phone-input" name="phone-input" type="tel" size="3" maxlength="3" placeholder="555"> '+
'<input class="phone-input" name="phone-input" type="tel" size="3" maxlength="3" placeholder="555"> '+
'<input class="phone-input" name="phone-input" type="tel" size="4" maxlength="4" placeholder="5555">'+
'<\/div>';
layer.bindPopup(content);
});
Use the following example to achieve what you want:
$(document).ready(function(){
$('body').on('keyup', 'input.phone-input', function(){
if($(this).val().length === this.size){
var inputs = $('input.phone-input');
inputs.eq(inputs.index(this) + 1).focus();
}
});
});
DEMO

How do I create a search against JSON data with input and radio buttons?

So far I am able to display the data in an HTML page. However I am stuck when it comes to searching against the Description field and also filtering this data according to Location radio buttons selected.
HTML:
<form>
<input id="searchterm" type="search" name="query" placeholder="Search">
<input type="radio" name="location" value="houston">
<label for="houston">Houston</label>
<input type="radio" name="location" value="austin">
<label for="austin">Austin</label>
<input type="button" name="searchbutton" value="search" onclick=search();>
</form>
JSON data:
[
{
Description: A bunch of text from which I need to search against
Location: This will be selected by a radio button
}
]
Here is what I have tried:
JS CODE:
function search() {
var $searchField = $('#searchterm');
var query = $searchField.val();
$.getJSON("API LINK HERE", function(data) {
var output="<ul>";
$.each( data, function (i, item) {
output+="<li class='results'><div class='title'><div class='mainCat'>" + data[i].MainCategoryName + "</div>";
output+="<div class='AdID'>" + data[i].AdID + "</div></div>";
if(data[i].PhotoUrl !== null){
output+="<img class='image' src=" + " ' " + data[i].PhotoUrl + " ' " + "></img>";
}
output+="<div class='description'>" + data[i].Description + "</div>";
output+="<button type='submit' class='goToAd' formaction=" + data[i].AdUrl + ">Go To Ad </button> </li>" ;
});
output+="</ul>";
$("#content").html(output);
});
}

Categories

Resources