Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, October 5, 2012

JavaScript code to Get/Set the Caret position from/at TextArea


<html>
<head>
<title>Get/Set Caret in Textarea Example</title>
<script>
function doGetCaretPosition (ctrl) {

var CaretPos = 0;
// IE Support
if (document.selection) {

ctrl.focus ();
var Sel = document.selection.createRange ();

Sel.moveStart ('character', -ctrl.value.length);

CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;

return (CaretPos);

}


function setCaretPosition(ctrl, pos)
{

if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}

function process()
{
var no = document.getElementById('no').value;
setCaretPosition(document.getElementById('get'),no);
}

</script>
</head>
<body>
<textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
<br>
Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
<BR>
<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
value="Get Position">
</body>
</html>

Wednesday, September 19, 2012

Sample JavaScript Code to Display/Hide the Table


<!--          Sample JavaScript program to Display/Hide Table         -->

<html>
<head>
<title>TableDisplayOnOff</title>
<script>
function load()
{
        var t = document.getElementById("tab");
        t.style.visibility="visible";
}

function load2()
{
        var t = document.getElementById("tab");
        t.style.visibility="hidden";
}
</script>
</head>
<body bgcolor=white>
<br><br><br><br><br><h3 align="center" style="font-family:arial;font-weight:BOLD;font-size:16px"> <u>Table</u></h3>
<form name ="frm">
<table id="tab" style="visibility:hidden">
<tr>
<th>RAGHUPATI</th><th></th><th>RAGHAVA</th><th></th><th>RAJA</th><th></th><th>RAM</th>
</tr>
</table>
<input type="button" name="hai" value="Display" onclick="load()">
<input type="button" name="hai" value="Hide" onclick="load2()">
</form>
</body>
</html>


---------------------------------------------------------------------------------------------------


<!--   Example:    Table Display/Hidden         -->
<html>
<head>
<title>Sample Program</title>
<script>
function load()
{
        var t = document.getElementById("tab");
        t.style.visibility="visible";
}
</script>
</head>
<body bgcolor=white>
<br><br><br><br><br><h3 align="center" style="font-family:arial;font-weight:BOLD;font-size:16px"> <u>TaskList</u></h3>
<form name ="frm">
<table id="tab" style="visibility:hidden">
<tr>
<th>name</th><th>address</th>
</tr>
</table>
<input type="button" name="hai" value="hai" onclick="load()">
</form>
</body>
</html>


Saturday, August 4, 2012

Play Audio files at background from HTML page using JavaScript

JavaScript Methods

var audioFileName = "NenuSaitam";
var audioFileExtn = ".wav";


function playSound(audioFileName) // Audio : Start Sound
{


// alert (audioFileName);
audioFileName = audioFileName + audioFileExtn;

try
{

if(document.all)
{

document.all["BGSOUND_ID"].src = audioFileName;
}
else
{

self.iplayer.location.replace("jsplayer.htm?" + audioFileName);
}
}
catch(err)
{

dispErrorMessage(err);
}
finally
{ }

} // playSound


function stopSound() // Audio : Stop Sound
{

try
{

if(document.all)
{

document.all["BGSOUND_ID"].src = "jsilence.mid";
}
else
{

self.iplayer.location.replace("jsplayer.htm?stop");
}
}
catch(err)
{

dispErrorMessage(err);
}
finally
{ }

} // stopSound


HTML Code



<BGSOUND id="BGSOUND_ID" name="BGSOUND_ID" LOOP=1 SRC="jsilence.mid"/>

<iframe id="iplayer" name="iplayer" src="jsplayer.htm" style="vertical-align:top; width:200px; height:22px; scrolling:no; border:0; frameborder:0">
Your browser does not support iFrame.
</iframe>



JavaScript File (jsplayer.htm)


<html>
<body style=margin:3px; bgcolor=#dddddd>

<noscript>
<div class="noscript" style="margin:24px;">
<img src="noscript.gif" alt="In order to access this site you need to enable JavaScript !" />
</div>
</noscript>

<script type="text/javascript" language="JavaScript">
<!--

var sUsrAgt = navigator.userAgent;
var sSearch = self.location.search;
var sNameLC = sSearch.toLowerCase().substring(1);
var nameLen = sNameLC.length;
var sType   = 'unknown';

if (sNameLC.lastIndexOf('.au') >nameLen-6) sType="audio/basic";
if (sNameLC.lastIndexOf('.ra') >nameLen-6) sType="audio/x-pn-realaudio";
if (sNameLC.lastIndexOf('.rm') >nameLen-6) sType="audio/x-pn-realaudio";
if (sNameLC.lastIndexOf('.mid')>nameLen-6) sType="audio/midi";
if (sNameLC.lastIndexOf('.mp3')>nameLen-6) sType="audio/mpeg";
if (sNameLC.lastIndexOf('.wav')>nameLen-6) sType="audio/wav";

if (sSearch.length<3) document.bgColor="white";
else if (sNameLC=='stop' ) document.writeln('<center><small>Audio stopped.</small></center>');
else if (sType=='unknown') document.writeln('<center><small>Unknown audio file type.</small></center>');
else
{ // WRITE HTML TAGS FOR AUDIO PLAYBACK

  if (sUsrAgt.indexOf('Opera')!=-1||sUsrAgt.indexOf('MSIE')!=-1)
document.writeln('<bgsound volume=-1000 LOOP=1 src="'+encodeURI(sSearch.substring(1,99))+'">');
  else document.writeln('<object width=194 height=16 data="'+encodeURI(sSearch.substring(1,99))+'" type="'+sType+'"></object>');
}

-->
</script>
</body>
</html>

Sunday, April 29, 2012

JavaScript code to send text from HTML page to MS Word


<HTML>
 <HEAD>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <SCRIPT type="text/javascript">


function trim(stringToTrim) 
{


return stringToTrim.replace(/^\s+|\s+$/g,"");
}


function SelectionToWord(theField)
{


var tempVal = eval("document." + theField);
tempVal.focus();
tempVal.select();


if(tempVal.createTextRange)
{


theRange = tempVal.createTextRange();

if(trim(theRange.text).length > 0) // If selection is not empty:
{


if(theRange.execCommand)
{


theRange.execCommand("Copy");


// window.status="Contents highlighted and copied to clipboard!";

var word = new ActiveXObject("Word.Application");   // Start MS Word instance:
word.Documents.Add(); // Create new document:
word.Selection.Paste(); // Paste clipboard contents into the document:
word.Visible = true; // Show MS Word:
}


}
else
{


alert("Please type the text and click the button.........");
}


}
else
{


alert("This feature is not available for this Browser.");
}


}
  </SCRIPT>
 </HEAD>


 <BODY>


 <form action="#" name="test2">


 <P>Please type the text and click the button.</P>


<textarea cols='60' rows='2' name='textWord2' id='textWord2' style='font-size:20; font-weight:bold' > </textarea>


<br><br><br>


 <INPUT type="button" onclick="SelectionToWord('test2.textWord2')" value="Send To MS Word"></INPUT>


 </form>


 </BODY>
</HTML>

Thursday, October 27, 2011

i18n : JSP and MySQL Internationalization


I) JSP Character Set Handling

Character handling can be split into two categories: displaying the characters and receiving the ones entered by the user.  For JSP pages, setting the encoding for each category is done separately by using different directives and/or functions.

Displaying International Characters

i. To set the character encoding for JSP page display, use the standard “page” directive with “contentType” parameter as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

Page directive is used to control the structure of a servlet or a JSP by importing classes, customizing superclasses, and setting the content type, etc.

ii. The following HTML tag can be used for the web browser to load the correct character set:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Meta tags with an http-equiv attribute are the same as HTTP headers. In general, they are used to control the action of browsers, and can be used to refine the information provided by the actual headers.

iii. Avoid using Java String functions (or constructors) such as the following to convert character encoding of a string, because it is both inefficient and unnecessary. Once you set all the options mentioned in this article correctly, you will not need to use such a conversion.

str = new String(request.getParameter("value").getBytes("ISO-8859-1"), "UTF-8");

iv. On every request, you have to set the encoding of characters manually; it is best to create a filter that can be called for every action by specifying it in web.xml:

CharacterEncodingFilter.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.FilterChain;

import java.io.IOException;

public class CharacterEncodingFilter implements Filter
{

    private FilterConfig fc;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF8");

        chain.doFilter(request, response);        //do it again, since JSPs will set it to the default

        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF8");
    }

    public void init(FilterConfig filterConfig)
    {

        this.fc = filterConfig;
    }

    public void destroy()
    {

        this.fc = null;
    }
}


web.xml


<filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>com.its.struts.action.CharacterEncodingFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <servlet-name>action</servlet-name>
</filter-mapping>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
</filter-mapping>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>*.html</url-pattern>
</filter-mapping>

ACTION class needs to be specified for the STRUTS application.
Other than STRUTS, we can specify all the servlets to handle all requests.

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/servlets/*</url-pattern>
</filter-mapping>


v. Java Mail : Finally comes the easiest part: sending e-mails with the subject and body in UTF-8.  The only things you have to do here is use MimeMessage, and give additional parameters when setting the subject and text of your message:

(…)
MimeMessage msg = new MimeMessage(session);
msg.setFrom(InternetAddress.parse(from, false)[0]);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
transport.sendMessage(msg, msg.getAllRecipients());




II) For the data entered into and received from MySQL database server, you can set the default character set and collation at five levels: (i) server, (ii) database, (iii) table, (iv) column, and (v) connection.  More information and example for each follows:

i. When you start the database server: We can add the following lines in my.ini file to initialize the settings on database startup.

default-collation=utf8
collation_server=utf8_unicode_ci
character_set_server=utf8
default-character-set=utf8


ii. When you are creating the database (or with alter statement after creation):

CREATE DATABASE db_name
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

iii. When you are creating the table (or with alter statement after creation):

CREATE TABLE tbl_name (column_list)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

iv. When you are describing the columns during table creation:

CREATE TABLE tbl_name
(
clm_name VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci
);

v. When you are creating the connection:

conn.createStatement().execute(" SET NAMES 'utf8' ");


i18n