Button click not fire after remove element - javascript

I have create a div like this
<div id="hidden">
<img src="photos/Close-2-icon.png" width="16" height="16">
<input id="add" value="Add feild" type="button" >
<input type='button' id='h_div_ok' value="check !" />
<div id="inside_display" >
</div>
<input type="button" value="Insert" id="btninser" >
</div>
and when click the add button it will create a table. This is the jquery for
that.$("#add").click(function() {
i++;
var input = jQuery('<tr><td><input type=\"text\" id=\"input_'+i+'\"></td><td><textarea id=\"txtar_'+i+'\"></textarea></td><td><input type=\"button\" id=\"remove_'+i+'\" value=\"Remove\" /></td></tr>');
if(i == 1){
jQuery('#hidden').append('<table>');
jQuery('#hidden table').append(input);
jQuery('#hidden table').append('</table>');
}else{
jQuery('#hidden table tr:last').after(input);
}
$("#remove_" + i).click(function(){
if(i == 1){
$(this).closest("table").remove();
}else{
$(this).closest("tr").remove();
}
});
i is a global variable. Then after click the btninser button it will generate a string of the dynamically created table code.
$('#btninser').click(function(){
$('#'+id).text(getval());
$("#hidden table").remove();
});
function getval(){
var htmlString = '<table>';
var j;
for(j=1; j<=i; j++){
if($('#input_'+j).length === 0){
}else{
var itval = $('#input_'+j).val();
var taval = $('#txtar_'+j).val();
htmlString =htmlString + ('<tr><td>'+itval+'</td><td>'+taval+'</td></tr>');
}
}
htmlString =htmlString + ('</table>');
return htmlString;
}
in this case id also a global variable and it is just a id of a textare. after that if i click add button again that event not firing. How can i solve this ?

Here you should go with "i--" it make ur "i" count correct ,same as u done with i++.
also need to do this
$('#remove_'+i).click(function () {
i--;
});
Your code
$(document).ready(function () {
$("#add").click(function () {
i++;
var input = jQuery('<tr><td><input type=\"text\" id=\"input_' + i + '\"></td><td><textarea id=\"txtar_' + i + '\"></textarea></td><td><input type=\"button\" id=\"remove_' + i + '\" value=\"Remove\" /></td></tr>');
if (i == 1) {
jQuery('#hidden').append('<table>');
jQuery('#hidden table').append(input);
jQuery('#hidden table').append('</table>');
} else {
jQuery('#hidden table tr:last').after(input);
}
$("#remove_" + i).click(function () {
if (i == 1) {
$(this).closest("table").remove();
} else {
$(this).closest("tr").remove();
}
});
$('#btninser').click(function () {
$('#' + id).text(getval());
$("#hidden table").remove();
})
**$('#remove_'+i).click(function () {
i--;
});**
});
});
function getval() {
alert("getval");
var htmlString = '<table>';
var j;
for (j = 1; j <= i; j++) {
if ($('#input_' + j).length === 0) {
} else {
var itval = $('#input_' + j).val();
var taval = $('#txtar_' + j).val();
htmlString = htmlString + ('<tr><td>' + itval + '</td><td>' + taval + '</td></tr>');
}
}
htmlString = htmlString + ('</table>');
return htmlString;
}

I think you need to reset i variable so your table will be redrawn again when pressing add button (if (i == 1))
$('#btninser').click(function() {
$('#' + id).text(getval());
$("#hidden table").remove();
i = 0; //here!
});

if your 2nd code block is exactly how you have it in your code, then your #add event handler is missing its end close brackets. Also, Im not sure what you have that doing in front of the jquery selector..
that.$("#add").click(function() {
i++;
// .......
}else{
$(this).closest("tr").remove();
}
});
assuming your 2nd event handler is intended to be nested, it should be..
$("#add").click(function() {
i++;
// .......
}else{
$(this).closest("tr").remove();
}
});
});

Related

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

Recursive previous and next in arrow key press in custom autocomplete with jquery

I have developed customise autocomplete which works fine in terms of data pulling and displaying in the page. I want to enhance it. I want to implement something like this (multiple dataset of typeahead pluggin) where I want to select or set focus on the next and previous li of my autocomplete when down / up arrow key is pressed. Here is my jquery code which populate the autocomplete.
$("input[data-tg-autocomplete]").keyup(function (e) {
if (e.keyCode == 40 || e.keyCode == 38) {
//alert(e.keyCode);
DownUpKeyPress(e.keyCode);
}
else {
var $input = $(this);
//-----------------------------Allowing user to enter atleast one character for auto search
if ($input.val().length > 0) {
var request = $.ajax({
url: $input.attr("data-tg-autocomplete"),
method: "GET",
data: { term: $input.val() },
dataType: "json"
});
request.done(function (JsonData) {
LoadAutoSuggest(JsonData);
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
});
}
}
});
//========================populate autocomplete
function LoadAutoSuggest(result) {
var tag = "";
$('.custom-autocomplete').html("");
if (result.Destination != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Destination";
tag = tag + "</a>";
tag = tag + "</li>";
for (i = 0; i < result.Destination.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Destination' data-id='" + result.Destination[i].DestinationID + "'>";
tag = tag + "<div>";
tag = tag + result.Destination[i].DestinationName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
}
}
if (result.Business != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Business";
tag = tag + "</a>";
tag = tag + " </li>";
for (i = 0; i < result.Business.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Business' data-id='" + result.Business[i].BusinessID + "'>";
tag = tag + "<div>";
tag = tag + result.Business[i].BusinessName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
//alert(result.Business[i].BusinessName + " ID = " + result.Business[i].BusinessID)
}
}
$('.custom-autocomplete').html(tag);
$('.autocompleteListItem').click(function () {
var id = $(this).attr("data-id");
var type = $(this).attr("data-type");
var text = $(this).text();
$("#searchtext").val(text);
$('.HiddenSearchInput #id').val(id);
$('.HiddenSearchInput #type').val(type);
$('.custom-autocomplete').html("");
$('.Search-submit').trigger("click");
});
$(':not(".search-wrapper")').click(function () {
if ($('.custom-autocomplete li').length > 0) {
$('.custom-autocomplete').html("");
}
});
$('.custom-autocomplete li.list-group-item').first().addClass("focused");
}
function DownUpKeyPress(keyCode) {
//$this = $(this);
if (keyCode == 40) {
// alert('40');
// $this.next().focus();
if ($('.custom-autocomplete li').length > 0) {
var $focused = $('.custom-autocomplete li.focused');
$('.custom-autocomplete li.focused ~ .list-group-item').first().addClass('focused')
$focused.removeClass('focused')
}
return false;
} else if (keyCode == 38) {
//alert('38');
// $this.prev().focus();
if ($('.custom-autocomplete li').length > 0) {
}
return false;
}
}
and here is my html where I am populating the autocomplete
<div class="Search-container">
<span class="error search-validation"></span>
<div class="input-group input-group-lg">
<input id="searchtext" name="searchtext" type="text" class="form-control " placeholder="Find travel agents, search travel agents in your destination" data-tg-autocomplete="#Url.Action("AutocompleteBusiness")" />
<span class="input-group-btn">
<button class="btn btn-primary Search-submit" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div><!-- /input-group -->
<div class="displaynone HiddenSearchInput">
<input type="hidden" id="id" name="id" value="" />
<input type="hidden" id="type" name="type" value="" />
</div>
</div>
<ul class="list-group custom-autocomplete">
#*List will be populated from ajax call in function LoadAutoSuggest*#
</ul>
My function DownUpKeyPress is for setting focus for next and previous li. Focused li item will be used for site search but I am not been able to set focus on the next and previous li when up/down arrow is pressed. I am using MVC5 for developing my project. Probably I am wrong with jquery. May someone help me out to fix the issue. I dont want to use any pluggin for this.
Add this code in DownUpKeyPress
// for up arrow => Previous Li Focus
if (keyCode == 40) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').next('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').first().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').next('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').addClass('focused');
}
}
return false;
}
// for down arrow => Next Li Focus
else if (keyCode == 38) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').prev('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').last().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').prev('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').addClass('focused');
}
}
return false;
}

How to get the values of all textfields in add/remove textfields and form JSON

I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});

how to show hidden button if more than 1 checkbox selected

I have 2 buttons add and group. Initially group button is hidden. Add button is used for creating records.
So for example:
When 5 records are created(pressing 5 times add button). Now if user selects more than
checkbox, then the hidden group button should appear. Can any body please tell me how to do this?
Please see this fiddle
I am using bootstrap css and for hiding I do as
<input type="button" id="btn2" class="btn btn-lg btn-primary hide" value="Group">
UPDATE
Check boxes will only appear if user enters some records. Filling the form and after pressing the add button
See this FIDDLE
$(document).on('change','#mytable input:checkbox',function () {
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
});
Here's the FIDDLE
if($('#mytable input:checkbox:checked').length > 1)
$('#btn2').show();
else
$('#btn2').hide();
Add a check in the change event for the checkboxes. fiddle and example below:
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//updated using your bootstrap class to show/hide
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide');
} else {
$('#btn2').addClass('hide');
}
});
Updated to use bootstrap class as per your updated question.
Try This
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});;
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
var rowCount = $('#mytable tr').length;
if($('input:checkbox:checked').length > 1 && rowcount > 6) {
$('#btn2').removeClass('hide')
}
});
});
Updted Fiddle is : http://jsfiddle.net/4GP9c/184/

Pure Javascript to get all span elements but make editable specificly by the defined class

I need only pure javascript assistance for the following code to work as mentioned in my post title.
jsfiddle: demo
Full source pasted below:
<!DOCTYPE html>
<script>
function init_events(){
if (!document.getElementsByTagName){ return; }
get all the spans here
var divReports = document.getElementById('reports');
divReports.innerHTML = '<ol><b>Reports:</b>';
var allSpans = document.getElementsByTagName('span');
// Not getting or alerting values
var allCanEditSpans = function(){
if(allSpans.className == 'canEdit'){
alert("canEdit!");
}
};
// Not getting or alerting values
var allCant_EditSpans = function(){
if(allSpans.className == 'cant_Edit'){
alert("cant_Edit!");
}
};
add events
if (document.addEventListener) { // For all browsers minus IE
divReports.innerHTML += '<li>Total '+ allSpans.length + ' spans detected.</li>';
divReports.innerHTML += '<li>Total '+ allCanEditSpans.length + ' Editable spans detected.</li>';
divReports.innerHTML += '<li>Total '+ allCant_EditSpans.length + ' Not Editable spans detected.</li>';
divReports.innerHTML += '</ol>';
divReports.innerHTML += '<ol><b>Actice Span:</b>';
for (var i=0; i<allSpans.length; i++){
var activeSpan = allSpans[i];
divReports.innerHTML += '<li>Active Span ID: ' + activeSpan.id + '\nSpan Text: ' + activeSpan.innerHTML +'</li>';
if (activeSpan.className == 'canEdit') {
activeSpan.addEventListener('mouseover', function (e) {
activeSpan.style.cursor = 'pointer';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = '1px solid red';
divReports.innerHTML += '<li>On Mouse Active Span: '+activeSpan.id +'</li>'; // Debug - Why it always takes the last span
});
activeSpan.addEventListener('mouseout', function (e) {
activeSpan.style.cursor = 'auto';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = 'none';
});
activeSpan.addEventListener('click', function (e) {
activeSpan.style.cursor = 'auto';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = '1px dotted yellow';
activeSpan.innerHTML = '<input type="text" name="txtInput">'; // Add text box
activeSpan.innerHTML += '<input type="button" name="butSave" value="Save">'; // Add Save button
activeSpan.innerHTML += '<input type="button" name="butCancel" value="Cancel">'; // Add Cancell butto
});
}
divReports.innerHTML += '</ol>';
}
}else { // For the always BUGGY or Lonely IE!
divReports.innerHTML += '<li>Total '+ allSpans.length + ' spans detected.</li>';
divReports.innerHTML += '<li>Total '+ allCanEditSpans.length + ' Editable spans detected.</li>';
divReports.innerHTML += '<li>Total '+ allCant_EditSpans.length + ' Not Editable spans detected.</li>';
divReports.innerHTML += '</ol>';
divReports.innerHTML += '<ol><b>Actice Span:</b>';
for (var i=0; i<allSpans.length; i++){
var activeSpan = allSpans[i];
divReports.innerHTML += '<li>Active Span ID: ' + activeSpan.id + '\nSpan Text: ' + activeSpan.innerHTML +'</li>';
check if they are of a canEdit class
if (activeSpan.className == 'canEdit') {
activeSpan.attachEvent('onmouseover', function (e) {
activeSpan.style.cursor = 'pointer';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = '1px solid red';
divReports.innerHTML += '<li>On Mouse Active Span: '+activeSpan.id +'</li>'; // Debug - Why it always takes the last span
});
activeSpan.attachEvent('onmouseout', function (e) {
activeSpan.style.cursor = 'auto';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = 'none';
});
activeSpan.attachEvent('onclick', function (e) {
activeSpan.style.cursor = 'auto';
activeSpan.title = 'Click to Edit.';
activeSpan.style.border = '1px dotted yellow';
activeSpan.innerHTML = '<input type="text" name="txtInput">'; // Add text box
activeSpan.innerHTML += '<input type="button" name="butSave" value="Save">'; // Add Save button
activeSpan.innerHTML += '<input type="button" name="butCancel" value="Cancel">'; // Add Cancell butto
});
}
}
divReports.innerHTML += '</ol>';
}
// DEBUG TEST -> START
var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
if (spans[i].className == 'canEdit') {
spans[i].style.backgroundColor = '#999dee';
}
if (spans[i].className == 'cant_Edit') {
spans[i].style.backgroundColor = '#555dee';
}
}
// DEUG TEST <- END
}
</script>
<span id="span_1" class="canEdit">I am editable!</span>
<br>
<span id="span_2" class="cant_Edit">I am not editable!</span>
<br>
<span id="span_3" class="canEdit">I am editable!</span>
<br>
<hr>
<p>Not span</p>
<table border="1">
<tr>
<td><span id="span_td1" class="cant_Edit">I am not editable!</span></td>
<td><span id="span_td2" class="canEdit">I am editable!</span></td>
<td><span id="span_td3" class="cant_Edit">I am not editable!</span></td>
<td>Not span</td>
</tr>
</table>
<hr>
<div id="reports">
</div>
<script>
init_events();
</script>
// Not getting or alerting values
var allCanEditSpans = function(){
if(allSpans.className == 'canEdit') {
...
var allSpans = document.getElementsByTagName('span'); //allSpans is an HTMLCollection
The result of getElementsByTagName is an HTMLCollection, which doesn't have a className property.
var allCanEditSpans = function(){
var count = 0;
for(var i = 0; i < allSpans.length; i ++) {
if(allSpans[i].className === 'canEdit') {
count ++;
}
}
return count;
}();
And use it like this:
divReports.innerHTML += '<li>Total '+ allCanEditSpans + ' Editable spans detected.</li>';
For newer browsers, you can use Array.prototype.filter as in:
var allCant_EditSpans = function() {
return Array.prototype.filter.call(allSpans, function(span) {
return span.className === 'cant_Edit';
}).length;
}();
Using the new Selectors API:
var allCanEditSpans = document.querySelectorAll('span.canEdit').length;
Updated jsFiddle Demo
EDIT: For the event listener part, you need to create a closure
if (activeSpan.className == 'canEdit') {
(function(aSpan) {
aSpan.addEventListener('mouseover', function (e) {
aSpan.style.cursor = 'pointer';
aSpan.title = 'Click to Edit.';
aSpan.style.border = '1px solid red';
divReports.innerHTML += '<li>On Mouse Active Span: '+aSpan.id +'</li>'; // Debug - Why it always takes the last span
})(activeSpan);
}
jsFiddle Demo

Categories

Resources