Developpement Informatique

février 18, 2010

JQuery: Playing with Select (DropDownList/ComboBox)

Filed under: JQuery — izaam01 @ 2:39

Why oh why did the HTML overlords call their Combo Box/DropDownList a SELECT?  Then call the items in the list OPTIONS?  It isn’t like there weren’t a plethora of other names for the widget.  Then it could have been consistent anyway.

Oh well.

It seams that each time I start a new project I have to relearn how to grab values out of a DropDownList – I mean “select element”.  Anyway, I’m trying to get this down before I go nuts and have to learn it all over again.

Basic Select

First off, here is the basic html I’m talking about:

   1: <select id="ComboBox" >
   2:       <option value="1">Value 1</option>
   3:       <option value="2">Value 2</option>
   4:       <option value="3">Value 3</option>
   5:       <option value="4">Value 4</option>
   6:       <optgroup label="Group1">
   7:         <option value="5">Value 5</option>
   8:         <option value="6">Value 6</option>
   9:         <option value="7">Value 7</option>
  10:         <option value="8">Value 8</option>
  11:       </optgroup>
  12:     </select>

 

Value 1 Value 2 Value 3 Value 4 Value 5 Value 6 Value 7 Value 8

Nice and simple.  Now, the basic things you want to do with said select statement:

1. Get the value of the selected item.

2. Get the text of the selected item.

3. Find out when the value changed

4. Programmatically set the selected item.

5. Modify the list.

Most of those are very easy with JQuery, but one is slightly strange. Lets go through these one by one:

1. Get the value of the selected item

This is the easiest.  Use the val method.  All done.

   1: $("#ComboBox").val()

 

2. Get the text of the selected item

You would think this would be easy as well, but it isn’t.  You cannot just use the text() method on the combobox.  That will give you the text values of all of the options in a single string.  Not what you want.  The trick is to use the :selected query modifier on the option.

   1: $("#ComboBox option:selected").text()

 

Now, you might be tempted to use the ‘>’ (means direct descendent of) between the #ComboBox and the option — don’t.  If you look at my example above, that code will only work for options not in optgroup nodes.

3. Find out when the select value changed

This is also rather easy with JQuery.

   1: $("#ComboBox").change(function() { /* do something here */ });

 

4. Programmatically set the selected item.

   1: $("#ComboBox").val(2);

 

5. Modify the list.

Modifying a select element is not fundamentally different than modifying any other element in the dom, but there are a few basics here to keep in mind. Mainly: try to avoid using the dom directly.  Create html strings instead.

Clear the list:   $(“#ComboBox”).html(“”);

Add to the list: $(“<option value=’9’>Value 9</option>”).appendTo(“#ComboBox”);

Simple as that.

jQuery » Select box manipulation

Filed under: JQuery — izaam01 @ 1:53
jQuery » Select box manipulation

Source code available from GitHub or a Zipped download.

My Select:

#myselect option 1 #myselect option 2

My Select 2:

#myselect2 option 1 #myselect2 option 2

#myselect2 ‘#myselect2 option 2’ (text) : ‘myselect2_2’ (value) selected
You can add a single option: $("#myselect").addOption("Value", "Text");, change the text of an existing option: $("#myselect").addOption("Value", "Text Replacement"); or add multiple options using a hash:
var myOptions = {
« Value 1 » : « Text 1 »,
« Value 2 » : « Text 2 »,
« Value 3 » : « Text 3 »
}
$(« #myselect2 »).addOption(myOptions, false); // use true if you want to select the added options
ajaxAddOption(url[, params, select, fn, args])
Add options via AJAX (page must return valid JSON, sample below): $("#myselect2").ajaxAddOption("ajaxoptions.js");.
{
« ajax1 »: « AJAX option 1 »,
« ajax2 »: « AJAX option 2 »,
« ajax3 »: « AJAX option 3 »
}

Parameters

  • url – Page to get options from (must be valid JSON)
  • params (optional) – Any parameters to send with the request
  • select (optional) – Select the added options, default true
  • fn (optional) – call this function with the select object as param after completion
  • args – (optional) array of arguments to pass onto the function

$("#myselect2").ajaxAddOption("ajaxoptions.js", {}, false, sortoptions, [{"dir":"desc"}]);

function sortoptions(sort)
{
var $this = $(this);
// sort
$this.sortOptions(sort.dir == « asc » ? true : false);
}

removeOption(index/value/regex/array[, selectedOnly])

Remove an option by
– index: $("#myselect2").removeOption(0);
– value: $("#myselect").removeOption("Value");
– regular expression: $("#myselect").removeOption(/^val/i);
– array $("#myselect").removeOption(["myselect_1", "myselect_2"]);

To remove all options, you can do $("#myselect").removeOption(/./);

If you supply a second parameter as a boolean (true, false), then only options that have been selected (and matched) will be removed: $("#myselect2").removeOption("Value 2", true);.

sortOptions([ascending])

Sorting is done as follows: $("#myselect2").sortOptions(false); (descending) or $("#myselect2").sortOptions(); (ascending)

selectOptions(value[, clear])

Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);. You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);

Originally coded by Mathias Bank, with a modification to allow it to take a regular expression.

copyOptions(to[, which])

You can copy options from one select to another: $("#myselect").copyOptions("#myselect2"); (copy selected options) or $("#myselect").copyOptions("#myselect2", "all"); (copy all options)

containsOption(value[, fn])

Checks if a select box has an option with the supplied value

Parameters

  • value – Which value to check for. Can be a string or regular expression
    e.g. if( $("#myselect").containsOption("val1") ) { ... } or if( $("#myselect").containsOption(/^val/i) ) { ... }
  • fn (optional) – Function to apply if an option with the given value is found. Use this if you don’t want to break the chaining
    e.g. $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued

selectedValues()

Returns an array of the values which have been selected. $("#myselect2").selectedValues().

selectedTexts()

Returns an array of the texts which have been selected. $("#myselect2").selectedTexts().

selectedOptions()

Returns a jQuery object with each <option> that has been selected. $("#myselect2").selectedOptions().

Loading content with jQuery AJAX – selecting the element to inject

Filed under: JQuery — izaam01 @ 1:34

On Wednesday I looked at how to load content with jQuery via AJAX using the .load() function. This is the second part of that post which looks at how to just select a portion of the content loaded and inject just that part into the current webpage.

Using a similar example to my previous post, the current webpage that we wish to inject content into has a placeholding <div> that looks like this:

<div id="foo"></div>

We can load content into this with the following Javascript snippet (as long as we’ve also included the jQuery library) from the page /path/to/foo.html:

$('#foo').load('/path/to/foo.html');

If foo.html is a regular HTML page containing <html> <script> etc tags then it can completely screw with your existing page, so it either just needs to contain very basic content, or you can inject just a section of the page into your current webpage.

For example, if foo.html contains something along these lines:

<html>
<head>
<title>My title goes here</title>
<link rel="stylesheet" type="text/css" href="/css/main.css"  />
<script language="javascript" src="/js/jquery-1.2.6.min.js" type="text/javascript">
</script>
</head>
<body>

<div id="blah1">
    ...
</div>

...

<ul id="navigation">
    <li><a href="">ABC</a></li>
    <li><a href="">DEF</a></li>
    <li><a href="">GHI</a></li>
</ul>

...

<div id="blah2">
    ...
</div>

</body>
</html>

and we only wanted to load the navigation list into our current webpage into #foo, we can do this:

$('#foo').load('/path/to/foo.html #navigation');

Note that we have specified #navigation after the path to the filename to be loaded. This tells jQuery to only inject the element #navigation into our current webpage’s #foo element. The resulting #foo <div> would now look like this:

<div id="foo">
<ul id="navigation">
    <li><a href="">ABC</a></li>
    <li><a href="">DEF</a></li>
    <li><a href="">GHI</a></li>
</ul>
</div>

You can use any normal jQuery selectors to choose which elements to inject into the current webpage, so the following would be equally valid:

$('#foo').load('/path/to/foo.html #navigation li');

This would just load the <li> elements from #navigation, resulting in invalid HTML but the jQuery call would succeed.

As noted in the previous post, using .load() in this way will not produce any way of tracking errors if the content could not be loaded. Future posts will look at other ways to load content and look for errors. jQuery/Javascript posts are made on Tuesdays and Sundays so make sure to sign up to my RSS feed (see below) to make sure you don’t miss out.

Liens

Filed under: JQuery — izaam01 @ 1:29

JSON WIKIPEDIA   http://en.wikipedia.org/wiki/JSON#Supported_data_types.2C_syntax_and_example
jQuery API http://api.jquery.com/text-selector/
DOC FR http://jquery.jarodxxx.com/manuel/Les-attributs/text/

Auto-populating Select Boxes using jQuery & AJAX

Filed under: JQuery — izaam01 @ 1:19

source: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

If you are familiar with using select boxes for categorisation and sub-categories, such as ebay does when selling an item, usually this can require a lot of JavaScript to maintain the select boxes, but jQuery can hugely simplify this task by adding a dash of AJAX.

The Goal

Allow the user to select a top level category from one select box and to automatically populate the sub-category.

Prerequisites

  1. Latest copy of jQuery
  2. A basic understanding of JSON (don’t let this put you off – it’s really very, very easy)
  3. A server-side script that can respond to the AJAX request (though I’ve provided a simple example)

Demo

Our demo will specifically look to build a simple form that allows us to book human resource for a project. The top level category is the resource type, and the sub-category will list the individual’s names.

See the demo in action

How it works

Once the top level category select is changed, it sends an AJAX request for the sub-categories. The result of which are converted to select options and the sub-category select’s elements are replaced.

Unobtrusive JavaScript

First things first: as with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this for our tutorial here’s what we need to ensure:

  1. When the page is loaded, the sub-category is loaded (if the top level has a selected item).
  2. There is a ‘load sub-category’ button the user can select to re-load the page. We will hide this button with a <noscript> tag in our demo.

The Code

There are 4 parts to this demo.

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to pre-load the select boxes when the user first visits).
  3. The jQuery & JavaScript.
  4. The JSON response (which will reuse the server-side code).

HTML

<form action="/select_demo.php">
  <label for="ctlJob">Job Function:</label>
  <select name="id" id="ctlJob">
    <option value="1">Managers</option>
    <option value="2">Team Leaders</option>
    <option value="3">Developers</option>
  </select>
  <noscript>
    <input type="submit" name="action" value="Load Individuals" />
  </noscript>
  <label for="ctlPerson">Individual:</label>
  <select name="person_id" id="ctlPerson">
    <option value="1">Mark P</option>
    <option value="2">Andy Y</option>
    <option value="3">Richard B</option>
  </select>
<input type="submit" name="action" value="Book" />
</form>

Server-side

This is just a simple example, but it should be obvious that you can expand this to go off to a database and return an object in a JSON data structure:

<?php
if ($_GET[&apos;id&apos;] == 1) {
  echo <<<HERE_DOC
[ {optionValue: 0, optionDisplay: &apos;Mark&apos;}, {optionValue:1, optionDisplay: &apos;Andy&apos;}, {optionValue:2, optionDisplay: &apos;Richard&apos;}]
HERE_DOC;
} else if ($_GET[&apos;id&apos;] == 2) {
  echo <<<HERE_DOC
[{optionValue:10, optionDisplay: &apos;Remy&apos;}, {optionValue:11, optionDisplay: &apos;Arif&apos;}, {optionValue:12, optionDisplay: &apos;JC&apos;}]
HERE_DOC;
} else if ($_GET[&apos;id&apos;] == 3) {
  echo <<<HERE_DOC
[{optionValue:20, optionDisplay: &apos;Aidan&apos;}, {optionValue:21, optionDisplay:&apos;Russell&apos;}]
HERE_DOC;
}?>

Note that this is not accessible. To ensure accessibility, the server side will handle the pre-population of the select boxes as the page is loaded. Here is an example (excluding the headers, footers and JavaScript) of the accessible example.

JSON Response

If I pass the server side id = 2, i.e. /select.php?id=2&ajax=true, the return value is (the ajax=true is an arbitrary flag that I’m using to differentiate between a normal user request and one done via AJAX):

[ {optionValue:10, optionDisplay: 'Remy'},
{optionValue:11, optionDisplay: 'Arif'},
{optionValue:12, optionDisplay: 'JC'}]

The enclosing square brackets denotes an array and each element is separated by a comma.

Within the array are three objects. If you’re familiar with PHP or Perl, you can basically treat these as hashes. The objects have keys (in this case two keys, one called ‘optionValue’ and one called ‘optionDisplay’), and values. Note that keys don’t need to be wrapped in quotes (though in some cases you will need them sometimes).

There are two ways which we can get the data out of this structure (assuming j is the structure):

alert(j['optionDisplay'])

Or:

alert(j.optionDisplay)

jQuery & AJAX Request

Our JavaScript is going to attach itself after the page is load, and fire an event each time the job function select box is changed.

The event will send the new value of the select box and reload the contents of the person select box.

Note that I’m be a bit naughty here, in that I’m plugging HTML directly in to the DOM.

Each item in the JSON response is looped round and used to build up the new options for the select box. As the response is an array (as mentioned earlier), we can call the .length method on it.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
  $("select#ctlJob").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: &apos;true&apos;}, function(j){
      var options = &apos;&apos;;
      for (var i = 0; i < j.length; i++) {
        options += &apos;<option value="&apos; + j[i].optionValue + &apos;">&apos; + j[i].optionDisplay + &apos;</option>&apos;;
      }
      $("select#ctlPerson").html(options);
    })
  })
})
</script>

Acceder à une balise

Filed under: JQuery — izaam01 @ 10:56

Pour une balise avec ID on utilise #

HTML:

<div id= »H1N1″></div>

JS:

$(‘#H1N1’).toggleClass(« selected »);

CSS:

.selected { background: #09F ; fonf-weight=bold; font-size:24 px;}

« Newer Posts

Propulsé par WordPress.com.