Top SEM and SEO Tips    

Archive for the ‘jQuery’ Category

jQuery – Add a default button to a page

Monday, December 29th, 2008

Normally in HTML you can add a ‘input type=”submit”‘ to a page and it acts as a default button. However this only works if the input tag is within a ‘form’. I was using AJAX and found that adding a form caused the AJAX to fail. Instead I ended up with the following code:

$(‘input’).keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
$(‘#btnSubmit’).click() ;
}
});

This adds to all input fields a keyup function that checks for the enter key and if found calls the click function on the button I want to use as the default button – in this case it’s an input button called ‘btnSubmit’.



jQuery Automatic Trim of Input Fields

Tuesday, December 23rd, 2008

Really common task with a really easy solution

$(function()
{
$(“input”).change( function() { $(this).attr(“value”, $.trim( $(this).attr(“value”) ) ) });
});

This attaches a function to the ‘change’ event of all <input> tags. When the input field is changed it uses the built in ‘trim()’ function of jquery to trim off whitespace.



Save HTML Table to Excel using jQuery

Friday, November 7th, 2008

After a few hours work looking into this, this turned out really easy to implement using jQuery and server side PHP programming as follows:

On the client side the following HTML code needs adding to the page:

<form action="/SaveToExcel.php" method="post" target="_blank"
onsubmit='$("#datatodisplay").val( $("<div>").
append( $("#ReportTable").eq(0).clone() ).html() )'>
<input  type="image" src="/images/icons/Floppy-48x48.png" width="12" height="12">
<input type="hidden" id="datatodisplay" name="datatodisplay" />
</form>

Note – variables used above – ReportTable is the id of the table you want to save and datatodisplay is a hidden variable used to post the table to the server.

The jQuery commands were added to the form’s onsubmit event but could easily be in your $(function(){}); fuction

The hard part here was getting all of the <table> HTML code. The standard jQuery .html() command gets the innerHTML and was cutting off the <table> HTML code. Getting all the HTML code was accomplished using the code $(“#datatodisplay”).val( $(“<div>”).append( $(“#ReportTable”).eq(0).clone() ).html() ) which effectively gets the outerHTML of the named HTML object (in this case the table we want to save to excel).

On the server side create a file called’SaveToExcel.php’ and add the following code:

<?php
header("Content-type: application/vnd.ms-excel; name='excel'");

header("Content-Disposition: filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>
<html>
<head></head>
<body><?=$_REQUEST['datatodisplay']?>
</body>
</html>