Dynamically added checkbox value doesn't work - javascript

I am sending a post request to my database and according to the response, I am dynamically creating new checkboxes in my JSP page. Like this (here getMediums function is a onclick event handler of another component in my JSP page):
function getMediums(str)
{
currentClass = str; // save the current class
<%
String classStart = "<script>document.writeln(str)</script>";
HashMap<String, ArrayList<String> > medSubjects;
if(!tutoringInfoAcademic.containsKey(classStart)){ // first click
medSubjects = new HashMap<>();
tutoringInfoAcademic.put(classStart,medSubjects); // opening a blank map
}
else{ // already selected some medium of this class
medSubjects = tutoringInfoAcademic.get(classStart);
}
%>
// javascript code
var data = {};
data["classStart"] = str;
$.post('PopulateMedium',data,function(responseJson){
if(responseJson!=null){
var td = document.getElementById("mediums");
$(td).empty(); // deletes previous contents
$.each(responseJson,function(key,value){
var temp = value;
console.log(temp); // prints as per expected
var checked = "";
<%
String t = "<script>document.writeln(temp)</script>";
if(medSubjects.containsKey(t)){
// already selected, so check this checkbox
%>
checked = "checked";
<%
}
%>
td.innerHTML += " <input type='checkbox' onclick='medCheckboxOnClick()' name='mediumCheckbox' value=" + temp + " " +checked + "/>";
if(value == 'bm')td.innerHTML += "Bangla medium"
else if(value == 'em')td.innerHTML += "English medium";
else if(value == 'ev')td.innerHTML += "English version";
td.innerHTML += "<br/>";
})
}
});
}
The checkboxes get created as per expected. The onclick function:
function medCheckboxOnClick(){
var t = $(this).attr("value"); // bm, em, ev
console.log("entered into the checkbox onclick function");
if($(this).is(":checked")) {
console.log("checkbox for class "+currentClass+" and medium "+t+" has been checked");
<%
String id = "<script>document.writeln(t)</script>";
String currentClassStart = "<script>document.writeln(currentClass)</script>";
if(tutoringInfoAcademic.containsKey(currentClassStart)){ // redundant check
ArrayList<String> listOfSubjects = tutoringInfoAcademic.get(currentClassStart).get(id);
if(listOfSubjects == null){ // first clicked
listOfSubjects = new ArrayList<>();
tutoringInfoAcademic.get(currentClassStart).put(id,listOfSubjects);
System.out.println(tutoringInfoAcademic.get(currentClassStart));
}
else{ // list of subjects already created. either some subject has been chosen or not
}
}
%>
}
else{
console.log("checkbox for class "+currentClass+" and medium "+t+" has been unchecked");
<%
String ID = "<script>document.writeln(t)</script>";
String curClassStart = "<script>document.writeln(currentClass)</script>";
if(tutoringInfoAcademic.containsKey(currentClassStart)){ // redundant check
tutoringInfoAcademic.get(currentClassStart).remove(ID);
}
%>
}
}
When I click on one of the dynamically created checkboxes, execution enters the the medCheckboxOnClick() function and something like this comes out:
checkbox for class 1 and medium undefined has been unchecked
t remains undefined, though I set the value of the checkbox in the previous function while creating the checkboxes. Moreover, it always consides UNCHECK, no matter whether I have checked or unchecked the checkbox. Here currentClass is a global javascript variable and tutoringInfoAcademic has been set as the session attribute from my controller class. It has been declared like this:
HashMap<String, HashMap<String, ArrayList<String> > > tutoringInfoAcademic = new HashMap<>();
Why does the value of the checkbox remain undefined? And why do I always get the uncheck event caught by the click event handler?

Found the solution by writing
td.innerHTML += " <input type='checkbox' onchange='medCheckboxOnClick(this)' name='mediumCheckbox' value='" + temp + "' " +checked + "/>";
And then the function will have a parameter, which is the checkbox.
function medCheckboxOnClick(cb){
//$('.med').click(function() {
//var t = $(this).attr("value"); // bm, em, ev
var t = $(cb).attr("value");
console.log("entered into the checkbox onclick function");
if($(cb).is(":checked")) {
//
}
else{
//
}

Related

Get a list of checked checkboxes that also has a specific data-attribute value

I have a table of data containing a checkbox that the user can select to either export the record or edit the record. For editing the checkbox has a data attribute that shows whether the specific set of data is editable (based on user-permissions).
I am trying to get a list of the checkbox values where the checkbox is checked AND the data attribute has a value "True".
In my view model I have the field:
public bool ShortageIsEditable {get;set;}
This is set in the view model mapper to either true or false depending on the status of the record and the permissions of the user.
In my view I have a table that has the following checkbox with data attribute for each record:
#(Html.Kendo().Grid(item.Shortages)
.Name(string.Format("ShortagesGrid_{0}", item.Id))
.Columns(columns =>
{
columns.Template(GetViewLink)
.Title("View")
.Width(38);
columns.Template(o => "<input type=\"checkbox\" name=\"selectedRequestId\" " + (o.IsSelected ? "checked=\"checked\"" : "") + "class=\"myCssCheckAllCheckBox\" value=\"" + o.ShortageNo + "\" data-iseditable=\"" + o.ShortageIsEditable + "\"/>")
.Width(30);
columns.Bound(o => o.ShortageNo)
.Title("Shortage #")
.Width(120);
...
When the user selected some records for edit (checked the checkboxes) and presses the Edit button, the following javascript/JQuery function is executed:
function submitGridSelectedItemsForEdit() {
$('#gridExportForm').attr('action', '/Requests/Shortage/MultiEditShortages');
$('#gridExportForm').attr('method', 'GET');
var chkdlist = $('input[name="selectedRequestId"]:checked');
var newlist = chkdlist.filter(function (el) {
return el.data("iseditable") === "True";
});
newlist.submit();
This will always crash on the line "return el.data("iseditable") === "True";".
I have also tried using the following, but this crashes on submitting the newlist array:
function submitGridSelectedItemsForEdit() {
$('#gridExportForm').attr('action', '/Requests/Shortage/MultiEditShortages');
$('#gridExportForm').attr('method', 'GET');
var chkdlist = $('input[name="selectedRequestId"]:checked');
var newlist = [];
for (var chk in chkdlist)
{
if (chk.data("isEditable") == true) {
newlist.push(chk);
}
}
if (newlist.length == 0) {
alert("Please select at least 1 request to Edit.");
}
else {
newlist.submit();
}
}
What is the easiest way to get the list of objects that is both checked and has a data-attribute value of "True"?
el in filter() callback is the dom element, not a jQuery object. LAso it is not the first argument of the callback it is the second.
So to use jQuery methods you need to wrap el in $()
var newlist = chkdlist.filter(function (_,el) {
return $(el).data("iseditable") === "True";
});
Or filter based on the attribute value as selector
var newlist = chkdlist.filter('[data-iseditable="True"]')

Dynamically generated html, document.getElementByID returns null

I am generating an html table dynamically in my code behind file
protected void PopulateMemberTable()
{
var guid = "";
string[] selectedColumns = new[] { "MEMBID", "MEMBER_NAME", "BIRTH", "IPA", "HPNAME" };
if (Session["guid"] != null)
guid = Session["guid"].ToString();
StringBuilder html = new StringBuilder();
DataTable dt = MemberSearch(guid, membFirst.Text.ToString(), membLast.Text.ToString(), membDob.Text.ToString(), membId.Text.ToString());
if (dt != null)
{
DataTable new_dt = new DataView(dt).ToTable(false, selectedColumns);
html.Append("<table class='table table-hover data-table'>");
html.Append("<thead>");
html.Append("<tr>");
foreach (DataColumn column in new_dt.Columns)
{
html.Append("<th>");
switch(column.ColumnName.ToString())
{
case "MEMBID":
html.Append("Member ID");
break;
case "MEMBER_NAME":
html.Append("Member Name");
break;
case "BIRTH":
html.Append("DOB");
break;
case "IPA":
html.Append("IPA");
break;
case "HPNAME":
html.Append("Health Plan");
break;
}
html.Append("</th>");
}
//btn column (no header)
html.Append("<th></th>");
html.Append("</tr>");
html.Append("</thead>");
html.Append("<tbody>");
var counter = 0;
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
}
else
html.Append("<div class='alert alert-danger' role='alert'>No Members Found</div>");
membTable.Controls.Add(new Literal { Text = html.ToString() });
}
The table is generated just fine, but now I am trying to call some server side code when a row is clicked
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
I attempted to accomplish this task by placing a hidden <asp:Button/> in each row and then adding a corresponding onclick attribute to each <tr> tag
This is how the generated html looks like in the dev console
However when I attempt to click the row I get the following error message
I am having a hard time understanding what exactly I'm doing wrong. I'd appreciate some input, or possibly even an alternative approach.
You can use jquery and use the delegation model to handle click on dynamic elements. if for example you have some html like
<div id="dynamicname'></div>
then use
the jquery code snippet
$(document).on('click','#dynamicname',function(){
//handle your event here
});
dynamic html should always be handled by delegation model. And you can use
var dynamic_name="#"+getYourDynamicRowName;//variable for dynamic id's of dynamic html element
$(document).on('click',dynamic_name,function(){
//handle your event here
});
As per my experience we can not use asp tag while you are creating dynamic HTML.
If you see your code of dev console you can see that controls are not rendered properly..rendered with asp tag..
To achieve it you can use javascript/Jquery to call server side function.
<input type="button" ID="btn" runat="server" onclick="fn();" />
And in your javascript:
fn = function(){
__doPostBack("<%=btn.ClientID%>", "");
}
And in your code:
`
protected override void btnEvent(IPostBackEventHandler source, string eventArgument)
{
//call the button event
//base.btnEvent(source, eventArgument);
if (source == btn)
{
//do some logic
}
}
After figuring out that passing an <asp:button/> as a string wasn't going to work, I took an alternative approach.
In populateMemberTable()I added an href attribute to the first column in each row
var href = true;
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
if (href)
{
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");
html.Append(row[column.ColumnName]);
html.Append("</a></td>");
}
else
{
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
}
And then I saved the membId as a session variable in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
//save guid (http://url.com?guid=xxxxxx) as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
{
Session["membid"] = membId;
}
}
It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!

link a checkbox to an object in Javascript

Suppose I have a table which is populated by filling out a form on a page and clicking the submit button.
The last column of the table is a Completed section with a checkbox on each row. On clicking on the checkbox I want to change the .completed property from false to true on that object.
How can I distinguish which checkbox was clicked and change the property from that row?
this.addRowToTable = function() {
return "<tr id='tableRow'><td>" + this.app + "</td><td>" + this.priority + "</td><td>" + this.date + "</td><td>" + this.additionalNotes + "</td><td>" + "<input type='checkbox' class='checkApp[]' value='" + this.completed + "' />" + "</td></tr>";
};
I have all the checkboxes in the checkApp array, but Im not sure where to go from there?.
This is called when the form is submitted:
function addAppointment() {
if (txtApp.value == "" || txtPriority.value == "" || txtDate.value == "" || {
alert("Please fill all text fields");
} else {
var app = new Appointment(txtApp.value, txtPriority.value, txtDate.value, txtNotes.value, false);
apps.push(app);
localStorage.setItem("apps", JSON.stringify(apps));
clearUI();
}
updateTable();
updateTable() loops through all objects in my array and adds them between table tags:
for (var i = 0; i < apps.length; i++) {
var app = new Appointment(apps[i].app, apps[i].priority, expenses[i].date, apps[i].notes, false);
tblHTML += app.addRowToTable();
}
My Appointment Object:
function Appointment(app, priority, date, notes, completed) {
this.app = app;
this.priority = priority;
this.date = date;
this.additionalNotes = notes;
this.completed = completed;
this.addRowToTable = function { ... };
}
First of all, in HTML, id attributes should be unique. So, make sure table rows have unique IDs. At the moment, all of them have the identical ID of tableRow.
Besides, you should consider using a framework/library such as jQuery for real-world scenarios rather than creating the DOM elements, etc. manually.
Now back to the original problem: if you use the DOM API rather than string concatenation to create the table rows, you can add custom fields to the DOM objects representing the table rows. So, from each table row, you can have a reference back to its corresponding Appointment object:
var row = document.createElement("tr");
row.appointment = this;
Similarly, you can use the DOM API to create the table cells as well as the checkbox:
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
where addTd is the following function:
function addTd(row, innerHTML) {
var td = document.createElement("td");
td.innerHTML = innerHTML;
row.appendChild(td);
}
Now that you are using the DOM APIs, you can easily attach event listeners to each checkbox object as well.
Then inside the event listener you can get a reference back to the Appointment corresponding to the row you
have changed its checkbox:
var row = document.createElement("tr");
row.appointment = this;
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
input.addEventListener("change", function(event) {
var row = this.parentNode.parentNode,
appointment = row.appointment;
// change appointment however you like
});

JavaScript back button to display previous list

I want create a web application that display a list of items. Suppose I have displayed a list view (say listobject1) of 3 items. when clicked on any of them I get new list view (say listobject2) which its value is according to listobject1. When again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. when I'm now on listobject2 and again when back button is pressed I want to show listobject1. Can anybody tell me how I can do this in JavaScript?
Edit
I'm still study about the stuff but I can't solve this problem yet. In order to clarify my problem now, here's my code:
$(document).ready(function() {
$("#result").hide();
$("input[name='indexsearch']").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $("[name='valueLiteral']").val();
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">"
+ arraySubject[k] + "</span> " + " -> " + v + " : "+
//change object from text to be button form
"<button class = 'searchAgain-button' name = 'searchMore' \n\
value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br> <br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
$("button").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $(this).attr("Value");
//var $textInput = "G53SQM";
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
var searchMore = "searchMore";
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">" + arraySubject[k] + "</span> " + " -> " + v + " : "+ " <button class = 'searchAgain-button' name = " +searchMore + " value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br><br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
At first, user only see one button name "valueLiteral". After user perform 1st search, the result is return in a form of JSON and eventually put in stmt[] to display, which at this state the second button was create as a clickable-result which will automatically take the value of result and do second search if user click the second button.
Now the problem is, I want to add a 3rd HTML button name "back" to make the web display the previous result in stmt[] if user click on the button.
Hope this helps in clarify the problems, I'm still doing a hard work on this stuff since I'm a newbie in JavaScript. Appreciate all helps.
This is what you want almost exactly the way you want it.
You'll have to use history.pushState to push these fake events into the history.
Alternatively, you can use location.hash to store the current object, and update the hash every time you display a new list. Then onhashchange find the hash and display the appropriate list.
See http://jsfiddle.net/cFwME/
var history=[new Array(),new Array()];
history[0].id="#back";
history[1].id="#next";
Array.prototype.last=function(){
return this[this.length-1];
}
$('#list>li:not(:first)').click(function(){
if(!history[0].length || history[0].last().html()!=$('#list').html()){
history[0].push($('#list').clone(true,true));
$(history[0].id).prop('disabled',false);
history[1].length=0;
$(history[1].id).prop('disabled',true);
}
$('#list>li:first').html('This is List '+$(this).index());
});
$('#back').click(getHistory(0));
$('#next').click(getHistory(1));
function getHistory(n){
return function(){
if(!history[n].length){return false;}
history[(n+1)%2].push($('#list').replaceWith(history[n].last()));
history[n].pop();
$(history[(n+1)%2].id).prop('disabled',false);
if(!history[n].length){$(history[n].id).prop('disabled',true);}
}
}
Check out jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/

How do you dynamically create a radio button in Javascript that works in all browsers?

Dynamically creating a radio button using eg
var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
works in Firefox but not in IE. Why not?
Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Based on this post and its comments:
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;
}
Here's an example of more general solution which detects IE up front and handles other attributes IE also has problems with, extracted from DOMBuilder:
var createElement = (function()
{
// Detect IE using conditional compilation
if (/*#cc_on #*//*#if (#_win32)!/*#end #*/false)
{
// Translations for attribute names which IE would otherwise choke on
var attrTranslations =
{
"class": "className",
"for": "htmlFor"
};
var setAttribute = function(element, attr, value)
{
if (attrTranslations.hasOwnProperty(attr))
{
element[attrTranslations[attr]] = value;
}
else if (attr == "style")
{
element.style.cssText = value;
}
else
{
element.setAttribute(attr, value);
}
};
return function(tagName, attributes)
{
attributes = attributes || {};
// See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
if (attributes.hasOwnProperty("name") ||
attributes.hasOwnProperty("checked") ||
attributes.hasOwnProperty("multiple"))
{
var tagParts = ["<" + tagName];
if (attributes.hasOwnProperty("name"))
{
tagParts[tagParts.length] =
' name="' + attributes.name + '"';
delete attributes.name;
}
if (attributes.hasOwnProperty("checked") &&
"" + attributes.checked == "true")
{
tagParts[tagParts.length] = " checked";
delete attributes.checked;
}
if (attributes.hasOwnProperty("multiple") &&
"" + attributes.multiple == "true")
{
tagParts[tagParts.length] = " multiple";
delete attributes.multiple;
}
tagParts[tagParts.length] = ">";
var element =
document.createElement(tagParts.join(""));
}
else
{
var element = document.createElement(tagName);
}
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
setAttribute(element, attr, attributes[attr]);
}
}
return element;
};
}
// All other browsers
else
{
return function(tagName, attributes)
{
attributes = attributes || {};
var element = document.createElement(tagName);
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
element.setAttribute(attr, attributes[attr]);
}
}
return element;
};
}
})();
// Usage
var rb = createElement("input", {type: "radio", checked: true});
The full DOMBuilder version also handles event listener registration and specification of child nodes.
Personally I wouldn't create nodes myself. As you've noticed there are just too many browser specific problems. Normally I use Builder.node from script.aculo.us. Using this your code would become something like this:
Builder.node('input', {type: 'radio', name: name})
My solution:
html
head
script(type='text/javascript')
function createRadioButton()
{
var newRadioButton
= document.createElement(input(type='radio',name='radio',value='1st'));
document.body.insertBefore(newRadioButton);
}
body
input(type='button',onclick='createRadioButton();',value='Create Radio Button')
Dynamically created radio button in javascript:
<%# Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script type=”text/javascript”>
/* Getting Id of Div in which radio button will be add*/
var containerDivClientId = “<%= containerDiv.ClientID %>”;
/*variable count uses for define unique Ids of radio buttons and group name*/
var count = 100;
/*This function call by button OnClientClick event and uses for create radio buttons*/
function dynamicRadioButton()
{
/* create a radio button */
var radioYes = document.createElement(“input”);
radioYes.setAttribute(“type”, “radio”);
/*Set id of new created radio button*/
radioYes.setAttribute(“id”, “radioYes” + count);
/*set unique group name for pair of Yes / No */
radioYes.setAttribute(“name”, “Boolean” + count);
/*creating label for Text to Radio button*/
var lblYes = document.createElement(“lable”);
/*create text node for label Text which display for Radio button*/
var textYes = document.createTextNode(“Yes”);
/*add text to new create lable*/
lblYes.appendChild(textYes);
/*add radio button to Div*/
containerDiv.appendChild(radioYes);
/*add label text for radio button to Div*/
containerDiv.appendChild(lblYes);
/*add space between two radio buttons*/
var space = document.createElement(“span”);
space.setAttribute(“innerHTML”, “ &nbsp”);
containerDiv.appendChild(space);
var radioNo = document.createElement(“input”);
radioNo.setAttribute(“type”, “radio”);
radioNo.setAttribute(“id”, “radioNo” + count);
radioNo.setAttribute(“name”, “Boolean” + count);
var lblNo = document.createElement(“label”);
lblNo.innerHTML = “No”;
containerDiv.appendChild(radioNo);
containerDiv.appendChild(lblNo);
/*add new line for new pair of radio buttons*/
var spaceBr= document.createElement(“br”);
containerDiv.appendChild(spaceBr);
count++;
return false;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />
<div id=”containerDiv” runat=”server”></div>
</div>
</form>
</body>
</html>
(source)
for(i=0;i<=10;i++){
var selecttag1=document.createElement("input");
selecttag1.setAttribute("type", "radio");
selecttag1.setAttribute("name", "irrSelectNo"+i);
selecttag1.setAttribute("value", "N");
selecttag1.setAttribute("id","irrSelectNo"+i);
var lbl1 = document.createElement("label");
lbl1.innerHTML = "YES";
cell3Div.appendChild(lbl);
cell3Div.appendChild(selecttag1);
}
Quick reply to an older post:
The post above by Roundcrisis is fine, IF AND ONLY IF, you know the number of radio/checkbox controls that will be used before-hand. In some situations, addressed by this topic of 'dynamically creating radio buttons', the number of controls that will be needed by the user is not known. Further, I do not recommend 'skipping' the 'try-catch' error trapping, as this allows for ease of catching future browser implementations which may not comply with the current standards. Of these solutions, I recommend using the solution proposed by Patrick Wilkes in his reply to his own question.
This is repeated here in an effort to avoid confusion:
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;}
Patrick's answer works, or you can set the "defaultChecked" attribute too (this will work in IE for radio or checkbox elements, and won't cause errors in other browsers.
PS Full list of attributes you can't set in IE is listed here:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
why not creating the input, set the style to dispaly: none and then change the display when necesary
this way you can also probably handle users whitout js better.
My suggestion is not to use document.Create(). Better solution is to construct actual HTML of future control and then assign it like innerHTML to some placeholder - it allows browser to render it itself which is much faster than any JS DOM manipulations.
Cheers.

Categories

Resources