jQuery Getting Value and Text from Select Tag

I often forget this code so here it goes. Here’s the jQuery part:

$('#firstSelect').live('change', function(){
val = jQuery(jQuery('#firstSelect').find(":selected")).html();
alert(val);
});

while here’s the HTML part:

<select onchange="" name="attributes" id="firstSelect">
<option value="">Color/Finish</option>
<option value="4294860237">Black</option>
<option value="4294860179">Gray</option>
<option value="4294860020">Beige</option>
<option value="4294860011">Charcoal</option>
<option value="4294858068">Tan</option>
<option value="4294857128">Camel</option>
<option value="4294851209">Khaki</option>
<option value="4294851194">Medium stone</option>
<option value="4294851193">Slate gray</option>
<option value="4294851192">Dark slate</option>
<option value="4294851190">Dark khaki</option>
<option value="4294851189">Taupe and khaki</option>
<option value="4294843384">Cashmere</option>
</select>

Javascript Form Validation

Javascript part:

// FOR REGEX (REGULAR EXPRESSION)
var empty = /^\s*$/;
var email_format = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

function validateRegistration(val) {
tof = 0;
phone = 0;
// CLEAR ERROR MESSAGES
$(val + ' .error-msg').each(function() {
$(this).remove();
});
// RESET INPUT BORDERS TO GREY (OPTIONAL), IF THIS IS NOT NECESSARRY REMOVE FUNCTION CALLS FOR function changeBorder AND THE FUNCTION ITSELF
$(val + ' .required').each(function() {
newBorder = {'border-color' : '#BBBBBB'};
$(this).css(newBorder);
});

$(val + ' .required').each(function(event) {        // VALIDATE EACH INPUT
// vars
id = $(this).attr("id");
if(empty.test($(this).val())) {
tof++;
// IF EMPTY CHANGE INPUT BORDER TO RED
changeBorder($(this));
if($(this).hasClass('phoneNumber')){    // MULTIPLE INPUTS FOR ONE POST VALUE EX.: 123 - 456 - 789
phone++;
if(phone == 1){
displayError($(this));
}
}
else{
displayError($(this));
}
}
else{
// HAS VALUE BUT MUST BE CHECKED IF VALID INPUT
if($(this).hasClass('phoneNumber')){
if(isNaN($(this).val())){
tof++;
phone++;
if(phone == 1){
changeBorder($(this));
displayError($(this));
}
}
}
else if($(this).hasClass('zipCode')){

// CHECK IF INPUT IS DIGIT, NO OTHER CHARACTERS ALLOWED
if(isNaN($(this).val())){
tof++;
changeBorder($(this));
displayError($(this));
}
}
else if($(this).hasClass('email')){

// CHECK IF VALID EMAIL
if(!email_format.test($(this).val())){
tof++;
changeBorder($(this));
displayError($(this));
}
}
}

});
// RETURN T OR F VALUE
if(tof){

// FORM HAS INVALID INPUTS THEREFORE DATA WILL NOT BE POSTED
return false;
}
else{
return true;
}
}
// CHANGE COLOR OF BORDER TO RED IF INPUT IS INCORRECT OR BLANK
function changeBorder(val){
newBorder = {'border-color' : '#B01B00'};
$(val).css(newBorder);
}

function displayError(val){
err = $(val).attr("title");
$(val).closest('div').append('<p>' + err + '</p>');
}

// ONLY DIGITS ARE ALLOWED TO BE ENTERED, ELSE WILL NOT BE DISPLAYED
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if(window.event)
key = window.event.keyCode;
else if(e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}

the “numbersonly” function above came from this site.

HTML Part (Form)


<form id="formOne" onsubmit="return validateRegistration('#formOne');" method="post" action="/">
<div><input type="text" name="customer_last_name" id="customer_last_name" title="Please supply valid last name"></div>
<div>
<select id="customer_country" name="customer_country" title="Please select country">
<option value="">Select Country</option>
<option value="US">United States</option>
<option value="CA">Canada</option>
</select>
</div>
<div>
<input type="text" id="customer_phone_parts_1" name="customer_phone_parts[one]"onKeyPress="return numbersonly(this, event)" title="Please supply valid phone number" onKeyPress="return numbersonly(this, event)">
<input type="text" id="customer_phone_parts_2" name="customer_phone_parts[two]"onKeyPress="return numbersonly(this, event)" title="Please supply valid phone number" onKeyPress="return numbersonly(this, event)">
</div>
</form>

Implementation of CRUD

Implementation of four basic functions of persistent storage which is Create, Read, Update and Delete. I’ll be using a database named “wild” with a single table named “entry” having 3 columns named “id”,”title” and “content”. Shown below is the configuration.php wherein settings for database connection is established.

<?php
// FILENAME: configuration.php
$db_username="root";
$db_password="";
$db_hostname="localhost";
$db_name="wild"; /**************** Name of Database *************/
$dbconnection=mysql_connect($db_hostname,$db_username,$db_password) or die("Cannot connect to localhost.");
$dbselect=mysql_select_db($db_name,$dbconnection) or die ("Cannot connect to database.");
?>

this is the insertion part for the database. it was named as backend.php but it must be insert.php

Below is the snippet for HTML where users can enter the data they wish to be saved in the database. It is also called a “form”. Let’s name the file insert.php

<?php // FILENAME: insert.php ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="db-insert.php" method="post">
Title<br /><input type="text" name="title" id="title" /><br />
Content<br />
<textarea rows="15" cols="30" id="content" name="content">
</textarea>
<br /><input type="submit" value="Submit" />
</form>
<a href="view.php" style="text-decoration:none"><button>Cancel</button></a>
</body>
</html>

Once submit button is clicked on the insert.php, it will be redirected to db-insert.php

<?php
// FILENAME: db-insert.php

include('configuration.php');
$title=$_POST['title'];
$content=$_POST['content'];

$position=14; // Define how many character you want to display.
$post = substr($content, 0, $position);

// DISPLAY THE DATA TO BE SAVED, FOR SECURITY
echo $post;
echo "...";


// SQL QUERY PHRASE
$sql="insert into entry (title, content) values ('$title', '$content')";

// EXECUTE SQL QUERY ONCE CONNECTED TO DATABASE
// IF CANNOT CONNECT TO DATABASE OR SQL QUERY IS INCORRECT DISPLAY "Cannot perform query"
$sql2=mysql_query($sql,$dbconnection) or die ("Cannot perform query.");


// IF NO ERROR OCCURS
echo "<p>Successfully inserted item!</p>";
?>
<html>
<body>
<a href="view.php" style="text-decoration:none"><button>Back</button></a>
<a href="backend.php" style="text-decoration:none"><button>Add New</button></a>
</body>


</html>

The script below displays all the data inserted or saved in the database

<?php
// FILENAME: view.php


include('configuration.php');
$sql_query1="select * from entry";
$sql_query2=mysql_query($sql_query1,$dbconnection) or die ("Cannot perform query." );
$row="";


echo "<table border=\"1\" cellpadding=\"5\">";
while($row=mysql_fetch_array($sql_query2)){
$id1=$row['id'];
echo "<tr>";
/*************** (array) id is the unique id of entries in database */
/*************** where xx is the values to be passed on the edit or delete page */
$id="<td>".$row['id']."</td><td>".$row['title']."</td><td><a href=\"edit.php?xx=$id1\">Edit</a></td>"."</td><td><a href=\"delete.php?xx=$id1\">Delete</a></td>";
echo $id;
echo "</tr>";
}
echo "</table>";
?>
<html>
<body>
<a href="backend.php" style="text-decoration:none"><button>Add New</button></a>
</body>
</html>

edit.php allows user to edited selected data from the view.php
<?php
// FILENAME: edit.php


include('configuration.php');


$xx=$_GET['xx'];
echo $xx;


$sql_query1="select * from entry where id=$xx";
$sql_query2=mysql_query($sql_query1,$dbconnection) or die ('Cannot edit entry.');


while($row=mysql_fetch_array($sql_query2)){
$title=$row['title'];
$content=$row['content'];
}?>


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Page</title>
</head>
<body>
<?php
echo "<form action=\"update.php?aa=$xx\" method=\"post\">";
?>
Title<br /><input type="text" name="title" id="title" value="<?php echo $title; ?>"/><br />
Content<br />
<textarea rows="15" cols="30" id="content" name="content">
<?php echo $content; ?>
</textarea>
<br />
<input type="submit" value="Submit" />
<a href="view.php" style="text-decoration:none"><button>Back</button></a>
</form>
</body>
</html>

After clicking the Update button in edit.php,the page will be redirected to update.php

<?php
// FILENAME: update.php


include('configuration.php');


$aa=$_GET['aa'];
$title=$_POST['title'];
$content=$_POST['content'];


$sql_query1="update entry set title='$title', content='$content' where id='$aa'";
$sql_query2=mysql_query($sql_query1,$dbconnection) or die ('Cannot update entry');


echo "Successfully updated entry.<br>";
echo "<a href=\"view.php\">Back</a>";
?>

delete.php allows selected data from view.php to be deleted

<?php
// FILENAME: delete.php


include('configuration.php');


$xx=$_GET['xx'];


$sql_query1="delete from entry where id=$xx";
$sql_query2=mysql_query($sql_query1,$dbconnection) or die ('Cannot delete item.');


echo "Successfuly deleted item.<br> <a href=\"view.php\">Back</a>"


?>

HTML Special Characters

left single quote &lsquo;
right single quote &rsquo;
single low-9 quote &sbquo;
left double quote &ldquo;
right double quote &rdquo;
double low-9 quote &bdquo;
dagger &dagger;
double dagger &Dagger;
per mill sign &permil;
single left-pointing angle quote &lsaquo;
single right-pointing angle quote &rsaquo;
black spade suit &spades;
black club suit &clubs;
black heart suit &hearts;
black diamond suit &diams;
overline, = spacing overscore &oline;
leftward arrow &larr;
upward arrow &uarr;
rightward arrow &rarr;
downward arrow &darr;
trademark sign &trade;
unused &#00;-
&#08;
horizontal tab
line feed
unused &#11;
space
exclamation mark ! !
double quotation mark &quot;
number sign # #
dollar sign $ $
percent sign % %
ampersand & &amp; &
apostrophe
left parenthesis ( (
right parenthesis ) )
asterisk * *
plus sign + +
comma , ,
hyphen
period . .
slash / &frasl; /
digits 0-9 0-
9
colon : :
semicolon ; ;
less-than sign < &lt; <
equals sign = =
greater-than sign > &gt; >
question mark ? ?
at sign @ @
uppercase letters A-Z A-
Z
left square bracket [ [
backslash \ \
right square bracket ] ]
caret ^ ^
horizontal bar (underscore) _ _
grave accent ` `
lowercase letters a-z a-
z
left curly brace { {
vertical bar | |
right curly brace } }
tilde ~ ~
unused -
en dash &ndash;
em dash &mdash;
unused ˜-
Ÿ
nonbreaking space &nbsp;  
inverted exclamation ¡ &iexcl; ¡
cent sign ¢ &cent; ¢
pound sterling £ &pound; £
general currency sign ¤ &curren; ¤
yen sign ¥ &yen; ¥
broken vertical bar ¦ &brvbar; or &brkbar; ¦
section sign § &sect; §
umlaut ¨ &uml; or &die; ¨
copyright © &copy; ©
feminine ordinal ª &ordf; ª
left angle quote « &laquo; «
not sign ¬ &not; ¬
soft hyphen ­ &shy; ­
registered trademark ® &reg; ®
macron accent ¯ &macr; or &hibar; ¯
degree sign ° &deg; °
plus or minus ± &plusmn; ±
superscript two ² &sup2; ²
superscript three ³ &sup3; ³
acute accent ´ &acute; ´
micro sign µ &micro; µ
paragraph sign &para;
middle dot · &middot; ·
cedilla ¸ &cedil; ¸
superscript one ¹ &sup1; ¹
masculine ordinal º &ordm; º
right angle quote » &raquo; »
one-fourth ¼ &frac14; ¼
one-half ½ &frac12; ½
three-fourths ¾ &frac34; ¾
inverted question mark ¿ &iquest; ¿
uppercase A, grave accent À &Agrave; À
uppercase A, acute accent Á &Aacute; Á
uppercase A, circumflex accent  &Acirc; Â
uppercase A, tilde à &Atilde; Ã
uppercase A, umlaut Ä &Auml; Ä
uppercase A, ring Å &Aring; Å
uppercase AE Æ &AElig; Æ
uppercase C, cedilla Ç &Ccedil; Ç
uppercase E, grave accent È &Egrave; È
uppercase E, acute accent É &Eacute; É
uppercase E, circumflex accent Ê &Ecirc; Ê
uppercase E, umlaut Ë &Euml; Ë
uppercase I, grave accent Ì &Igrave; Ì
uppercase I, acute accent Í &Iacute; Í
uppercase I, circumflex accent Î &Icirc; Î
uppercase I, umlaut Ï &Iuml; Ï
uppercase Eth, Icelandic Ð &ETH; Ð
uppercase N, tilde Ñ &Ntilde; Ñ
uppercase O, grave accent Ò &Ograve; Ò
uppercase O, acute accent Ó &Oacute; Ó
uppercase O, circumflex accent Ô &Ocirc; Ô
uppercase O, tilde Õ &Otilde; Õ
uppercase O, umlaut Ö &Ouml; Ö
multiplication sign × &times; ×
uppercase O, slash Ø &Oslash; Ø
uppercase U, grave accent Ù &Ugrave; Ù
uppercase U, acute accent Ú &Uacute; Ú
uppercase U, circumflex accent Û &Ucirc; Û
uppercase U, umlaut Ü &Uuml; Ü
uppercase Y, acute accent Ý &Yacute; Ý
uppercase THORN, Icelandic Þ &THORN; Þ
lowercase sharps, German ß &szlig; ß
lowercase a, grave accent à &agrave; à
lowercase a, acute accent á &aacute; á
lowercase a, circumflex accent â &acirc; â
lowercase a, tilde ã &atilde; ã
lowercase a, umlaut ä &auml; ä
lowercase a, ring å &aring; å
lowercase ae æ &aelig; æ
lowercase c, cedilla ç &ccedil; ç
lowercase e, grave accent è &egrave; è
lowercase e, acute accent é &eacute; é
lowercase e, circumflex accent ê &ecirc; ê
lowercase e, umlaut ë &euml; ë
lowercase i, grave accent ì &igrave; ì
lowercase i, acute accent í &iacute; í
lowercase i, circumflex accent î &icirc; î
lowercase i, umlaut ï &iuml; ï
lowercase eth, Icelandic ð &eth; ð
lowercase n, tilde ñ &ntilde; ñ
lowercase o, grave accent ò &ograve; ò
lowercase o, acute accent ó &oacute; ó
lowercase o, circumflex accent ô &ocirc; ô
lowercase o, tilde õ &otilde; õ
lowercase o, umlaut ö &ouml; ö
division sign ÷ &divide; ÷
lowercase o, slash ø &oslash; ø
lowercase u, grave accent ù &ugrave; ù
lowercase u, acute accent ú &uacute; ú
lowercase u, circumflex accent û &ucirc; û
lowercase u, umlaut ü &uuml; ü
lowercase y, acute accent ý &yacute; ý
lowercase thorn, Icelandic þ &thorn; þ
lowercase y, umlaut ÿ &yuml; ÿ
Alpha &Alpha; Α
alpha &alpha; α
Beta &Beta; Β
beta &beta; β
Gamma &Gamma; Γ
gamma &gamma; γ
Delta &Delta; Δ
delta &delta; δ
Epsilon &Epsilon; Ε
epsilon &epsilon; ε
Zeta &Zeta; Ζ
zeta &zeta; ζ
Eta &Eta; Η
eta &eta; η
Theta &Theta; Θ
theta &theta; θ
Iota &Iota; Ι
iota &iota; ι
Kappa &Kappa; Κ
kappa &kappa; κ
Lambda &Lambda; Λ
lambda &lambda; λ
Mu &Mu; Μ
mu &mu; μ
Nu &Nu; Ν
nu &nu; ν
Xi &Xi; Ξ
xi &xi; ξ
Omicron &Omicron; Ο
omicron &omicron; ο
Pi &Pi; Π
pi &pi; π
Rho &Rho; Ρ
rho &rho; ρ
Sigma &Sigma; Σ
sigma &sigma; σ
Tau &Tau; Τ
tau &tau; τ
Upsilon &Upsilon; Υ
upsilon &upsilon; υ
Phi &Phi; Φ
phi &phi; φ
Chi &Chi; Χ
chi &chi; χ
Psi &Psi; Ψ
psi &psi; ψ
Omega &Omega; Ω
omega &omega; ω
password dot
bullet

WordPress Content Teaser with Thumbnail

Here’s the source link. Click Here

I want to make 4 preview post in the homepage of my website just like in YAHOO. Teasers to be exact.

The first thing i did was get the x number of character from the post and show it where it should be. So i use the function “substr” in php.

$content=get_the_content();    // get the whole content of the post
$content2=substr(strip_tags($content), 0, 100);  //rip of x number of characters from the $content
echo $content2;  //print it.

Then i integrated it with the code showed in the link above. After that, I went to the wp-include folder and looked for the function.php and inserted this chunk of code.
// Retrieve the src of first image in a post
function bm_extract_string($start, $end, $original) {
$original = stristr($original, $start);
$trimmed = stristr($original, $end);
return substr($original, strlen($start), -strlen($trimmed));
}
function getFirstImage() {
$content = get_the_content();
$pic_string = bm_extract_string('src="','" ',$content);
$imagesize = getimagesize($pic_string);
list($width, $height, $type, $attr) = getimagesize($pic_string);
$link = get_permalink();
$title = get_the_title($post->post_title);
echo '<a
href="'.$link.'" style="background:url('.$pic_string.'); display:block;
width:'.$width.'px; height:'.$height.'px;" title="'.$title.'"></a>';
}

If the post doesn’t have an image it will print error notice that’s why i inserted conditional codes that will check if the post has an image in it or doesn’t have.

// Retrieve the src of first image in a post
function bm_extract_string($start, $end, $original) {
$original = stristr($original, $start);
$trimmed = stristr($original, $end);
return substr($original, strlen($start), -strlen($trimmed));
}
function getFirstImage() {
$content = get_the_content();
if(bm_extract_string('src="','" ',$content)) // this is the conditional statement i've inserted
{
$pic_string = bm_extract_string('src="','" ',$content);
$imagesize = getimagesize($pic_string);
list($width, $height, $type, $attr) = getimagesize($pic_string);
$link = get_permalink();
$title = get_the_title($post->post_title);
//echo '<a href="'.$link.'" style="background:url('.$pic_string.'); display:block; width:'.$width.'px; height:'.$height.'px;" title="'.$title.'"></a>';
echo '<img src="'.$pic_string.'" height="100" align="left" style="margin-right:5px;">';
}
else
{
// this returns nothing if post doesnt have an image
return 0;
}
}

NOTE (code above): do not put this code outside the tag or else it will send a warning that has says like “Header already sent”. Place the code inside the same tag.

Back to the index.php part, i want the number of teasers be limited to 4 latest posts. so i used a $ctr variable counter and initialized it to 4. After that i used the while process that is being taught in WordPress Codex for posts.

Finally, put the following snippets in index.php (template folder) where the four teasers must appear.


<div>
<?php query_posts('category_name=teaser'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
if($ctr <= 4) // checks if there are already four posts listed in the index page, if not, proceed
{
?>
<div>
<p style="margin-left:auto; margin-right:auto; color:#c00000; margin-top:10px; margin-right:5px;">
<?php getFirstImage(); ?>
<?php $link=get_permalink();
echo '<span style="font-weight:bold; font-size:16px; margin-bottom:15px"><a href="'.$link.'">';
?>
<?php the_title(); ?></a></span>


<br />


<?php
$content=get_the_content();
//$content2=substr($content,0,100);
$content2=substr(strip_tags($content), 0, 100);
echo $content2;
$link=get_permalink();
echo "...";
echo '<br><a href="'.$link.'">Read More >></a>';
//echo strip_tags($content);
$ctr++;
}
else //if the $ctr reaches value four, the loop stops or breaks
{
break;
}
?>
</p>

Or you can set the number of posts that can be displayed in the index file via the Dashboard. Go to Settings > Reading then find the “Blog pages show at most” and set it to 4 or whatever number of posts you like.