click(dataMap, method) version of the jQuery is not working - javascript

I tried to pass data through the click method to test it out so that I do not have to call a function from handler onclick. I want to do this to prevent the default submit whenever I press any button. Like this instead of having.
<button onclick="addAuthor()">Add Author</button>
I can have something like:
<button id="addAuthor">Add Author</button>
Which would go to.
$("#addAuthor").click({
id: 100
}, addAuthor);
Then.
function addAuthor(dataMap) {
alert(dataMap.data.id)
//add another author
}
I want the button "Remove div2" to do the same thing the span "Remove" does.
For now I had it to give an alert with the value of 100 but it does not even do that.
$("removeDiv").click({bookDiv: count}, removeDiv);
This is what I want to put so that the variables are passed but the test doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
////////////////////////////////////////////////
//HERE
$("#removeDiv1").click({
id: 100
}, removeDiv1);
////////////////////////////////////////////////
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>'
///////////////////////////////////////////////////
////HERE
+ '<button id="removeDiv1"> Remove div2</button>'
///////////////////////////////////////////////////
+ '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
///////////////////////////////////////////
//HERE
function removeDiv1(dataMap) {
alert(dataMap.data.id)
}
///////////////////////////////////////////
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>

The problem isn't with passing in the dataMap (try it without it; it still won't work).
The problem is that when you attempt to set your click handler with $("#removeDiv1").click(...), the #removeDiv1 element doesn't exist yet - it's created and added to the DOM later, in addMore.
You need to do one of the following:
Set your click handler inside of addMore, after str is appended.
Change your click handler to use jQuery's event delegation capabilities. $("#removeDiv1").click(...) becomes $("body").on('click', '#removeDiv1', ...)
Side note: the "body" selector can be replaced by any selector that will select an ancestor of #removeDiv1; the click event propagates up from #removeDiv1 to its parent, its parent parent, and so on, until it's handled and something calls e.stopPropagation(), or until it reaches the document root.

First off, this is really something that Angular or something like it can do much better.
Next, I wouldn't use ids. You can do the same thing with classes without having to increment and restrict your code. Here's how I'd code the HTML:
<div>
<h1>My favorite authors and their books</h1>
<button class="js-add">Add An Author</button>
<div class="authors"></div>
<button class="js-save">Save</button>
</div>
I've also pulled all the javascript out of the HTML.
Next, "click" won't apply to items added after it is stated. You either need to re-state a click for the new element, or you need to use "on". Note in the code below that I can use the "click" method for "add Author" because that button exists when the script was run. For the other buttons, I had to use "on('click'..."
var addAuthor = function($this) {
var books = $('<div>')
.addClass('books')
.append(
$('<button>')
.addClass('js-addBook')
.html('Add a book')
)
.append(
$('<div>')
.addClass('bookName')
.html('Books:')
);
addBook(books.find('button'));
$($this)
.parent()
.find('.authors')
.append(
$('<div>')
.addClass('author')
.append(
$('<div>')
.addClass('authorName')
.html('Author: ')
.append(
$('<div>')
.addClass('remove js-removeAuthor')
.html('x')
)
.append(
$('<input>')
)
)
.append(
books
)
)
};
var addBook = function($this) {
$($this)
.parent()
.append(
$('<div>')
.addClass('book')
.append(
$('<div>')
.addClass('remove js-removeBook')
.html('x')
)
.append(
$('<input>')
)
)
};
addAuthor($('button.addAuthor'));
$('.js-addAuthor').click(function() {
addAuthor(this);
});
$('.authors').on('click', '.js-addBook', function() {
addBook(this);
});
$('.authors').on('click', '.js-removeBook, .js-removeAuthor', function() {
$(this)
.parent()
.remove()
});
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/rt3tpeta/3/

Related

Find all Divs after being created with JQuery on click event

I'm trying to find all divs that have been created from my click event and split them into another div (.wrapAll) on a count of 3. I can't seem to get anything back when i console.log the vars length. I know this works when I do that same process on the html thats been statically typed. Below is my code and thank you fo the thoughts!
jQuery(document).ready(function($) {
// load default twitch channels
$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {
//console.log(data);
});
// Bind 'Enter' to click event
$(document).bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#search').trigger('click');
}
});
// manually search for games
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
// console.log(data2.streams.length);
data2.streams.forEach(function(entry) {
//console.log(entry._links);
var streamURL = entry.channel.url;
url = entry.preview.medium;
$('#results').append('<div class="searchResults"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></div><hr>');
});
});
// Get 3 divs and slice into one div to style ** problem child **
var a = $('div[id^=searchResu]').find('div');
console.log(a.length);
for( var i = 0; i < a.length; i+=3 ) {
a.slice(i, i+3).wrapAll('<div class="slide"></div>');
}
});
});
Check out this plunker here. I believe this does what your looking for.
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
<script>
jQuery(document).ready(function($) {
function appendHtmlContent(resultHtmlContent) {
resultHtmlContent = '<div class="slide">' + resultHtmlContent + '</div>';
$('#results').append(resultHtmlContent);
}
function processSvcResponse(data2) {
var count = 0,
searchResultContents = '',
$div = $("<div>", { class: "searchResults"});
data2.streams.forEach(function(entry) {
var streamURL = entry.channel.url;
url = entry.preview.medium;
searchResultContents += '<div class="searchResults"><a href="' + streamURL
+ '" target="_blank"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game
+ '<br> Viewers: ' + entry.viewers + '<br> Is Mature: ' + entry.channel.mature
+ '<br> Status: ' + entry.channel.status + ' </p></a></div><hr>';
count++;
if(count === 3) {
appendHtmlContent(searchResultContents);
searchResultContents = '';
count = 0;
}
});
// more results that have not been appended?
if(searchResultContents) {
appendHtmlContent(searchResultContents);
}
}
// load default twitch channels
$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {});
// Bind 'Enter' to click event
$(document).bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#search').trigger('click');
}
});
// manually search for games
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=" + search, processSvcResponse);
});
});
</script>
</head>
<body>
<input id="searchTerm" type="text" />
<button id="search" type="button">Search</button>
<div id="results"></div>
</body>
</html>
If I understand correctly you are wanting to iterate over the results and for every third one wrap it inside a div with class "slider". As mentioned in the comments by #charlietfl in order to query newly created DOM elements using jQuery you have to query them after they are created. In the call to jQuery.getJSON the second argument accepts a callback function. The signature is jQuery.getJSON(url, someCallbackFunction). In order to make your code a bit more readable I moved "function(data2)" up and named it processSvcResponse. Inside processSvcResponse I build up an HTML string from the results and track how many results are processed by using a counter variable. Once the counter reaches 3 I append the contents to the results div and reset the counter. This solution does not "find" the divs and slice/wrapAll as you were intending to do originally, however, I believe this still accomplishes your goal.
As #charlietfl said, you'll need to place the code that wraps your divs in the callback for getJSON. Your click event listener would look something like this then:
$('#search').on("click", function() {
// clear previous results and get search term
$('#results').html('');
search = $('#searchTerm').val();
// begin API call
$.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
// console.log(data2.streams.length);
data2.streams.forEach(function(entry) {
//console.log(entry._links);
var streamURL = entry.channel.url;
url = entry.preview.medium;
$('#results').append('<div class="searchResults"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></div><hr>');
});
// Get 3 divs and slice into one div to style ** problem child **
var a = $('div[id^=searchResu]').find('div');
console.log(a.length);
for( var i = 0; i < a.length; i+=3 ) {
a.slice(i, i+3).wrapAll('<div class="slide"></div>');
}
});
});

Using an event handler on a anchor link added in Javascript

I have an Ajax call that returns an array of movie titles. I'd like to click on a button next to each title and add the title to a "currently watching" list. My "add" link doesn't seem to be accepting the event handler. What can I do to add the specified title to my "currently watching" list
$("#search").click(function(event){ event.preventDefault();
var show = $("#showTitle").val().toLowerCase();
console.log("the show title is " + show);
var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(show)+ "&api_key=9b97ec8f92587c3e9a6a21e280bceba5";
console.log(url);
$.ajax ({
url: url,
dataType: "json",
success: function (data) {
// console.log(data.results);
var htmlStr = '';
$.each(data.results, function(i, results){
htmlStr += '' + 'Add' + ' <h2 class="movie-title">' + results.original_title + '</h2>' + "Average Rating " + results.vote_average + '<br>' + '<p class="showDescription">' + results.overview + '</p>' + '<br />' + '<img src=https://image.tmdb.org/t/p/w185' + results.poster_path + '>';
});
// console.log(htmlStr);
$('#searchresults').html(htmlStr);
}
// updateCount(); - count the classes inside the "currentywatching" function
}); //close .ajax
});
$('.addCurrentlyWatching').on('click', function(e){
e.preventDefault();
var movieTitle = $('.movie-title').text();
// console.log(movieTitle);
$('.currently-watching').append('<li>' + movieTitle + '</li>');
});
<section id = "shelf1">
<h2> Currently Watching </h2>
<ul class="currently-watching"></ul>
<div class="number">
<p> You currently have <span id="count"> 0 </span> shows in this list. </p>
</div>
</section>
The solution:
$(document).on('click','.addCurrentlyWatching', function(e){
e.preventDefault();
var movieTitle = $('.movie-title').text();
// console.log(movieTitle);
$('.currently-watching').append('<li>' + movieTitle + '</li>');
});
If you are interested in a more detailed answer:
Explanation
use
$('body').on('click','.addCurrentlyWatching', function(e){
take a look at Event binding on dynamically created elements?
and in
' + 'Add' + '
if you have Add variable defined use
' + Add + '
if you not
Add
and you can use
var movieTitle = $(this).next('.movie-title').text();
instead of
var movieTitle = $('.movie-title').text();
For older versions of jQuery use $.live & $.delegate
Docs:
http://api.jquery.com/live/
http://api.jquery.com/delegate/

jQuery: Count number of child elements inside a div, update number when element added/removed

I'm adding child elements inside a div using append() and counting/adding a number to each one using ++ to +1 each time an item is added.
I want the value to automatically adjust if an item is removed, for example if I have 4 elements:
Element #1
Element #2
Element #3
Element #4
Currently if element #3 is removed the list looks like this:
Element #1
Element #2
Element #4
But I want it to look like this:
Element #1
Element #2
Element #3
Appreciate any advice on what I should use to achieve this, thanks.
Example code: https://jsfiddle.net/wepsrzkm/
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function () {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
jQuery(".remove_price_rule").click(function() {
jQuery(this).parents('.price_rule_wrapper').remove();
});
});
Decrease price_rule_count by 1 when removing.
After remove one element, alter the existing elements #number.
UPDATED: As from Arun P Johny's answer, we don't need to traverse all the left elements, only need to change those which are after the removed one's text.
The origin code will register multiple events to .remove_price_rule each time you add a item, that means if you create the element 3 times, when you remove one, the logic in the remove handler will execute 3 times, so the price_rule_count will be inconsistent to the actual counts if we use price_rule_count--, however, even if we use jQuery(".price_rule_area_1").children().length; to get real count, its stll redundant to execute the same logic many times.
So It's better to use .on's delegate form here.
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function () {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
+jQuery('.price_rule_area_1').on("click", ".remove_price_rule", function() {
// As from Arun P Johny's answer, we only need to change the text after the removed element.
$element = jQuery(this).parents('.price_rule_wrapper');
$element
.nextAll('.price_rule_wrapper')
.find('span')
.text(function(index, prevText) {
return parseInt(prevText, 10) - 1;
});
jQuery(this).parents('.price_rule_wrapper').remove();
--price_rule_count;
// This would be slower as some elements don't need to be traversed.
// jQuery('.price_rule_wrapper').each(function(idx) {
// $(this).find(".price_rule_count > span").text(idx + 1);
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
jsfiddle
Check out this fiddle, I have used CSS counters in order to automatically keep your element number:
https://jsfiddle.net/wepsrzkm/8/
.price_rule_area_1{
counter-reset: section;
}
.price_rule_area_1 .price_rule_wrapper{
counter-increment: section;
}
.price_rule_area_1 .price_rule_wrapper .price_rule_count::after{
content: "#"counter(section);
display:inline-block;
}
You can update the content of the span element inside the price_rule_wrapper element like
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function() {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
jQuery('.price_rule_area_1').on('click', ".remove_price_rule", function() {
var $wrapper = jQuery(this).closest('.price_rule_wrapper');
$wrapper.nextAll('.price_rule_wrapper').find('span').text(function(i, text) {
return text - 1
})
$wrapper.remove();
price_rule_count--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
Note: Use event delegation to handler the click event of dynamically recreated elements.
You are binding multiple event handler for each remove element
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function() {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
$('div.price_rule_area_1').on('click', '.remove_price_rule', function() {
// event handler for dynamically generated element
jQuery(this).parents('.price_rule_wrapper')
.nextAll('div')
// get all div after the removing div
.find('span')
// get number span inside it
.html(function(i, v) {
return parseInt(v) - 1;
})
// decrementing value of it
.end().end()
// get back to the removing div
.remove();
// removing the div
price_rule_count--;
// decrementing the count by 1 after removing the element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
try this mate
<html>
<body>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script>
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
jQuery('.add_price_rule').click(function () {
var price_rule_count = jQuery(".price_rule_area_1").children().length;
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span class="bull ">' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
jQuery(".remove_price_rule").click(function() {
jQuery(this).parents('.price_rule_wrapper').remove();
price_rule_count--;
alert(jQuery('.price_rule_area_1').children().length)
jQuery('.price_rule_area_1').children().eq(price_rule_count-1).find('.bull').text(price_rule_count)
});
});
</script>
</html>

Div's content editor

I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});​
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);

How to fetch the id of dynamically generated textboxes?

How is it possible to get the id of the dynamically generated textboxes using jquery?. I need to fire the TextChanged event for the corresponging textbox. There is no method reference for the textboxes in the code behind.How can i refer to any method in the codebehind on firing the event. Somebody please help. I dont know jquery much. The entire script im using is as as follows:
<script type="text/javascript">
$(init);
function init()
{
$('#test').droppable(// Div Control
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
$(function() {
$("#draggable").draggable(); //Nothing to do with this div
});
function handleDropEvent(event, ui)
{
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
function addColumn(column)
{
var iHtml;
// This code will generate a checkbox and a textbox. I need to fire the event of thus generated textboxes.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input type="text" runat="server" id="aln' + column + '"> </div>';
return iHtml;
}
</script>
There's two ways: keep the generated element, or generate an ID when you generate your new element.
a) keep the generated element
This requires that you don't use innerHTML, but create the element (with document.createElement, or with jQuery's $), and then you can use the element directly (no need to call it by ID any more). For instance, with jQuery:
var container = $('#container');
var myDiv = $('<div id="myDiv"/>');
var myCheck = $('<input type="checkbox"/>');
myDiv.append(myCheck);
container.append(myDiv);
b) generate the ID
container.innerHTML = '<div id="myDiv"><input type="checkbox" id="myCheck"/></div>';
// and after this you can get them by ID:
var myCheck = $('#myCheck');
I would just add a class to the textbox in your iHtml then use .live() event
replace your iHtml with this
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="myclass" type="text" runat="server" id="aln' + column + '"> </div>';
then add the live event
$('.myclass').live('change', function() {
alert(' Live handler called.');
});
here is a WORKING DEMO

Categories