SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot dawgbone's Avatar
    Join Date
    Dec 2003
    Location
    Brampton
    Posts
    198
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Comparing an item in a selectbox

    I want to be able to do a string match on some data being populated via AJAX into a selectbox.

    currently, it works if I identify the option index, but not the option value (i.e. match it's position in the select, as opposed to matching the the value of the text).

    for instance (searchForm is the name of the form that the selectbox resides in. departureList is the name of the select box.):

    PHP Code:

    // var departureCity = "Calgary";

    var departureNum 1;

    if(
    document.searchForm.departureList.options[1].value == departureNum){

      
    document.searchForm.departureList.options[1].selected true;


    I hardcoded the value options[1] because it's part of a longer loop, and it's not necessary for this portion.

    Based on that code, if I had Calgary, Chicago, Detroit, Toronto as my 4 cities, me choosing options[1] would choose Calgary. That's all well and good, but the data that populates this selectbox comes from an XML file. That means one day it could be Buffalo, Calgary, Chicago, Detroit, Toronto... meaning that options[1] no longer represents Calgary, but Buffalo.

    What I'd prefer it to do, is match the string "Calgary", as opposed to trying to match it's postion in the selectbox.

    Basically, I'd rather do something like this:

    PHP Code:

    var departureCity "Calgary";

    if(
    Text of selext box  == departureCity){

      
    Make that value defaulted to selected;



  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's one way to select an option based on some text:

    Code:
    function setmatch(A,wotstring){
    	var L=A.length,who,val;
    	for(var i=0;i<L;i++){
    		who=A[i];
    		if(who.text===wotstring){
    			who.parentNode.selectedIndex=i;
    			return who;
    		}
    	}
    	return false;
    }
    setmatch(document.searchForm.departureList.options,'Calgary');

  3. #3
    SitePoint Zealot dawgbone's Avatar
    Join Date
    Dec 2003
    Location
    Brampton
    Posts
    198
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    worked like a charm!

    thanks,


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •