Archive
6 jQuery snippets you can use to manipulate select inputs
When it comes to manipulating the DOM, fewer elements are more tiresome than the good old select input. Fortunately for us, jQuery makes what was once a headache, a walk in the park.
Listed below are 6 snippets which should make manipulating those selects more pleasant than say, pulling your own teeth.
1. Getting the value of a selected option.
$('#selectList').val();
This couldn’t be simpler. Remember how before jQuery, you had to use selectedIndex and all those lovely javascript methods. I do, and I don’t miss it one bit.
2. Getting the text of a selected option.
$('#selectList :selected').text();
Similar in concept to the first snippet with one difference. Where the first example gives you the “value” of the selected option, this example gives you the actual text contained inside the option tag.
3. Getting the text/value of multiple selected options.
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
// to get the selected values, just use .val() - this returns a string or array
foo = $('#multiple :selected').val();
Once again, the same concept as the first two examples, except we’re now using jQuery’s “each()” method to loop through all selected options in a multiple select list. Each value or text value is read into an array for later use.
4. Using selected options in conditional statements
switch ($('#selectList :selected').text()) {
case 'First Option':
//do something
break;
case 'Something Else':
// do something else
break;
}
Much like example 2, we’re getting the text() value of a selected option, only this time we’re going to use it inside a switch statement.
5. Removing an option.
$("#selectList option[value='2']").remove();
Using an attribute filter, we can find and therefore manipulate specific options within a select list. In this example we’re telling jQuery to find the option with value=”2″ and then remove it from the select list. We can similarly add options to a select list as we’ll see in example 6.
6. Moving options from list A to list B.
$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
});
Originally posted by Jeremy Martin, here we have 2 select lists and 2 buttons. If you click the “add” button, we remove the selected option from select1 and add that same option to select2. The “remove” button just does things the opposite way around. Thanks to jQuery’s chaining capabilities, what was once a rather tricky undertaking with JS can now be done in 6 lines of code.
And there you go. That wasn’t so bad now was it ? If you have any other handy snippets, or you’ve found an easier way to do something already covered here, why not leave a comment and share the love!
Update:
Incidentally, a few hours after first publishing this post I came across the following “select element cheat sheet”. Technically speaking, it may be a little big to be called a cheat sheet, but the author has given a very thorough and practical guide which I’m definitely going to be making use of.
Writing dynamic classes with PHP
I recently had the necessity to write a dynamic class (i.e. where methods, or properties of the class are determined during runtime) and in doing some research, stumbled on to this very helpful article :
The author (Jack Herrington) goes to a lot of trouble explaining how the magic __get(), __set() and __call() methods work and how best to use them.
It does get a little bit complicated towards the end, but is a good example of a)why one should or need to use a dynamic class/object and b)how to implement it successfully within your application.
Beginners tips for form processing with PHP
I remember when first starting with the whole PHP / Web development scene that processing forms was a real hassle. This was back in the day when php_global_vars was still accepted as the “in” thing and you had to use each form variable as php variable. I only found out about $_GET (or as it was $HTTP_GET_VARS) later on, much to my consternation.
I did however, come up with a workaround at the time, and it’s stuck with me ever since. I fully realise that the PHP superglobals make this method somewhat redundant, but I still find it useful in larger forms, especially when you’re trying to group related form variables.
The basic idea is to add each form variable to an array. In my case this array is usually called “items”. For instance, I have a standard login form with the usual login and password fields. I define each field using the following method : <input type=”text” name=”items[login]” value=”" /> – for the novices out there, notice the “items[login]” bit. What this does is assign the value for “login” to the “items” array. This array is then accessed via the $_GET["items"] or $_POST["items"] superglobals. Of course you can have multi-dimensional arrays – for example : <input type=”text” name=”items[user][login]” /> and so on and so forth.
Now the really useful part comes in when you are looking to sanitize only certain parts of your user input (yes I’ve had instances where I purposely didn’t want to sanitize incoming data). For a good tutorial on how to sanitize user input – try this one . You can also assign input data to a session variable more easily. I.e $_SESSION["userdata"] = $_GET["items"]["user"].
Lately, I’ve found this method extremely useful when binding form data to my MVC model data. So lets say we have a form where a user can edit his/her profile. In addition, this form also has space for the user to edit his password. Usually, password and profile information is stored in 2 separate tables. Which means that I would use “user[]” for the password fields (since you need a “confirm password” field aswell) and I would use “profile[]” for the user’s profile data. Then once inside the PHP script, I can then bind $_GET["user"] to my user model, and $_GET["profile"] to my userProfile model. The only constraint then is making sure the form field matches a model field.
I admittedly haven’t seen this method being used all that often, and it does make me wonder if it goes against some “best practice” that I’m ignorant of, or perhaps I’m just way ahead of my time
Either way, hopefully it can be of some help to someone out there. I do promise though, that when I’ve improved my blogging and therefore writing skills, I’ll revisit this post and make it more “noob” friendly.
