Good day!
I'm doing a Dynamic table which you can add/remove row, and I'm using select2 to search Items on the database via ajax and its working well at the moment, then I want to add another button ("add new item") to my select2's input box. It was also working but when I add another row, the previous rows will have 2 (add new item) buttons on it, and when I add another row something weird is happening on my input box then.
Without adding new rows
After adding new rows
Here is my code:
$(document).ready(function() {
addRow();
});
addRow.js
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
function addRow(){
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemId"+rowArrayId+"' name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemId"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
$(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
Please Help me find solution for this one, been trying to solve this on my own but I cant get it working. Any suggestions, answers and comments would really be appreciated. Thank you very much and have a good day!
In my case I just added this function
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
}
Related
I have used Event binding on dynamically created elements? and Get changed value from <select> using jQuery to get to where I am now.
I am creating two Select dropdowns dynamically ('Activity Type' and 'Activity'). I use the selected item from the first dropdown ('Activity Type') to get a list of options for the second dropdown ('Activity'). How do I populate the second dropdown ('Activity') with the list of options please? Note that each line may have a different initial option selected and therefore a different set of options in the second dropdown.
My code is:
$(document).on('click', '#programDetailTablebody button[name="addPDRow"]', function(e) {
e.preventDefault();
var newRows = "";
newRows += "<tr><td class='button'><button type='button' name='addPDRow' class = 'buttonFront'><span class='glyphicon glyphicon-plus'></span></button></td>";
newRows += "<td class='keyvalue'><input class='timeWidth timeClass pdValue' name='timeInput' value='07:00'></input></td>"; //Time
newRows += "<td class='keyvalue'><select class='form-control activityTypeWidth activityTypeClass pdValue' name='activityTypeInput'>" //Activity Type
newRows += "<option value='' disabled selected>Select Activity Type</option>" + activityTypeOptions + "</select>"
newRows += "<td class='keyvalue'><select class='form-control activityWidth activityClass pdValue' name='activityInput'>" //Activity
newRows += "<option value='' disabled selected>Select Activity</option>" + activityOptions + "</select>"
newRows += "<td class='keyvalue'><input class='equipmentClass pdValue' name='equipmentInput'></input></td>";//Equip. Needed
newRows += "<td class='keyvalue'><input class='awardClass pdValue' name='awardInput'></input></td>";//Award
newRows += "<td class='keyvalue'><input class='leadersClass pdValue' name='leadersInput'></input></td>";//Leaders
newRows += "<td class='button'><button type='button' name='removePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-minus'></span></button></td></tr>";
$(newRows).insertAfter($(this).closest('tr'));
});
$('#programDetailTablebody').on( 'change', "select[name='activityTypeInput']", function (e) {
e.preventDefault();
var activityType = $(this).val();
$.ajax({
url : 'PPATActivityListView', ...
.done (unction(responseJson1a){
// JSON response to populate the activities options
dataType: "json";
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
this.activityOptions = activityOptionsNew;
})
});
This is the page:
I am getting the expected list of options for the second dropdown. So how do I then insert the options into the select for the second dropdown?
I have changed to use arrow function; however, I get an error "Syntax error on token ">", invalid FunctionExpressionHeader".
.done((responseJson1a) => {
// JSON response to populate the activities options
dataType: "json";
// alert(JSON.stringify(responseJson1a));
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})
You need to declare this ( current select-box) outside your ajax call and then access your select-box like below :
var selector = $(this); //declare this
$.ajax({
//..
.done (function(responseJson1a){
//other codes
selector.closest('tr').find('.activityClass').html(activityOptionsNew);//add htmls
})
You can change your jQuery ajax.done() to use arrow function, and then just replace .activityClass with activityOptionsNew
.done ((responseJson1a) => {
...
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})
I was getting values in due to for each it was repeating same values
----------------------------------------------
<script type="text/javascript">
$(document).ready(function(){
var i=0;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select name='job_id"+i+"' class='form-control'><option value=''>Select the Job</option><?php
$mysql="select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id."'";
$result1 = mysql_query($mysql) or die(mysql_error());
while($roww = mysql_fetch_array($result1)){
$sql="select * from `ca_job_type` where `jtype_id`= '".$roww['job_type']."'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$row1['jtype_id'].' selected>'.$roww['job_id'].'-'.$row1['job_type_name'].'</option>';
} ?></select></td><td><input name='sac_hsc_code"+i+"' type='text' placeholder='description' class='form-control input-md' /> </td><td><input id='i"+i+"' type='text' placeholder='SAC/HSC Code' class='form-control input-md' ></td><td><select id='employee"+i+"' name='tax_id"+i+"' class='form-control'><option value=''>Please select</option><?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?></select></td><td class='appendData'></td><td><input name='amount"+i+"' type='text' class='form-control amt' id='amount"+i+"' class='form-control input-md' style='text-align: right;' ></td><td><input name='store"+i+"' type='hidden' id='store"+i+"' class='form-control input-md' style='text-align: right;' ></td>"
);
$("#employee"+i).change(function() {
var length = i;
var tax_id = $(this).find(":selected").val();
var dataString = 'tax_id='+ tax_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getEmployee.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
var employee = [employeeData];
----------I think I was getting the error because of this forEach ---------------------------
employeeData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.tax_type+'</td>';
data+= '<td align="right">'+item.tax_Percent+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
}
}
});
});
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
Same value was repeating in all places. I attached a screenshot for reference. Please help if anybody knows. Thanks in advance
try using following way using for loop
for(var i = 0 ;i <employeeData.length;i++){
$('.appendData').append('<tr><td colspan="4"></td><td align="right">'+employeeData[i].tax_type+'</td><td align="right">'+employeeData[i].tax_Percent+'</td></tr>')
}
If you are sure that your var employeeData has the good value, you can try this maybe :
// new empty data value
var data = "";
// you add one row each time you loop
$.each(employeeData, function(item) {
data += '<tr>';
data += '<td colspan="4"> </td>';
data += '<td align="right">'+item.tax_type+'</td>';
data += '<td align="right">'+item.tax_Percent+'</td>';
data +='</tr>';
});
// when it's over, you append your data where you want.
$('.appendData').append(data);
// An other idea could be to create a "container" div and do :
$('#mycontainer').html(data);
Is it what you are looking for?
I have this appended codes here in my javascript that adds a new row every time the button is clicked to add a new employee.
Here is the code, which is working fine.
tab_workers.on('click', '.add-workers', function (e){
e.preventDefault();
var iRow = $('tbody tr:last',tab_workers).index() + 1;
var nRow = $("<tr>\n" +
"<td width='30%'><input name='worker_name_"+ iRow +"' class='form-control' placeholder='Name' /></td>\n" +
"<td width='50%'><input name='worker_address_"+ iRow +"' type='text' class='form-control' placeholder='Address'></td>\n" +
"<td width='14%'><input name='worker_phone_"+ iRow +"' type='text' maxlength='11' onkeypress='return event.charCode >= 48 && event.charCode <= 57' class='form-control' placeholder='Phone No.'></td>\n" +
"<td width='3%'><a class='btn btn-outline btn-circle btn-sm red del-workers pull-right'><i class='fa fa-remove'></i>Remove</a></td>" +
"</tr>\n");
$('tbody',tab_workers).append(nRow);
Then I have this code to sent it into the ajax post method, by wrapping it into javascript object first.
var workers = [];
$("[name^=worker_name]",tab_workers).each(function(i, wname){
//var workername = $("[name=worker_name_"+i+"]");
var workeradd = $("[name=worker_address_"+i+"]");
var workerphone = $("[name=worker_phone_"+i+"]");
workers.push({
uwiName: $(wname).val(),
uwiAddress: $(workeradd).val(),
uwiPhone: $(workerphone).val()
});
});
var workerdetails = {
umkeiWorkerInfo: workers,
};
console.log(workerdetails);
The console.log above, returns null for all the fields(name, address, phones).
Here is the ajax part,
$.ajax({
type: "post",
url: 'home/umkei/ssuForm/create/workers',
data: JSON.stringify(workerdetails),
contentType : "application/json",
success: function(d){
Metronic.unblockUI(el);
showMetronicAlert('success','check',msgSuccess);
console.log(d);
}
});
Thank you in advance.
I solved this, I use FOR loop instead of .EACH()
var workers=[];
var w = $("[name^=worker_name]",tab_workers);
var i;
for(i=1; i<=w.length;i++){
var workername = $("[name^=worker_name_"+i+"]");
var workeradd = $("[name^=worker_address_"+i+"]");
var workerphone = $("[name^=worker_phone_"+i+"]");
workers.push({
uwiName: workername.val();
uwiAddress: workeradd.val();
uwiPhone: workerphone.val();
//some other values
});
}
I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle
This is My Code. I'm preparing a offline quiz system. This code shows multiple questions with there option field. Now in radio variable, currently it stores the option of question submitted by user who's name is q1. Since the name of every question set is dynamic,how can I store multiple values in radio variable ?
Like option of q1, q2... and so on ...
<script type="text/javascript">
var currentPath = ((location+"").replace(/%20/g, " ").replace("file:///", "").replace("/", "\\").replace("index.html", ""));
var pad = currentPath+"\\quiz.mdb";
//var strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pad;
var strConn = "Provider=microsoft.ace.oledb.12.0;Data Source=" + pad;
var cn = new ActiveXObject("ADODB.Connection");
cn.Open(strConn);
var rs = new ActiveXObject("ADODB.Recordset");
var SQL = "SELECT * FROM ques_bank WHERE quizno = 'q_001'";
rs.Open(SQL, cn);
var sList = "<form target='sendinfo' id='infoform' onSubmit='return handleClick()'>";
while (!rs.EOF) {
sList = sList +
"<p>"+rs("question")+ "</p><br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='a' />"+rs("optionA")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='b' />"+rs("optionB")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='c' />"+rs("optionC")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='d' />"+rs("optionD")+"<br>"+
"<input type='radio' name='q"+ rs("ID") +"' value='e' />"+rs("optionE")+"<br>"+
"<input type='text' id='rank_list' name='q_id' value='"+ rs("ID") +"' /><br>"+
"<hr>";
rs.MoveNext();
}
document.write(sList+"<input type='submit' value='Submit'/></form>");
function test() {
}
//submit function
function handleClick() {
var radios = document.getElementsByName("q1");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1) {
alert("Please Select Radio");
}
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
rs.Close();
cn.Close();
</script>