Add and Remove ROWS in table using JQuery

Category : JQuery/JScript

Sounds hard, but very simple.

Say I have a table on a page and a button to add rows to that table. On that button, I have added an ONCLICK to go to the function below.

Below, I gave my table a CLASS name because .Net screws up the ID — and I am able to call that when the button is clicked.
Here the .append function adds after the last element — THIS COULD BE PROBLEM FOR YOU if you have a TBODY. There are workarounds but I am not going to discuss those at this time.

function AddCustomSetting() {
    $('.cusSettingsTable').append("<tr><td onclick='RemoveRow(this);'>Remove</a></td><td><input type='textbox' /></td><td>Test Me</td><td></td></tr>");
}

That is all it would take to add a new Row to a table… now what if we want to remove it? Well notice in that append statement that I added another onclick function to remove the row and sent the TD (via this) element with the call. Here is that function:

function RemoveRow(c) {
    $(c).parent().remove();
}

And that is it! JQuery strikes again!
ciao!
t

Create Custom Object In Javascript! very cool.

Category : JQuery/JScript

You can define your own objects in Javascript that will hold properties and perform calculations.

Additionally, as if that is not cool enough (dang I love Javascript), you can also define methods/functions that are attached to those objects (see below).

AND additionally, as if THAT is still not cool enough, if you are using Visual Studio 2010 (not sure about 2008) – you will get ‘ intellisense’ for these new Javascript objects (he laughs uncontrollably from pure geek joy!)!!!

Javascript custom Intellisense

Notice ID and Name are properties and MultiplyBy1000 is my custom made method for this object.

  //Create an array to hold your objects
  var jsObjectList = new Array(); 
 
  //You can define objects in Javascript like you would any JS function
  function myJSObject(num1, num2, myName) {
 
        this.num1 = num1;
	this.num2 = num2;
	this.myName = myName;
	this.combinedNums = num1 * num2;
 
    }
 
  //You can create methods and functions (that return values) for these objects by using the PROTOTYPE keyword.
   myJSObject.prototype.MultiplyNumberBy1000 = function(numberToMultiplyBy1000)
    {
        alert (numberToMultiplyBy1000 * 1000);
 
    } 
 
  //Make one of your spiffy new objects and then add it to your array!
  function createOneOfMySpiffyNewObjectsAndAddItToMyArray() {
 
	//Instantiating new obj
	var newObject = new myJSObject( 2, 12, 'Todds');
 
	//Adding it to array
        if (jsObjectList.length == 0)
                 jsObjectList[0] = newObject;
        else
                 jsObjectList[jsObjectList.length] = newObject;
 
   }
 
  //Now you can iterate through your array and grab values from your list of objects like this!
  function iterateMyObjectArray() {
 
	for (i = 0; i &lt; jsObjectList.length; i++) {
 
            var currentNewObject = jsObjectList[i];
 
            //Now pull info from that object like this...
	    var a = currentNewObject.num1;
	    var b = currentNewObject.myName // etc, etc.
 
	    //And call methods like this
	    currentNewObject.MultiplyBy1000(4);
       }
 
  }

Add JQuery, Javascript, CSS to ASPx User Controls parent

Category : ASP.Net, C#, JQuery/JScript

This is my preferred method. (Microsoft has controls such as ScriptManager and ScriptManagerProxy but like nearly everything they do, I believe its overkill) To me, this is the simplest method.

The Problem: You want to convert or to create a user control that has scripts and/or css.

Solution: Within the Page_Load event of the user control, simply include the following:

    //For Scripts - notice we add this script call to the PARENT HEADER
    LiteralControl jQuery = new LiteralControl();
    jQuery.Text = "<script type=\"text/javascript\" src=\"js/jquery.js\"></script>";
    Page.Header.Controls.Add(jQuery);
 
    //For CSS - You could add Media under attributes as well.  
    HtmlLink stylesLink = new HtmlLink();
    stylesLink.Attributes["rel"] = "stylesheet";
    stylesLink.Attributes["type"] = "text/css";
    stylesLink.Href = "css/yourPagesCSS.css";
    Page.Header.Controls.Add(stylesLink);

Hope this helps someone! t

Get parent div ID with JQuery

Category : JQuery/JScript

$(this).parent().attr(“id”);

Send JSON via AJAX to JQuery from an aspx page.

Category : ASP.Net, JQuery/JScript

This took me many tries to get this right so I am logging this so I dont have to go through this again.

JSON (Javascript Object Notation) allows us to send data to our Javascript (JQuery) and let it read that data in very useful ways.  With JSON, we can send basic keys and values to Javascript (as I will show here) up to complete objects with parameters and functions ( just google JSON tutorials to see some amazing ways to use the data).

HERE I will show the following scenario:  using an aspx page (but it could just as easily be a simple html page) I declare the JQuery library and  using JQuery on that page  I make a call to another aspx page (so we can get to the server and do ‘thinking’ stuff) using one of JQuerys Ajax functions  (“$.post”) -  In that CALLED page I will be grabbing any sent in data (because our JQuery can send data to that page) , doing WHATEVER you want to do with the data (tap into a database, apply business rules, etc.) and then formatting whatever data you want to return in JSON format so that our JQuery can use it in a somewhat intelligent fashion.

I probably lost many of you, so let me just SHOW you and it will be much clearer.

STEP 1:  Markup – add the JQuery Library to your page, then call the $.post function (that function can take several types of configurations but the one I am using is the NAME of the page I am calling, the data I am sending to it, what to do with the Results I get back, and finally telling it that the results WILL BE IN JSON format.

<head runat="server">
    <title>JSON Test Page</title>    
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
 
    $(document).ready(function() {
        $("#jsonButt").click( function() {
                  $('#jsonReturnDiv').html( '<img src="images/loading.gif" />' );  
 
                  $.post('ajax/jsonTestPage.aspx',         
                        {'ThisIsWhereIWouldSendDataIn' : 'Data1', 'Data2Etc' : 'Data2'},  
                      //The data we return will come back as JSON
                       function(data) {                            
                           $('#firstReturnDiv').html(data.first);
                           $('#secondReturnDiv').html(data.second);
                           $('#thirdReturnDiv').html(data.third);
                           $('#jsonReturnDiv').html( '' );  
                        }, "json");
              });
 
     });  
     </script> 
</head>
<body>
    <form id="form1" runat="server">
        <div id="firstReturnDiv"> This is the first return div... check it</div>
        <hr />
        <div id="secondReturnDiv"> This is the second return div... check it</div>
        <hr /> 
        <div id="thirdReturnDiv"> This is the third return div... check it</div>       
        <hr />
        <input id="jsonButt" type="button" value="button" /> <div id="jsonReturnDiv"></div>
    </form>
</body>
</html>

If you dont understand the Document ready, butt click, and the rest then you should probably just read a couple QUICK JQuery tutorials — its very simple to pick up and very worthwhile. Basically the .click function is what Kicks the whole thing off so that when a user clicks a button on my page that I have set the ID to ‘jsonButt’. (I also kick off a lovely little whirly gig [ i love whirly gigs ] that I eventually hide after the data comes back) ….

STEP 2: Code Behind – So inside of my aspx page (the one I point to in the $.post function ( ‘ajax/jsonTestPage.aspx’, ) I remove ALL markup and only leave my top line “<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jsonTestPage.aspx.cs" Inherits="ajax.jsonTestPage" %>” . Then in code behind I can grab the data that was sent in to the page via the Query string (I dont do this here) … the format the JSON data to return BACK to the page. *** TWO THINGS MUST BE PRESENT TO MAKE THIS WORK : THE CONTENT TYPE MUST BE SET AS I HAVE HERE AND THE JSON DATA HAS TO BE SURROUNDED BY DOUBLE QUOTES

        protected void Page_Load(object sender, EventArgs e)
        {
           // Response.ClearHeaders();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //JSON MUST BE SENT BACK WITH THIS CONTENT TYPE!
            Response.ContentType = "application/json"; 
            //JSON MUST HAVE DOUBLE QOUTES!!!
            string jsonReturn = "{\"first\":\"This is the first\", \"second\":\"This is SECOND!\", \"third\" : \"This is third!\"}";
            Response.Write(jsonReturn);
        }

Now look at the jsonReturn string. We have a piece of data called ‘first’ and it’s value ‘This is the first’, etc… here is where we could make more complicated objects but we will keep it simple for now.

STEP 3 – This isnt really a step but just some explanation… The Response.Write now sends the data back to the page in JSON format. If you look again at our $.post function you will see that the return data (which we have appropriately named ‘data’) will be used here:

function(data) {
$(‘#firstReturnDiv’).html(data.first);
$(‘#secondReturnDiv’).html(data.second);
$(‘#thirdReturnDiv’).html(data.third);
$(‘#jsonReturnDiv’).html( ” );
},
Take note of how we were able to use the data simply now by calling data.first, data.second, etc… again, this is a simple (although elegant) use. This allows us to do many advanced things with our return data. We could even return an array of multiple objects and be able to use and manipulate and display them straight from Javascript.

Using this technique, one could write an elegant front end using ONLY JQuery and HTML while still being able to harness the power of IIS on the back end. Hope this helps someone! T.

Trying to get the divs within a div by class name? jquery

Category : JQuery/JScript

$('#DIVID &gt; div.CLASSNAME').each(function() {
           numOfColumns++;
                });

This asks for all divs within your holding div that have a certain class name. ** THE ‘ATGT’ after DIVID is a Greater Than sign**

How to tell if a div is visible / hidden using JQuery

Category : JQuery/JScript

You have a DIV and want to check if it is visible

Use the is() function passing “:visible” :

if( $('#myDiv').is(':visible') ) {}

Hidden

This is the same as checking if an element is visible but uses :hidden instead and the logic is the reverse:

if( $('#myDiv').is(':hidden') ) {}


Elements will return TRUE to the Hidden check even if they are not but take up no space!

Make the IS NOT check to combat this.

if( !$('#myDiv').is(':visible') {}
}

You can use the visible parameter to loop through all visible divs

$("#mydiv div:visible").each( function() {}

JQUERY Select a Hidden input within a Div

Category : JQuery/JScript

Had a div with a hidden input holding a value, wanted to get it… wanted a good way to select it… here is what I found.

$('input:hidden:first','#mydiv'); // get first one using first
$('input:hidden:last','#mydiv'); // get last one using last
$('input:hidden','#mydiv').eq(0); // get first one using eq
$('input:hidden','#mydiv').eq(1); // get second one using eq
$('input:hidden','#mydiv').eq(2); // get third one using eq
$('input:hidden:eq(0)','#mydiv'); // get first one using eq in selector

The options are:
  • first - get the first matched element in the collection.
  • last - get the last matched element in the collection.
  • eq(N) - get the Nth matched element, 0 based.
  • :eq(N) - get the Nth matched element, 0 based, inside the selector string.
However, using Hidden this way could also give you elements within your div that are NOT VISIBLE -- you could also use this;
$('input[type=hidden]', '#mydiv').eq(0);

Worked well for me, thanks StackOverflow!

Javascript Is Numeric? Use parseInt() to test!

Category : JQuery/JScript

You can use JavaScript’s built-in parseInt() function to easily test for a numeric value:

if (myTextboxValue != parseInt(myTextboxValue))
alert(myTextboxValue + ' is not a whole number');

parseFloat will also allow you to get test if the data is a number (including floats)

Testing if a Javascript function exists….

Category : JQuery/JScript

Believe it or not, you may come up against a situation where you do not whether a Javascript function exists in your page or not…. here is my scenario.

I am using usercontrols that are added to the page IF certain settings are set in the webconfig (something you might do if someone has one of your apps installed or has purchased a certain portions of your app) … so its possible this usercontrol has not been added to my page.

SO I need to know if I have a certain javascript function so that I can call it…. however if I call it or test for it WRONG I will get a Javascript error.

Here is the simple way to test this situation:

if(window.myJavascriptFunction) {
//do whatever I want to do now… like just CALL IT!
myJavascriptFunction();
}

hope this helps!
t