Calling a function from StringBuilder(vb.net) - javascript

How can I call a function in javascript from the stringBuilder in VB.Net?
Code:
oSB.Append("<table id= '" + table_id + "' class='sortable' ><thead><tr><th class=border onclick='sort()'>" + "Name" + "</th><th class=border>" + "Duration" + "</th><th class=border>" + "State" + "</th><th class=border>" + "Party" + "</th><th class=border>" + "Year" + "</th></tr></thead>")
Is this a correct method?

Instead of using the outdated onclick attribute, you should assign you handlers via javascript/jQuery. This makes for a better separation of concerns.
First of all remove the onclick="sort()" from your code, and add this jQuery code to the page:
$(".sortable th:first").click(function() {
// do something...
});

you can remove the inline onclick event.. and use jquery click event instead
$(".sortable th:first").click(function() {
// do your stuff
});

Related

Jquery Mobile dynamic created range change event not firing

I'm creating a Jquery Mobile range dynamic with this code:
$('<input data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Now I want to add a change event with this code:
$(".brightness").change(function() {
alert("changed");
});
I have no idea why it's not working, I tried to refresh the range after defining the event, I tried to bind the event to the range, nothing works. The function that contains the first code snippet, is getting called first, and the function that contains the second snipped is getting called second.
Does someone of you know what I'm doing wrong, or what I'm overlooking?
Two things you need to do
1. add css class brightness to your range input
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
Add event handler using on
$(document).on("change",".brightness",function() {
alert("changed");
});
EDIT - for id selector use # instead of .(dot) like below
$(document).on("change","#brightness",function() {
alert("changed");
});
Check jQuery Selector
Use on method for your dynamically created elements
$(".brightness").on('change',function() {
alert("changed");
});
I think you are giving id brightness and Calling Onchange Event by Class using dot(.).
if the name of the id is brightness then
you should use #
$("#brightness").on('change',function() {
alert("changed");
});
but if you want call onchange event by class only then you need to add class to your input and use dot(.)
$('<input class="brightness" data-type="' + elementType + '" id="' + name +' " min=' + value1 +' max=' + value2 + ' value="127" >').appendTo("fieldset");
$(".brightness").on('change',function() {
alert("changed");
});

How to pass `this` as an argument in javascript function?

I am using javascript in my project.
I have on HTML table <table id='idDocList'> and I am doing append some html on this table as below code.
But I want to hide respective <tr> when user click on Delete anchor tag.
$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a onclick=deleteDocument(this,'" + file.name + "')> Delete</a></td></tr>");
How can i do this using Jquery?
The following example does not work
function deleteDocument(CurAnchorTag, fileName) {
$(CurAnchorTag).closest('tr').hide();
}
I don't want to use ID for <a> tag as I have many Documents.
As a quick fix, you can use like this,
$(CurAnchorTag).closest('tr').hide();
Replaced <tr> with tr
You can remove the inline function call with jquery like this way,
$("#idDocList").on("click", "td a", function() {
$(this).closest("tr").hide();
var filename = $(this).closest("td").prev().text();
});
I would suggest you to change your code to:
var newRow = $("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a href='#'> Delete</a></td></tr>").appendTo("#idDocList");
newRow.find( 'a' ).click( function( e ) {
e.preventDefault();
$( this ).closest('<tr>').hide();
});
You would better use event delegation and get rid of inline onclick handlers all together:
$('#idDocList').on('click', '.btn-delete', function() {
$(this).closest('tr').hide();
// read filename: $(this).data('filename')
});
And use it with HTML (the sting you append):
"<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class="btn-delete" data-filename='" + file.name + "'>Delete</a></td></tr>"
Note the part:
<a class="btn-delete" data-filename="filename">Delete</a>
you can just use
$(".delete_link").click(function(){$(this).closest('tr').hide();}
Jquery will use the this of which ever element called it. There will be no need for the onclick on the html file.
You recommend you to use event for a class using the jquery
$("#idDocList").append("<tr><td>" + file.name + "</td><td>" + sz + "</td><td><a class='delete_link'> Delete</a></td></tr>");
The code below will add the event and need to execute always after add a "tr", unless you use a delegate to this
$(".delete_link").click(function(){ $(this).closest("tr").hide() });
If you don't want to use a class you can use this
$("#idDocList td > a").click(function(){ $(this).closest("tr").hide() });

Click function not registering correctly in Jquery

I have a function that should be triggered on click of productid...
$("[id^='productid']").click(function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
})
The products are generated using Jquery pagination as given below....
function createproducts(jsondata){
transactiondata = jsondata
$("<div id='product-container'></div>").appendTo("#product-list");
$('#pagination').pagination({
items: jsondata.length
,itemsOnPage: 12
,onInit:redrawData
,onPageClick: redrawData
,cssStyle: 'light-theme'});
}
function redrawData(pageNumber,event){
if (pageNumber) {
slicedata = transactiondata.slice(pageNumber*12,
Math.min((pageNumber+1)*12,transactiondata.length));
}
else {
slicedata = transactiondata.slice(0,12)
}
$("#product-container").empty()
slicedata.forEach(function(e,i,a){
var obj = e;
$("<div id = productid" + i + " class = product-cards </div>").appendTo('#product-container')
//-working$("<div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")'> </div>").appendTo('#product' + i);
//lightbox is the jquery plugin that we use..The below line is very sensitive...
//-lightbox working$(" <div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")' > </div>").appendTo('#product' + i);
$("<div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")'> </div>").appendTo('#productid' + i);
$("<div id = product" + i + "right class = product-cards-right> </div>").appendTo('#productid' + i )
$("<label><b> Price: <b></label> <label>" + '$' + obj.price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Old Price: <b></label> <label>" + '$' + obj.old_price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Author Name: <b></label> <label>" + obj.author_name + "</label>").appendTo('#product' + i +"right" )
$("<div id= elementid style='display:none' >"+ obj.id+" </div>").appendTo('#product' + i +"right" )
//$("<label>" + obj.name + "</label>").appendTo('#product' + i +"right" )
})
Problem:-
When I click the productid the click function is correctly working and calculates "match" correctly..But once I move to next page(Onpageclick is triggered) and click productid, the click function is not working anymore..Why would this happen?
You can use $(document) handler so that your click handler is not lost.
$(document).on("click", "[id^='productid']", function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
});
You need to use a delegated event handler like this:
$(document).on("click", "[id^='productid']", function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
});
It works by listening for events bubbled up to a non-changing ancestor element, then applying the jQuery selector on the chain of elements that caused the event, then applies the function to any matching elements that caused the event.
You would normally attached the delegated event to the nearest non-changing ancestor element, but the fallback is document if nothing is convenient to use. Do not ever use body for delegated events as it has a bug with some events (due to styling).
When you change the page you lose the hook jquery adds on the DOM which is triggering the click. Just recall the method that listens to clicks on page change.

WHy Doesnt This Javascript Function Work

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources