Monday, January 9, 2012

Looping through select fields and getting the selected text using jQuery

I spent a little time wrestling with this and I thought it may come in useful to pop on to the blog. In my situation I had to loop through a number of select items as I needed to post some data. I needed to do this as I had to pass 3 sets of information from each select / drop down box. It had to be done this way because I was using the dropdown boxes for a number of different functions, some needed to pull the text and some needed to pull the value.
  • The name of the select box
  • The value of the select box
  • The text of the selected item
$('select').each(function(){
     var selected_text = $(this).children('option:selected').text();
})
Happy programming :)

Labels: , ,

Tuesday, June 22, 2010

jQuery is what JavaScript should have been - introduction and examples

jQuery is what Javascript should have been - introduction and examples
Please note this is not an extensive jQuery tutorial, it is more about how jQuery is the better option for client side browser scripting compared to javaScript and is aimed at people looking to change over from one to the other. jQuery is a framework that uses javascript to 'write less and do more'.

jQuery is what Javascript should have been. This is most definitely true, but is somewhat harsh I think. Javascript was created by Netscape as a language that allowed the programmer/developer of the website to manipulate the various elements of a web page. It was called JavaScript after Sun licenced their Java brand name to give the language a little more credibility. JavaScript allowed the creators of the website to display and showcase the content with a little more flair.

Like a lot of things on the Internet, the use of JavaScript was exploited and made web surfing painful at times. JavaScript can be used to open multiple windows at once and these 'popups', especially when a user was connected to the 'net using a dial up connection and tens of windows would open up simultaneously offering you products ranging from hair extensions to god knows what. Popups thankfully became less of a problem as browsers and firewall software improved including pop up blockers.

Another problem and some may argue a bigger problem was the way the software ran in browsers. Javascript was created by Netscape and was thus adopted by other browsers, unfortunately the language was not adopted as a standard and the browsers (namely Internet Explorer) did not all act the same when they came across JavaScript - this gave developers a huge problem. Scripts had to be tested in mutliple browsers and debugging time obviously shot through the roof.

This is where the wonder of jQuery comes rushing through. JavaScript had started to be used more and more as many online applications needed the little bit of extra functionality to deliver. jQuery took away the need for writing scripts for multiple browsers. You could in a reduced manner add in code in one line that would without jQuery library taken 10 or so line of code. It really did make it that easy.

Below are a number of examples of some of the more common tasks that you can use JavaScript for. Starting with the basic task of obtaining an element's value right through to the more advanced method of making an AJAX call. Each example will have the jQuery code followed by the JavaScript that would have been necessary without the jQuery library. jQuery also allows for developers to easily add events to elements, i.e. a mouse click. This is where we will begin as it one of the cornerstones of using jQuery and using for the coding on the web.

For the sake of this tutorial, I will be an using an element named 'myElement' - which could be anything like a paragraph, div, input. If any other elements are used or are a special, I will explain further where necessary.

You will see the $ sign a lot throughout this exercise, it basically means let jQuery handle the code.

Adding an event in jQuery:

This is how you add an event in jQuery:
$('#myElement').click(function(){
alert('Hello World');
});


Like with all jquery it works in all browsers, now lets take a look at the above in plain JavaScript, unfortunately there are a number of issues when it comes to adding event handlers - Internet Explorer. Microsoft, in their infinite wisdom decided to add their own event handling system.

Here is the the code according to w3c specification - i.e. for Firefox, Opera, Chrome using an anonymous function as the second parameter - you could as easily add a reference to another function, i.e. myFunction() instead like I have shown on the Internet Explorer example below

myElement.addEventListener('click',function(){
alert('Hello World')
},false);


The 3rd parameter given here as boolean = false refers to refers to event bubbling and that goes beyond the scope of this introduction, rest assured though, jQuery makes that easier too!

Here is the code for Internet Explorer

myElement = document.getElementById('myElement');
myElement.attachEvent('onclick',myFunction);


The problems here not only lead to writing more code to get the reference for the variable, address both w3c spec and non w3c spec browsers but you may also have to write code that detects the browser type so that your script doesn't cause errors.

Getting the value of a input form field

This includes select inputs and and select, most form values- I know, how easy...

var myVar = $('#myElement').val();

Now let's look at this in plain JavaScript to obtain a text input value:

var myVar = document.getElementById('myElement').value;

For a select dropdown menu it's even more cumbersome, not only do you have to select the element from a form, but you have to go through the array of options to find the value:

var mySelectDropDown = document.forms['myForm'].mySelect;
var selectChoice = mySelectDropDown[mySelectDropDown.selectedIndex].value;


Modifying an Element's CSS property

Let us look at this in jQuery:

$('#myElement').css('background-color','#000000');

Now let us look at this in JavaScript:

In this case we are going to change the background color of an element and set it to black(#000000). First we have to find the element using the document.getElementById() function. We then have to name the CSS property

myElement = document.getElementById(myElement')
myElement.style.backgroundColor = "#000000";


Again, how much easier is this? The added bonus is that it uses the same referencing system that you may be used to using in CSS, rather than a different reference, again saving you time and effort.
On to Ajax...

Performing jQuery Ajax calls couldn't be easier. This example uses a the .open() method, but there are a number others you may be interested in, namely $.get() and $.post(), so you may want to read up on them later. The following example takes the contents of another page and then adds the content to the element:

$('#myElement).open('myOtherPage.html);

Now let's look at that in plain JavaScript:

//first we have to create the XmlHttpRequestObject
var myAjaxObject = createXmlHttpRequestObject();
//then we create the function that triggers the event
function getContents() {
//reference the source to open
myAjaxObject.open('get', 'myOtherPage.html);
//assign the function that will handle the response
myAjaxObject.onreadystatechange = handleInformation;
//declare extra parameters, not needed when using the get method
myAjaxObject.send(null);
}
//now we have to create the function to handle the above:
function handleInformation() { //check the state of the request
if(myAjaxObject.readyState == 4 && myAjaxObject.status == 200) {
//Add the information to the myElement ID
myElement = document.getElementById('myElement');
myElement.innerHTML = myAjaxObject.responseText;
}
}

Hope this helps.

Labels: , , ,

Saturday, May 1, 2010

Becoming Mobile

It's been a while since I last added a post on to this blog, mainly because I have been very busy. I took on a full time PHP development role in September and left behind the world of search (for the time being) so that I can really push on with my career.

Anyway, down to business. I once thought that if I could master a web language then I could stick to that, work away day after day and life would be good. This was of course a feeling I had before I had actually learnt a language, before I had actually applied the skills in a real life situation. This is now such a silly notion to me now that I cannot believe that I actually thought that, but I guess that is the benefit of hindsight. This is even more astonishing when you consider what the Internet is and how the very nature of the beast requires you to be fluid, adaptive and progressive. This now brings on to my next point. Mobile Apps.

I really do not want to talk about what I am going to do with them (in this post) yet, but as I have actually bought a Mac Mini to develop iPhone Apps I am sure I am going to have some great fun in doing so (but more on this later). The main point of this post is to discuss why I made the decision to start building apps and continue on my learning spree that I have been on these last couple of years. The purchase of Mac while important, only served as a catalyst to get me thinking about this idea of linked learning (a phrase I have coined for this post) and what the effect of learning one skill helps/drives to you to learning another. If this makes no sense to you, then please let me explain:

Years ago I taught myself VBscript to run within the ASP environment. These scripts required the use of databases (new skill) which in turn required me to learn MS Access which in turn allowed me to create dynamic website. The need to learn how databases worked is the link I am referring to. The acquiring of knowledge for one subject turned into another. This is quite a short chain of events, mainly because I came to the whole ASP game quite late, .Net was coming in and I considered learning that for a while but ended up choosing PHP instead.

This is very much a stripped down version, but you will get the idea. The arrows are not literally a point from one skill to another, just merely a way of demonstrating movement. If this was to be made a graphical representation then it would be more like a flow chart and many of the skill sets would be interlinked.

PHP/MySQL Led to Programming Skills -> OOP Theory -> XML -> javaScript
MySQL -> Advanced Database SQL-> Stored Procedures
Apache (running on windows) -> Regular Expressions
javaScript -> DOM knowledge -> jQuery and other frameworks
Apache (Windows) -> Apache running on Linux
Apache (Linux) -> Linux web server setups -> Linux OS
Linux OS -> Application Languages (c++, python)

This is not an exhaustive list, I could be here forever doing that. I would also have to decide at which point does each skill set become its own subset. Also, just because one skill has fired another it doesn't mean that its parent subject has been exhausted. This is especially true with something like Linux, which is a huge topic and will take years to master. The problem with this linked learning is that fact you may spread yourself a little thin. While I can apply all the skills mentioned above I am always new things about each one. In addition, as the skills are inter-related, it generally (though not always) makes each new skill all that bit easier. For example, once I had learnt PHP, I found C++ much easier as many of the constructs are similar in nature.

Does this post apply to other areas, of course. You could apply it to just about anything, if you have a similar experience then please think back. It may help you to [re]discover skills and improve your career prospects or just help you find some direction.

So what's next on the learning radar? Well, like I mentioned at the beginning of the post it is now Apple Apps for iPod and iPhone, so please watch this space as I be reporting on this once my shiny new Mac mini arrives and I learn how to use OSX (oops another new skill), it's a good job I know how to use Linux as I hear they have many things in common ;-)

Labels: , , , , , ,

Tuesday, July 14, 2009

My PHP development Book List (Beginners)

Learning PHP and web development from scratch...

Learning a new language can be difficult, especially when you haven't got someone looking over your shoulder trying to help you. That is why we have text books and believe me, some are definitely better than others. This is not just a statement based on 1 example, there were numerous times throughout my time at university that we were given a recommended reading list and the books that were supposed to help, were in fact just being endorsed by some unscrupulous lecturer who wanted to line their pockets - though this could never be proven. If you are reading this as a student, then please before you buy a book that has been 'recommended' take a look at some reviews on web sites that are freely available, after all £30 of your loan cheque is quite sizeable. I have numerous books that were truly awful and have never seen the light of day since the 13 times I attempted to read them.

Anyway, back to the subject at hand:

Here are a list of books I would use to start learning PHP and web development from scratch. You may disagree with me and that's fine, I may open comments on this post, so please do leave me your choices. You may find that I recommend the same published on numerous occasions, I am endorsing any published over another and all recommendations are purely my opinion based on my own experiences.

1. Start at the beginning - Learn (X)HTML - I was a fresh faced first year when I started learning HTML and loved it almost immediately. I had never done any real programming at this point and found it awe inspiring that you could write something in Notepad, refresh it in a browser and there you go, rendered immediately and outputting your thoughts to the world. The book I used for this was by a lady named Elizabeth Castro called 'HTML 4 for the World Wide Web' which was published in 1999 by Peachpit Press. It has of course been updated for the modern age of W3C standards and is now called HTML, XHTML, and CSS by the same author. This is a fantastic book, moves a manageable pace and unlike then will help you learn HTML and CSS all in one go, rather than how I learnt the two technologies years ago when CSS was just a bit of an extra to be used in your HTML. Technically HTML isn't programming, you are writing Markup but it will get used to many things that as a programmer will be using later on in your career i.e. attributes, properties (in CSS) and referencing different parts of your code.

2. It's another Peachpit publication, this time from Larry Ullmang. PHP and MySQL is now in its third editon and is still going strong. I have had to buy this a couple of times (different editions) as I still use for it a little bit of reference. My first edition was worn out very quickly, constant flicking through the pages and index to find what I need took its toll and as a result my first copy is in numerous parts.

Larry is a great programmer and teacher (as I have mentioned in other posts) as he can teach without laying too much on the student. He also has another more advanced PHP book which will advance your knowledge over a number of key subjects, i.e. OOP in PHP and Ajax with PHP. I would recommend that you build a number of sites first before you tackle that book as it can be heavy going in places. The advanced book is definitely more of reference manual and can be dipped in and out of, rather than the PHP MySQL which I would recommend reading in its natural order.

3. Now that you have hopefully sites coming together. I would recommend taking a look at JavaScript. Javascript has had its ups and downs (mainly due to unscrupulous coders and hackers) but has since had a well deserved revival. I like Javascript, it adds an extra dimension to a web site and makes a site feel more like a desktop application than a website (even more so when Ajax is used). However it can be a quirky language, some of the naming and referencing conventions can be tricky, but once you get the hang of it, you will love it.

JavaScript as well as being a programming language for your browser, it also gives you access to the DOM (Document Object Model) and when you learn to manipulate it, can give you some really impressive looking results.

The reason I have added Javascript after PHP is that it looks rather similar to PHP in terms of the code and that with PHP you only have to worry about 2 or 3 real events. Page Load and then GET and POST. JavaScript has many more events and uses objects (HTML elements etc) to add to its functionality.

So the book I recommend for learning JavaScript is the JavaScript Bible (now in its 6th edition) by Danny Goodman et al. A brilliant book, set a good pace and has a massive reference section for you to look almost every property, method and attrbute in the language. It also teaches you about the DOM and how to create scripts that affect it, so is a very good all round.

There are more books that I have used but I will talk about them in my next post. These books will move in to more advanced areas including Object Oriented Programming, Ajax and a few other areas.

Labels: , , , , , , ,