How to check ajax data.d is null in append? - javascript

I am trying to append some data in html table using jquery that is working fine but when the data is null or empty i have to append another div to that html table.
Am trying like this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
but it is not working please help me how to fix this...

Never understand why somebody use this
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
Instead of this:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
Using this approach you can incapsulate table cell building inside of your class and make your code much more readable and reusable. Also, as I see now, you are trying to append td inside of something with id #table, and look like it is incorrect, because you should append td inside of tr.
Also, using this you can get references to all objects such as inputs and avoid of $('input, select, textarea') selectors.

You could use something like this,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);

You could use :
if( data.d ){
//Your code
}
That will check if data.d is NULL or empty string "".
If you want to check in every iteration use the index i :
if( data.d[i] ){
//Your code
}
Hope this helps.
Take a look to https://stackoverflow.com/a/5515349/4281779.

Related

How to get the value from dynamically created checkbox using Jquery with class

I am trying to get the value from checkbox when checked which is created dynamically with jquery associated with html table am using class to get the value but am unable to get it
My code is like this
Input created with Jquery
"<td><div class=" + "checkbox checkbox-primary" + "><input type=" + "checkbox" + " class=" + "cbCheck" + " value=" + "" + data.d[i].Rowname + "" + "" + data.d[i].one + "" + "></div></td>"
Jquery to get the value
$("#table").on(":checked", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Please help me how to fix this.
Thanks in advance
Working Fiddle
Try:
$('table tr td').on('click','.cbCheck',function() {
if ($(this).is(':checked')) {
alert($(this).attr('id'))
}
else
alert('unchecked');
});
Use 'change' event:
$("#table").on("change", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Instead of creating it like that
use Create element and add id dynamically then use your function I guess it will work, actually worked in my case
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'ptworkinfo';
You can do using following for dynamically created elements:
$(document).on("click", ".cbCheck", function () {
var value=$(this).attr("value");
alert(value);
});

How to style dynamically generated Select2 dropdowns after the page has loaded?

I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.

How do I create HTML table using jQuery dynamically?

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

inline if else statements in jQuery

I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;

Dynamically Creating ChkBox on click with Different name and Value Giving "NaN" using Jquery?

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.

Categories

Resources