I was populating my tabular data from server through ajax using json. I want to create my HTML table row dynamically using jquery and every row must contain html elements like input type='text' and select dropdowns. I was able to create textboxes in columns, but I was not able create select dropdowns in columns. Here is my js code:
function loadFunction(){
$.ajax({
type : "GET",
url : "s3.do",
data : "",
success : function(data){
alert("success");
for(var i=0;i<data.length;i++){
var ispSelect = $("<select></select>");
var idProofSelect = $("<select></select>");
var dataArr = data[i];
var id = dataArr.id;
var name = dataArr.name;
var address = dataArr.address;
var isp = dataArr.lsIsp;
var idproof = dataArr.lsIdProof;
$.each(isp,function(index,product){
$("<option>").val(product.id).text(product.name).appendTo(ispSelect);
});
$.each(idproof,function(index,product){
$("<option>").val(product.id).text(product.name).appendTo(idProofSelect);
});
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td>"+ispSelect+"</td>"
+"<td>"+idProofSelect+"</td>"
+"</tr>");
}
},
error : function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
}
the above code created below HTML table structure where under ISP and ID-Proof columns I am getting [Object Object], whereas I expected it to create <select> options for me. How can I resolve this issue. I am not that fluent with Jquery concepts. Is it the right way of what I am trying to do.
You add jQuery object to string - this wrong. Try:
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td>"+ispSelect[0].outerHTML+"</td>"
+"<td>"+idProofSelect[0].outerHTML+"</td>"
+"</tr>");
}
When you do "some string" + Object - Object is being converted to String, that's why you get [object Object]
You need to add ids to each <td>, and then append the select boxes:
$("#tab tr:last").after("<tr><td><input type='checkbox' value='"+id+"'/></td><td><input type='text' value='"+name+"'/></td>"
+"<td><input type='text' value='"+address+"' /></td>"
+"<td id='ispSelect_'" + i + "></td>"
+"<td id='idProofSelect_'" + i + "></td>"
+"</tr>");
$("#ispSelect_" + i).append(ispSelect);
$("#idProofSelect_" + i).append(idProofSelect);
Related
I was using select2 plugin on my input box to search items from the database using AJAX based on what the user type on it. It was working fine, I can search Items on it and select it when its available, but my problem is whenever I add new rows on my table the previous item fields "text" will be gone, I'm making a table where you can add/remove rows dynamically so here is my HTML:
<td><input name='product[0][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' /></td>
and my javascript:
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 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>");
rowArrayId = rowArrayId + 1;
};
$(".itemSearch").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};
}
}
});
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);
};
here are some screenshots:
1st state:
2nd state: when searching item on the input box
3rd state: after adding new row on my table
What can be the issue?
The same id value is used for the input elements as rows get added.
It is best to have unique id within the page.
I would guess that every time you call .select2(), that all the selects get reset to the original state. You could only call the constructor on the new box by limiting the scope.
To update only the new select2s you should change the following.
See this example (untested, please adjust):
var newHtml = $("<h1>Code to be appended here</h1>");
newHtml.appendTo('#tblItemList tbody');
$('.itemSearch', newHtml).select2(/* ... */)
As an alternative you could try "freezing" the state by applying the "selected" attribute to all boxes before you call the constructor.
See this example (untested, please adjust)
$('.itemSearch').each(function(){
var val = $(this).val();
$(this).find('option[value='+val+']').attr('selected', 'selected');
})
I am trying to create a HTML table like the following dynamically using jQuery:
<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>
This is my actual table :
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
This is the method which will create tr and td elements taking id and labelText:
function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);
// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}
I also have a value which will be shown as tool tip.
Please help me to create a table dynamically with tool tip and tr td.
EDIT:
I have almost done with the following code:
function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
Here label is coming properly and the input box is not coming and it shows [object Object] where the text box has to come...
When I printed the textInputBox using console.log, I get the following:
[input#nickname, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
What could be the issue?
Thanks to #theghostofc who showed me path... :)
You may use two options:
createElement
InnerHTML
Create Element is the fastest way (check here.):
$(document.createElement('table'));
InnerHTML is another popular approach:
$("#foo").append("<div>hello world</div>"); // Check similar for table too.
Check a real example on How to create a new table with rows using jQuery and wrap it inside div.
There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.
Edit:
Check Dynamic creation of table with DOM
Edit 2:
IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:
function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
Here is a full example of what you are looking for:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
});
</script>
</head>
<body>
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.
It's much easier to construct just the html and change the id s of the label and input according to your needs.
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}
I have a web page that is a dynamic form. It allows users to specify any number of Attributes to devices. These attributes can be select option lists. When the user selects this, they are presented with a button to add options.
My problem is that I need to know how many options there are for each attribute. I have tried using var counter=$('.class-name').next().val(); to try and count them alert(counter); to see if it works. But all I get is an alert of undefined so the var counter is not being initalised.
I need to know the number of options for each select list to be able to group them together and know which options go with a particular attribute. I cannot think of a way to do this through JS or PHP. I can get the options posted in the php but I can't identify what options go with each attribute.
Here is a fiddle!
Here is the code to get the lengths for each of the respective options.
$('.tattribute option:selected[value="text"]').length
$('.tattribute option:selected[value="checkbox"]').length
$('.tattribute option:selected[value="select-list"]').length
$('.tattribute option:selected[value="notes"]').length
Fiddle
Here is a fiddle with a hidden field added to keep track of the options count. Every time an option is added or removed the value of the hidden field is incremented or decremented. The changes are in the code below
var template="<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attributeName[]"+"\">Name:</label>"
+ "<input class=\"attribute\" type=\"text\" name=\"attributeName[]"+"\">"
+ "<input class=\"attribute_count\" type=\"hidden\" name=\"attributeCount[]"+"\">"
+ "<label for=\"attributeType[]"+"\">Type:</label>"
+ "<select class=\"tattribute\" name=\"attributeType[]"+"\">"
+ "<option value=\"text\" selected>Text</option>"
+ "<option value=\"checkbox\">Checkbox</option>"
+ "<option value=\"select-list\">Select Option List</option>"
+ "<option value=\"notes\">Notes</option>"
+ "</select>"
+ "<div class=\"option\"></div>"
+ "<button type=\"button\" class=\"remove\">Delete</button>"
+ "</div>";
And
//Add action
$("#attributes").on('click', '.btn', function () {
add = "<div class=\"op\"><label for=\"attributeOption[]" +"\">Name:</label>"
+ "<input class=\"option-input\" type=\"text\" name=\"attributeOption[]" + "\">"
+"<button type=\"button\" class=\"remove-option\">remove</button></div>";
$(this).after(add);
//COUNT NUMBER OF OPTIONS
$opt = $(this).closest('.option')
$opt.siblings('.attribute_count').val($opt.find('.op').length)
alert($opt.siblings('.attribute_count').val());
});
//Remove input
$("#attributes").on('click', '.remove-option', function () {
$(this).closest('.op').remove();
$opt = $(this).closest('.option')
$opt.siblings('attribute_count').val($opt.find('.op').length)
});
i am trying to create chkbox on click with different name and value and then alerting its value resulting in error "NaN" my script is here,
<script type="text/javascript">
var k=0,j=0;
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
k+=1;
var newRow1="<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+DDL_fromProfession +" to "+DDL_ToProfession +"</td></tr>"
+"<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>I currently work here</input>";
alert(k);
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
alert(chkvalue);
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
var input = "<input name='parameters' id='field' type='text' />";
var input1="<input name='parametersCompany' id='field' type='text'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " +input1 +"</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
</script>
i wanna crete chkbox like,
name = chkbx_CurrPro0 , value = 0
name = chkbx_CurrPro1 , value = 1
name = chkbx_CurrPro2 , value = 2
.
.
.
then i am printing its value resulting in NaN error ?? Hopes for your suggestion
one more thing i wanna do after creating dynamicaally chkbox it will get value of only marked chk box ,
my code here,
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
but check all chkbox created at run time
Hopes for Suggestions
Thanks
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
I think you have some issues with the quotes here. Try this...
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro"+k+"']").val()) + 1;
EDIT: Looks like youhave the same issue here...
"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>
This will try to make the name chkbx_CurrPro'1' but that is not valid. This should instead be...
"<input type='checkbox' name='chkbx_CurrPro"+k+"' value='"+k+"'>
Edited Again :
I see another issue here, you are trying to get the value of the checkbox before the checkbox has actually been added to the dom. You have added it to the string, but that is just a string of text when you call parseInt, not a part of the page. Move the parseInt line to below your append lines, near the bottom.
Hi this was actually orginally in another question (HERE) that had two parts. The first part was solved by #epascarello - thanks again, now just this part remaining, and i don't seem to get it.
I'm creating a duplicate-able div's containing checkboxes, on submit it only returns one value for the original input in the console, but no value for any duplicates.
Any help greatly appreciated.
JS Fiddle: http://jsfiddle.net/dawidvdh/EEd7c/
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var relation_fields=[0];
var relation_input ="<label>Spouse</label>"+
"<input type='checkbox' value='spouse' class='relationship' name='relationship' />" +
"<label>own child</label>"+
"<input type='checkbox' value='ownchild' class='relationship' name='relationship' />" +
"<label>adopted</label>"+
"<input type='checkbox' value='adopted' class='relationship' name='relationship' />" +
"<label>stepchild</label>"+
"<input type='checkbox' value='stepchild' class='relationship' name='relationship' />" +
"<label>parent</label>"+
"<input type='checkbox' value='parent' class='relationship' name='relationship' />" +
"<label>inlaw</label>"+
"<input type='checkbox' value='inlaw' class='relationship' name='relationship' />" +
"<label>brother</label>"+
"<input type='checkbox' value='brother' class='relationship' name='relationship' />" +
"<label>other</label>"+
"<input type='checkbox' value='other' class='relationship' name='relationship' />";
//Generate variables
jQuery(document).ready(function(e) {
//populate jquery generated fields
jQuery(relation_fields).each(function() {
jQuery(relation_input).appendTo('#relation-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var relation_newDiv = 'relation-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
$clonedDiv.find('input:checkbox').removeAttr('checked');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
relation_input_groups.push(relation_newDiv);
}
//Cloning Function
//Validation
//submit function
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['relationship'] = $(v).find('.relationship:checked').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
});
and the HTML:
<div id="dependant-1" class="dependant">
<div id="label">relationship:</div> <div id="relation-group-1"></div>
</div>
<button id="clone">clone</button>
<button id="submit">submit</button>
See this updated fiddle : http://jsfiddle.net/EEd7c/7/
Comment this line : $clonedDiv.find('input').val('');
Also set dep_counter = 0; on submit button click..
Your cloned check boxes do not have any values assigned to it. Ensure that when its cloned the values are set in the net set of checkboxes
It is simply because those checkboxes have the same name attribute. When the submit button is pressed, it serializes the values of all the form controls (text boxes, radio boxes, check boxes, etc) and send them. The name property should be unique for all those controls.
In your code, all those checkboxes have the same name property (relationship) which makes them indistinguishable. A fix to this problem is to give different names to those check boxes.