I have a report populated as a table with a stringbuilder from the codebehind. The first TD of every row is a checkbox, the id of each checkbox is assigned dynamically:
sb.Append("<td><input type='checkbox' id='chkSelectAll_" + i + "' name='chk_" + i + "' onclick='JavaScript: chkAll_click(this);' /> </td>"
The aspx page uses a master page and
<asp:Content><div id='divMain'></div></asp:Content>
format other than a form to populate. The problem I am running in to is that I am having trouble finding all the elements (or any actually) of the div to work with. Here is the javascript I have been given. (Team project at work, I was just assigned 1 task on the project so changing anything is not an option.)
function divBatchBuild_click() {
debugger
var form = document.forms[0];
var visitList = '';
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == 'checkbox') {
//alert(form.elements[i].id.toString());
if (form.elements[i].checked == true &&
form.elements[i].id != 'chkSelectAll') {
var y = form.elements[i].id;
//alert('id=' + y[1].toString());
visitList = visitList + y[i].toString() + '|';
}
}
}
}
Apparently this worked on a previous project, but when used with this report the process never goes inside the if statement. Any help on what is going wrong is appreciated.
I think you want to first get the div, then get the elements in the div with the checkbox tagname. Something like:
var div = document.getElementById('divMain');
var elements = div.getElementsByTagName('checkbox');
for (i = 0; i < elements.length; i++) {
Related
I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
I have a gridview which has some templatefield. At cell5 i have a label which is the input for database. but not all the labels in all the rows contains the value. its based on the click event of an editTemplateField. I have vb.net code for accessing that label inside the gridview. but i want to get it by javascript. following is the sample vb.net code and javascript that i have tried so far.
For Each i as gridViewRow in gridview.Rows
Dim lnk as linkbutton = CType(i.FindControl("del"),LinkButton)
If lnk.ForeColor = Drawing.Color.Red
pid = CType(gridview.Rows(i).FindControl("lblposid"), Label).Text
End If
Next
javascript:
for (var i = 0; i < grid.rows.length-1; i++) {
if(grid.rows[i].cells[1].style.color == "red")
pid = grid.rows[i].cells[5].innerHTML;
}
vb.net works . but javascript is not working. i dont know how to make it in javascript.Thanks in advance]
Note: The template field's visible is "False" also.
I found my own solution now.
for (var i = 1; i < grid.rows.length; i++)
{
var links = grid.rows[i].getElementsByTagName("a");
if(links[1].style.color=="red")
{
var spanlist = grid.rows[i].getElementsByTagName("span");
pid=spanlist[1].innerHTML;
links[1].style.color="blue";
}
}
Hi this is a second part to an early question. I need to add rows to a form consisting of a selection box. Each row of the form is a type of "Room" in a house and the user has to be able to add as many rooms as needed. I have it all working however if you fill in the 2nd room and then add a 3rd room it resets the selection box to its default for the 2nd room. I can see why it is doing this i just cant think of how to change the function so it keeps your previous selections intact. Note: i have the 1st row for the 1st room written in the HTML then this function(below) is called from a button click and adds the extra rooms.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room')
var roomSelect = '<select name="level[]" id="levels"' + room_count + '/> ';
roomSelect += '<option>Basement</option>';
roomSelect += '<option>Lower Level</option>';
roomSelect += '<option>Main Floor</option>';
roomSelect += '<option>2nd Floor</option>';
roomSelect += '<option>3rd Floor</option></select>';
write.innerHTML += roomSelect;
room_count++;
}
Thanks for any help you can offer!
This is because of the magic of .innerHTML +=.
As you might have guessed, It's actually identical to div.innerHTML = div.innerHTML + moreHTML - So the browser resets the HTML of the div. Including any selection, obviously.
I'd recommend you used div.appendChild. It doesn't change previously loaded HTML, and so won't change the user's selection.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room');
var roomSelect = document.createElement('select'); // create select node
roomSelect.setAttribute("name", "level[]");
roomSelect.setAttribute("id", "levels" + room_count);
roomSelect.innerHTML = '<option>Basement</option>'+ //set the innerHTML (the options)
'<option>Lower Level</option>'+
'<option>Main Floor</option>'+
'<option>2nd Floor</option>'+
'<option>3rd Floor</option>'
write.appendChild(roomSelect); //append the child
room_count++;
}
I've a database containing the options to add dynamically, after button click, in a <select> tag.
This is what the HTML looks like, its inside a div with data-role="page" (for jQuerymobile)
<div id="endSessionPageContent" data-role="content">
<div data-role='fieldcontain' id="endSessionForm">
</div>
</div>
Basically, I get some values from a sqlite database, and then I'd like to put them inside the "endSessionForm" div. The data should be displayed both with <inputs> and <select> elements.
The function looks like this (no sql interaction here, for simplicity):
function buildPage(divId){
$("#endSessionForm").empty();
var div = "<div><label>aaa</label><input></input></div>";
div += "<div><label>bbb</label><input></input></div>";
div += "<div><select><option>1</option><option>2</option><option>3</option></select></div>";
$('#endSessionForm').append(div);
$("#endSessionForm").trigger('create');
}
Then after some event, I call the buildPage function (see this jsfiddle for a live example http://jsfiddle.net/xdR43/12/). The trigger(create) is used to force the UI reload:
As you can see, the <select> is not properly created. The jsfiddle page throws this error:
Syntax error, unrecognized expression: :nth-child
while, the same code in my app throws this error:
'undefined' is not an object (evaluating 'this.list[0].appendChild')
What do you think is wrong? Thanks for any help, I hope I gave you all the informations you need. If you need more, ask and I'll add em.
Thanks again, best regards
______EDIT________
this is the entire function:
function buildPage(divId){
$(divId).empty();
for(var i = 0; i < results.rows.length; i++){
var area = results.rows.item(i).area;
var campo = results.rows.item(i).campo;
var campoWOspcs = campo.replace(/ /g,"_");
var valori = results.rows.item(i).valori;
var div = "<div><label for='newCompany_"+campoWOspcs+"'>"+campo+":</label>";
if(valori == ""){ //input
div += "<input type='text' name='"+campoWOspcs+"' id='newCompany_"+campoWOspcs+"' placeholder='"+campo+"'></input>";
}else{ //select
div += "<select name='"+campoWOspcs+"' multiple='multiple' id='newCompany_"+campoWOspcs+"'><option>Select "+campo+"</option>";
var split = valori.split(";");
for(var j = 0; j < (split.length -1); j++ ){
div += "<option>"+split[j]+"</option>";
}
div += "</select>";
}
div += "</div>";
$(divId).append(div);//alert(div);
}
$(divId).append(div);
$(divId).trigger('create');
}
General Info:
Aspx page holds an Ascx User control. Inside the User control, the Repeater is contained inside a View, contained inside a Multiview.
Asp.Net 2.0 framework / C#
Details:
I have a repeater (inside an ascx user control) that shows records, and the first column is a checkbox. If checked, that row will be deleted.
OUtside the repeater, I have a button that will deleted all rows that are checked.
Everything works fine, but have been asked to add a pop up "confirm delete" message that includes the number of records that will be deleted if the user clicks "Ok" on the pop up.
Something like:
"You are about to delete 8 records".
Currently my button looks like this:
<asp:Button ID="btnDeleteAllRecords" runat="server" Text="Delete all Checked Records" Onclick="btnDeleteAllRecords_Click" OnClientClick="javascript:GetCbCount();" />
I have this javascript code block:
<script type="text/javascript">
function GetCbCount()
{
var cb = document.getElementById("rptrVoicemail").getElementsByTageName("input");
var cbCount;
for(i = 0; i < cb.lenght; i++)
{
if(cb[i].type == "checkbox")
{
if(cb[i].checked)
{
cbCount = cbCount + 1;
}
}
}
return confirm('You are about to delete' + cbCount + 'records.');
}
</script>
When I click my button I'm getting:
Error: 'document.getElementById(...)' is null or not an object
on this line:
var cb = document.getElementById("rptrVoicemail").getElementsByTageName("input");
Why is the JS not seeing my repeater? Is it because it's buried inside a MultiView? How can the JS be corrected so that the pop up will show the record count in the message?
UPDATE:
I changed the script to:
function GetCbCount(){
var inpt = document.getElementById("vmDiv");
var checkboxes = inpt.getElementsByTagName("input");
var cbCount;
for(i = 0; i<checkboxes.lenght;i++){
if (checkboxes[i].type == "checkbox" && checkboxes[i].checked){
cbCount = cbCount + 1;
}
}
return confirm('You are about to delete ' + cbCount + ' Voicemails.');
}
This should work:
document.getElementById('<%= rptrVoicemail.ClientID %>').getElementsByTageName("input");
Another approach is this little script that returns the ClientID. You could add it even to an included JS-file.
function GetClientId(strid)
{
var count=document.forms[ 0 ].length ;
var i = 0 ;
var eleName;
for (i = 0 ; i < count ; i++ )
{
eleName = document.forms [ 0 ].elements[ i ].id;
pos=eleName.indexOf( strid ) ;
if(pos >= 0) break;
}
return eleName;
}
Found here.
If you are using a master page or nesting controls (inside ascx, view, etc.) the framework will change the IDs that are rendered with elements.
If you do a "View Source" or use FireBug, you might see that rptrVoicemail became something like ctl00_ContentPlaceHolder1_someUserControl_ctl00_multiViewID_ctl28_rptrVoicemail.
You can use getElementById('<%= rptrVoicemail.ClientID %>') to get at the ID of the element as it would be rendered on the client.
Edit: To help debug, do something like this... you get the point.
var rptr = document.getElementById('<%= rptrVoicemail.ClientID %>');
rptr.borderColor = 'pink'; // draw a border to check it's the right element