SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Oct 2000
    Posts
    407
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Check select value onLoad

    I have a form with a select drop-down menu that has several options. When the user enters the page with the form I want to check the value of the selected option and do something if it's a certain value.

    Confused?

    Well, the user has signed up for an account and selected some options earlier, he goes to this page to edit them. His previous options are stored in a database and retreived with PHP. The option he previously selected is automatically pre-selected in the drop-down box. Now I want to do something if it's a specific option.

    I have tried several variations of a script, but I can't get it to work. This is what I currently got: (The form is named "designselect" and the select menu is named "design").
    Code:
     
    function checkDesign() {
    if (document.designselect.design.selectedIndex == "design00") {
    alert('Works');
    } else {
    alert('Does not work');
    }
    }
     
    window.onload = checkDesign();

  2. #2
    SitePoint Wizard silver trophy
    Join Date
    May 2003
    Posts
    1,843
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First, the obvious question: why not do this in php? You're already using it to query the dB and presumably other purposes; not much point running this on the client when you're assured of 100% control at your end.

    Otherwise...this:
    Code:
    window.onload = checkDesign();
    ...won't assign your event handler for later use, it'll run it immediately (as part of the assignment). That's what () are for. Set a 'pointer' (reference, really):
    Code:
    window.onload = checkDesign;
    HTML (<body> tag) handles this quirk for you. And: .selectedIndex is an integer property; I think you're confusing it with Option.value, retrieved by 'plugging in' the selectedIndex to the Options array:
    Code:
    onload = function()
    {
        var oSelect = document.designselect.design;
        if (oSelect.options[oSelect.selectedIndex].value == 'design00')
            alert('Works');
        else alert('Does not work');
    }
    ::: certified wild guess :::

  3. #3
    SitePoint Evangelist
    Join Date
    Oct 2000
    Posts
    407
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, that works perfectly

    Yes, it could be done in PHP, but I thin it is much simpler to do what I want with JavaScript. Thanks for the explanation, I see what you mean and I might have mixed up some things. I'm fairly new at JS

    Thanks again for the help!


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
  •