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{
//
}
I'm trying to make a graph with the content in a GridView, and now I have this codes:
string js0 = #"var data = {}; CarregarGrafico(data);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Graph0L", js0, true);
var i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
string periodo = "" + row.Cells[0].Text + "/" + row.Cells[1].Text + "";
string prevReceb = row.Cells[6].Text.ToString();
string totalReceb = row.Cells[10].Text.ToString();
string js1 = #"myBarChart.addData([{1}, {2}], '{0}');";
js1 = js1.Replace("{0}", periodo).Replace("{1}", prevReceb).Replace("{2}", totalReceb);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Graph1L", js1, true);
i++;
if (i >= 10) break;
}
But I'm dealing with some problems:
Script aren't appearing at the page
I can't get the prevReceb and totalReceb values because it was in a <span> tag. How can I use only text into span of the cell?
Please, help me, thanks.
I have the following jQuery:
<script>
$(document).ready(function () {
$('#btnGetIDs').click(function getIDs() {
var checkedIds = $(":checkbox:checked").map(function () {
return this.id;
}).get();
});
});
</script>
This is used for the creation of the checkboxes (it is nested within a lengthy foreach datarow in datatable).
results.Append("<td> <input id=" + RosteredCareID + " type=\"checkbox\" unchecked> </td>");
Which I can see, from debugging in the browser, is working as intended and creating an array of IDs.
The intended functionality is:
1. System loads page
2. User clicks some check boxes
3. User clicks submit
4. System gets the IDs of checked boxes and stores in array
Here
protected void btnConfirm_Click(object sender, EventArgs e)
{
string[] IDs = new string[20];
// IDs = "";
}
So how I can access the jQuery array from the btnConfirm_Click event?
I have tried a scriptmanager line of code but it was causing errors with a scriptmanager on a masterpage.
Add a name property to your checkbox markup.
results.Append("<td><input id='" + RosteredCareID + "' type='checkbox' name='" + RosteredCareID + "' unchecked /></td>");
(Notice I properly quoted your ID. And I used single quotes within the JS string to avoid the need to escape your double quotes.)
Then in the server side, the values will be available in the Request.Form property. You can enumerate over them like this:
foreach (var name in Request.Form.AllKeys)
{
System.Diagnostics.Debug.WriteLine("Form Name: " + name + " Form Value: " + Request.Form[key]);
}
If the value is checked, it will be in there.
There may be lots of form values, so you'll need to filter them to get only what you want. I suggest you prefix your name with a particular string. Ex:
results.Append("<td><input id='" + RosteredCareID + "' type='checkbox' name='RosterCareCB_" + RosteredCareID + "' unchecked /></td>");
Then on the server side, filter on that prefix.
var checkedIds = new List<string>();
foreach (var name in Request.Form.AllKeys)
{
if(name.StartsWith("RosterCareCB_") && Request.Form[name] == "on")
{
checkedIds.Add(name);
}
}
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
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”, “  ”);
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.