Category Archives: javascript

Eclipse: JS validation bug – Cannot return from outside a function or method

<form:form method="POST" commandName="student" name="reg-form" onsubmit="return validateFields()">
</form:form>

Issue
Cannot return from outside a function or method.

Solution
We can just ignore it

Reference
StackOverflow

Form : Basic

student-registration.jsp


<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
	<jsp:directive.page language="java"
		contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" />
	<jsp:text>
		<![CDATA[ <?xml version="1.0" encoding="ISO-8859-1" ?> ]]>
	</jsp:text>
	<jsp:text>
		<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
	</jsp:text>
	<html xmlns="http://www.w3.org/1999/xhtml">
<SCRIPT type="text/javascript">
	function clearFields() {
		document.forms["reg-form"]["name"].value = "";
		document.forms["reg-form"]["age"].value = "";
		document.forms["reg-form"]["gender"].value = "";
		document.forms["reg-form"]["email"].value = "";
	}

	function validateForm() {
		var name = document.forms["reg-form"]["name"].value;
		if (name == null || name == "") {
			alert("Name must be filled out");
			return false;
		}
		return false;
	}
</SCRIPT>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Student Registration Form</title>
</head>
<body>
	<FORM action="student-register.do" method="post" name="reg-form"
		onsubmit="return validateForm()">
		<TABLE border="1" align="center">
			<TR>
				<TD></TD>
				<TD>${message}</TD>
			</TR>
			<TR>
				<TD>Name</TD>
				<TD><INPUT type="text" name="name" /></TD>
			</TR>
			<TR>
				<TD>Age</TD>
				<TD><INPUT type="text" name="age" /></TD>
			</TR>
			<TR>
				<TD>Gender</TD>
				<TD><INPUT type="text" name="gender" /></TD>
			</TR>
			<TR>
				<TD>Email</TD>
				<TD><INPUT type="text" name="email" /></TD>
			</TR>
			<TR>
				<TD></TD>
				<TD><INPUT type="submit" value="Submit" /> <INPUT
					type="button" value="Clear" onclick="clearFields();" /></TD>
			</TR>
		</TABLE>
	</FORM>
</body>
	</html>
</jsp:root>

StudentRegistrationController.java


package jkcs.basic;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;

import org.apache.catalina.connector.Request;

/**
 * Servlet implementation class StudentRegistrationController
 */
public class StudentRegistrationController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StudentRegistrationController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("S T U D E N T");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		String gender = request.getParameter("gender");
		String email = request.getParameter("email");

		// validation
		boolean validForm = false;
		// name
		if (checkEmpty(name) && checkEmpty(age) && checkEmpty(gender)
				&& checkEmpty(email)) {
			// further validation
			validForm = true;
		} else {
			response.getWriter().write("errors");
			validForm = false;
		}

		RequestDispatcher view = request
				.getRequestDispatcher("student-registration.jsp");
		if (validForm) {
			request.setAttribute("message", "Thank you!");
		} else {
			request.setAttribute("message",
					"Please recheck and submit");
		}

		view.forward(request, response);

	}

	public boolean checkEmpty(String data) {
		if (data.equals("") || data == null) {
			return false;
		}
		// more validation
		return true;
	}

}

Reference

Extjs : Manipulating Items in Containers

Create two Windows and add a panel.

	var panelX = {
		html : 'panelX',
		id : 'panelX',
		frame : true
	}

	var parentX = new Ext.Window({
		title : 'parentX',
		id : 'parentX',
		height : 250,
		width : 250,
		items : [panelX]
	});

	var parentY = new Ext.Window({
		title : 'parentY',
		id : 'parentY',
		height : 250,
		width : 250
	});

	parentX.show();
	parentY.show();

Remove the panel from a Window and add it to the other Window.

	var panel = Ext.getCmp('panelX');
	Ext.getCmp('parentX').remove(panel, false);
	//Ext.getCmp('parentX').doLayout();
	// panel is still there in the parentX, because we passed false to remove()
	
	Ext.getCmp('parentY').add(panel);
	// Now it is in the parentY

Complete Code

Ext.onReady(function() {

	var panelX = {
		html : 'panelX',
		id : 'panelX',
		frame : true
	}

	var parentX = new Ext.Window({
		title : 'parentX',
		id : 'parentX',
		height : 250,
		width : 250,
		items : [panelX]
	});

	var parentY = new Ext.Window({
		title : 'parentY',
		id : 'parentY',
		height : 250,
		width : 250
	});

	parentX.show();
	parentY.show();

	var panel = Ext.getCmp('panelX');
	Ext.getCmp('parentX').remove(panel, false);
	// Ext.getCmp('parentX').doLayout();
	// panel is still there in the parentX, because we passed false to remove()
	
	Ext.getCmp('parentY').add(panel);
	// Now it is in the parentY
});

Another Example

Ext.onReady(function() {

	var panelX = {
		html : 'panelX',
		id : 'panelX',
		frame : true
	}

	var button = new Ext.Button({
		text : 'Knock',
		handler : function() {
			var panel = Ext.getCmp('panelX');
			Ext.getCmp('parentX').remove(panel, false);
			Ext.getCmp('parentY').add(panel);
		}
	});

	var parentX = new Ext.Window({
		title : 'parentX',
		id : 'parentX',
		height : 250,
		width : 250,
		items : [panelX, button]
	});

	var parentY = new Ext.Window({
		title : 'parentY',
		id : 'parentY',
		height : 250,
		width : 250
	});

	parentX.show();
	parentY.show();

});
Tagged ,

Extjs : Events

Software driven events

Create an object of Observable

var myObservable = new Ext.util.Observable();

Add custom events

myObservable.addEvents('sayHello');
// or
myObservable.addEvents({
  'sayHello' : true // enabled by default
});

Register event handler

myObservable.on('sayHello', function() {
  console.log('Hello stranger');
});
// myObservable.on is the shorthand for myObservable.addListener

Fire the event

myObservable.fireEvent('sayHello');

If we want to pass parameters

myObservable.addEvents('sayHello');
var sayGoodbyeFn = function(firstName, lastName) {
console.log('Goodbye ' + firstName + ' ' + lastName + '!');
}
myObservable.on('sayGoodbye', sayGoodbyeFn);
myObservable.fireEvent('sayGoodbye', 'Holly', 'Cow');

Remove listeners

myObservable.un('sayGoodbye', sayGoodbyeFn);
// myObservable.un is the shorthand for myObservable.removeListener

Originally from [ Ext JS in Action by Jesus Garcia ]


Complete Example

Ext.onReady(function() {
	Ext.define('Test', {
		extend : 'Ext.util.Observable',
		constructor : function(config) {
			this.name = config.name;
			this.addEvents({
				'test' : true
			});
			this.listeners = config.listeners;
			this.callParent(arguments);
		}
	});

	var test = new Test({
		name : 'Test X',
		listeners : {
			test : function(param_x, param_y) {
				console.log('initiating ' + this.name + ' : ' + param_x +  ': ' + param_y);
			}
		}
	});	
	test.fireEvent('test', 'x', 'y');		
});
// http://docs.sencha.com/ext-js/4-0/#!/api/Ext.util.Observable

result : initiating Test X : x : y

For more details Extjs docs

Tagged ,

Javascript : OOP Basics

Original Source from Mozilla Developer Network

function makePerson(first, last) {
    return {
        first: first,
        last: last,
        fullName: function() {
            return this.first + ' ' + this.last;
        },
        fullNameReversed: function() {
            return this.last + ', ' + this.first;
        }
    }
}

3WT?
Everytime we create a Person it creates two brand new function objects.

function personFullName() {
	return this.first + ' ' + this.last;
}

function personFullNameReversed() {
	return this.last + ', ' + this.first;
}

function Person(first, last) {
	this.first = first;
	this.last = last;
	this.fullName = personFullName;
	this.fullNameReversed = personFullNameReversed;
}

WCWT?
Function code is shared.

function Person(first, last) {
	this.first = first;
	this.last = last;
}
Person.prototype.fullName = function() {
	return this.first + ' ' + this.last;
}
Person.prototype.personFullNameReversed = function() {
	return this.last + ', ' + this.first;
}

WCWT?
We can add extra methods to an existing object at runtime.

Example : Adding a function at runtime.

Person.prototype.firstNameCaps = function() {
    return this.first.toUpperCase()
}

Another Example : Changing prototype.toString function

Person.prototype.toString = function() {
   return '<Person: ' + this.fullName() + '>';
}
var s = new Person("Sim", "Son");

If we print s

[object Object] – Without our new toString()
<Person: Simon Willison> – With our new toString()