Posts Tagged ‘jQuery’

Clear Default Input Box Text on Click with jQuery

Sunday, February 21st, 2010 by Phillip Napieralski

Check out the demo

You know those search boxes that say “search here” and you go to click them and the text goes away? It’s a nice little feature and is really simple with jQuery.

Here is the simple script to take you through the ages:

The HTML

	<form>
		<input type="text" name="search" id="search_box" value="search here!" />
		<input type="submit" value="Search" />
	</form>

Here we simply create a form with a textbox with an id of “search_box”. This id will help us reference it later with jQuery. ALSO take note that the value attribute is set to search here!.

The jQuery

Now simply place the following in your <head> tags and call it good.

<script type="text/javascript">
  // Some simple jQuery to remove the default search value when the user clicks the box
  $(document).ready(function() {
	  	$search_box = $("#search_box");

	  	// If the user clicks the input box and the text is "search here!",
	  	//    set it to blank
		$search_box.click(function() {
			if( $search_box.attr("value") == "search here!" ) {

				// Set it to an empty string
				$search_box.attr("value", "");
			}
		});
  });
</script>

That’s it! Basically, we find the search box by its id with $(“#search_box”) and then clear its value attribute if the string we compared to is the default search string

Clickable Table Rows with jQuery

Wednesday, January 27th, 2010 by Phillip Napieralski

Check out the demo here!

This tutorial hints at a project I’m working on. A deck building application for the Magic: The Gathering card game.

Highlighting Rows

In jQuery Selectors 2, I talked about how to highlight certain rows in a table. We can build off this to begin a full sized app (at least the frontend) with jQuery.

To recap briefly, we allow rows be clickable by using the following code:

$(document).ready(function() {
	$("tr").click(function(){
		// store our selection of the row that was clicked
		row = $(this);

		// toggle the "selected" class for the clicked row
		row.toggleClass("selected");
	});
});

Note first that the code is inside the $(document).ready(…) function. This will be the case for the code in the rest of this post.

Show Card Selections

How do we know what the user selected? Well, we can accomplish that task with the following code:

	// check for a button click
	$("#show_button").click(function(){
		var cards = "";
		
		// search through each row that has the "selected" class
		$("tr.selected").each(function() {
			// append the card name (which is between <th> tags) to our cards variable
			cards += $(this).find("th").html();
			cards += "\n";
		});

		// Simply alert the user what they selected for now
		alert("You selected:\n"+cards);
	});

There you have it. The next step is to replace the alert(“”) piece with a $.post(…) request to a php script with the selected cards.

Next Time

Lost on this tutorial? Try part 2

jQuery Selectors 2

Tuesday, January 26th, 2010 by Phillip Napieralski

Check out the demo

In this tutorial, we’ll be getting just a little bit more advanced with the selectors.

Children AND highlighting rows

: odd, :first, :last

If we are displaying a large amount of data in a table, we can easily increase the readability by highlighting every other row. Let’s look at this simple table:

<table id="demo" border="1">
	<tr>
		<th>Llanowar Augur</th>
		<td>Creature - Elf Shaman, Sacrifice Llanowar Augur: Target creature gets +3/+3 and gains trample until end of turn.</td>
	</tr>
	<tr>
		<th>Llanowar Behemoth</th>
		<td>Creature - Elemental, Tap an untapped creature you control: Llanowar Behemoth gets +1/+1 until end of turn.</td>
	</tr>
	...
</table>

We can highlight every other row of this table by adding the following code inside the $(document).ready(function(){…}) area.

$("#demo tr:odd").addClass("highlight");

What does this do? It first finds the id #demo, then it finds all the odd numbered table rows (<tr>). The .addClass(…) method refers to a CSS class highlight. We could easily define this with something like the following between <style> tags:

.highlight { background-color: lightgrey; }

With that same table, we could change our jQuery from $(“#demo tr:odd”) to $(“#demo tr:first”) and similarly with :last to grab the first and the last rows in the table

:first-child, :last-child, (>)

Now, what if we had nested HTML tags and wanted to highlight only certain tags inside the initial tag. Consider the following HTML:

<div id="demo" style="border:1px solid black">
	<p>
		This is inside a <em>p</em> and also a PARENT of the #demo div
	</p>
	<p>
		This is also inside a <em>p</em>, but it's not the first-child!
	</p>
	<p>
		Okay... this is another <em>p</em> inside #demo
	</p>
	<p>
		This is the last child of the #demo div.
	</p>
	This is NOT inside it's own <em>p</em>, so it does not count as a child!
</div>

Now, if we wanted to highlight the first and last p tags inside the #demo DIV, we execute the following jQuery:

$("#demo p:first-child").addClass("highlight");
$("#demo p:last-child").addClass("highlight");

More interestingly, we can choose to highlight every child with the following code:

$("div#demo &gt; p").addClass("highlight");

Next Time

Lost? Try part 1.

Make use of these selectors in part 3.

jQuery Selectors 1

Tuesday, January 26th, 2010 by Phillip Napieralski

Check out the demo (it’s very simple)

I realized my previous post about a Happy Polack feature might be completely confusing if you don’t know the following:

  • jQuery
  • PHP
  • My database structure

I’m going to remedy this by having a multi part series about jQuery (followed by PHP and mySQL).

Introduction

For part 1 of the tutorial, I will be focusing on a few simple examples so that you can get a hold of the various “selectors” in jQuery. But first… let’s get jQuery setup.

Adding jQuery to Your Page

Simply add the following code between the <head> tags on your webpage (for later releases, change the 1.4 to the current release):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

I should note that it is a VERY good idea to link directly to google’s repository instead of hosting the jQuery framework on your server. I have excellent reasons for this (ask me).

ID This, CLASS That

The most common thing I use jQuery for is to find a certain object ID or CLASS on the webpage. Let’s write some simple HTML that we will modify easily with javascript.

<div id="some_picture">
     <img src="http://pnapieralski.com/images/me.jpg" />
      This is a sweet picture isn't it!?
</div>
<button id="some_button">That pic is wack</button>

I simply created a div with a picture and some text in it. I gave it the id of some_picture that we will reference later. I also created a button with an id of “some_button”.

Now we want to add some functionality. Let’s make it so that when we press the That pic is wack button, the image disappears. Simple enough, here’s the code (add it between the <head> tags):

<script type="text/javascript">	
$(document).ready(function(){
     $("#some_button").click(function(){
          $("#some_picture").toggle("slow");
     })
});
</script>

Okay, let me explain. The $(document).ready(…) function tells us to execute the function in its parameter list after the webpage is done loading. NOTE: This piece is essential since the #some_button and #some_picture stuff is not loaded before this script since we put it in the <head> tags.

The $(“#some_button”) piece of code is selecting the button based on its id, which we assigned earlier. Then, we use the built-in jQuery function .click(…), which will execute the function supplied to it’s parameter list. Inside the function(){…} code, I placed code to toggle whether or not the div containing the picture is visible. Simply put, select the div with $(“#some_id”) and then call the toggle() function. Easy as that!

Now, suppose instead of an id, we had assigned the items a class instead. We can use jQuery to select it by doing $(“.some_pictures”).

Next Time

Make sure to check out part 2.

Inline AJAX Editing

Saturday, January 23rd, 2010 by Phillip Napieralski

Happypolack.com is a joke site I created as a side project a little bit ago and it’s continually being enhanced. The latest feature I added was a way for admins to edit any joke (eg, fix typos), quickly and easily.

An Example

This weirdo typed “Your Mommy” instead of “Yo Mama.” How distracting! Let’s write some code so we can fix this.

If we click the edit link corresponding to the joke, we get something that looks like the following:

Great! We edited it, now we simply click submit and we can go on with reading jokes and being merry!

How it works

When the edit link is clicked, some simple javascript is called. Here is the PHP code for the edit hyperlink for any joke.

echo "<a id="joke&quot;.$joke_id.&quot;" href="javascript:edit_joke(&quot;.$joke_id.&quot;);">;edit</a>";

We start by assigning each link with a distinct ID (corresponding to the joke’s ID in the database) and, upon clicking, it calls the javascript function edit_joke.

The Javascript/jQuery Part

Inside the edit_joke function, I used jQuery selectors to find the link and text for the joke. I then used the wrapInner() method to place an editable <div> inside our joke text’s <p> tags (basically, we now have <p id=”123″><div>Your mommy joke hehe haha</div></p> instead of <p id=”joke123″>Your mommy joke hehe haha</p>). After that, change the edit link to submit/cancel using jQuery. Clicking submit will call the javascript function edit_joke_submit(..) and clicking cancel will call the javascript function edit_joke_cancel(..). I placed those links inside a <span> tag so I could easily reference them later. The magic in this code is the contenteditable=’true’ part of the div. Here’s the code:

function edit_joke(joke_id){
	this_link = $("a#joke"+joke_id);
	this_joke = $("p#joke"+joke_id);

	this_joke.wrapInner("<div contenteditable='true' class='editable_div'></div>");

	this_link.replaceWith("<span id='submitcancel'>"+
		"<a id='joke"+joke_id+"' href='javascript:edit_joke_submit("+joke_id+");'>submit</a>"+
		"<a id='joke"+joke_id+"' href='javascript:edit_joke_cancel("+joke_id+");'>/cancel</a>" );
}

The edit_joke_cancel function is relatively simple. I first found the corresponding submit/cancel link and the joke div using jQuery selectors. After that, I used the html() method to grab the new text that was typed in. I set the text inside the <p> tags equal to the new text so that it would look like <p id=”123″>Yo mama joke hehe haha<div>Yo mama joke hehe haha</div></p> instead of <p id=”joke123″>Yo mama joke hehe haha</p>. Then, simply remove the <div> tags (and, consequently, the text inside), and it’s back to normal.

function edit_joke_cancel(joke_id){
	this_link = $("span#submitcancel");
	this_joke = $("p#joke"+joke_id);
	this_joke_div = this_joke.find("div");

	joke_text = this_joke_div.html();
	this_joke.html(joke_text);
	this_joke_div.remove();

	this_link.replaceWith(
			"<a id='joke"+joke_id+"' href='javascript:edit_joke("+joke_id+");'>edit</a>"
		);
}

To submit the joke changes, we need only send a post request to a server side php script with the joke id and the new joke text. Here’s the code:

function edit_joke_submit(joke_id){
	var this_joke = $("p#joke"+joke_id);
	var joke_text = this_joke.find("div").html();

	$.post('/jokes/ajax-edit.php',
			{
				id: joke_id,
				text: joke_text
			},
			function(data){
				alert(data);
			}
		);

	edit_joke_cancel(joke_id); // remove edible div
}

The PHP Part

All we have to do now is send an update query to the database with the corresponding id and text. The only caveat: editable divs place <br>’s when you hit enter, so I added the str_replace(..) to turn those into newline characters capable of storage in the database. Check it out:

// Include needed files for account verification here.
// Get your database connection and store it in $dbconn HERE. I use mySQLi in my code.
<?php
if( $accounts->check_admin() )
{
	$id = $dbconn->escape_string($_POST['id']);    // Prevent sql injection
	$text = $dbconn->escape_string($_POST['text']);

	$text = str_replace("<br>","\r\n", $text);    // Swap's out <br>'s

	$query = "UPDATE joke_table SET text='".$text."' WHERE id = ".$id;
	$dbconn->query($query) or die(mysqli_error($dbconn));
	echo "The joke has been edited :)";
}
else
{
	echo 'Yea... okay buddy -_-';
}
?>