Link to home
Start Free TrialLog in
Avatar of Shawn Janes
Shawn JanesFlag for United States of America

asked on

JavaScript Variable and Form Interaction

I have a form structured like this with roughly 20 options:

<select name="appIdId">
      <option value="56T34AKJJR">Treasure Wheel Slots</option>

I have the option text in a variable like this:

apptext = "Treasure Wheel Slots";

What I need to do is get the option value (56T34AKJJR) and store that in a variable I can use later on in my code.

apptextvalue = "56T34AKJJR";

Keep in mind I will not be selecting any options, just passing the apptext into the form and returning apptextvalue.

I am not a JavaScript expert, and I would like some guidance on how to pull this off. Is this feasible?

Thank you.

Avatar of Rob
Flag of Australia image

So you're wanting to match the string stored in the variable with an item in the list?
That's possible and involves just looping through each value till you find what you're after. I'll post an example when back at the laptop
Test page :

var apptext = "Treasure Wheel Slots";

window.onload = function() {
    var apptextvalue = getValueFromText(apptext);

    // checking

var getValueFromText = function(txt) {
    var dropdown = document.getElementsByName("appIdId")[0]; // add an ID and use getElementById instead getElementsByName for $0 !!!
    for(var i=0;i<dropdown.options.length;i++) if(dropdown.options[i].text == txt) break;
    return (i != dropdown.options.length)?dropdown.options[i].value:null;

Open in new window

Avatar of leakim971
Flag of Guadeloupe image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
beat me to it :) thanks, like your example @leakim971
That is a solution to the perceived problem as presented by shawnjanes.
I would like to know WHY you have apptext in a variable and not the accompanying value.

What is the server process that generates the select and the text?

You may simply miss some logic that sets up the needed values on the server.

Do you have more of these? If so you could possibly simply do a json_encode of the object that generates the select, it could be created in such a way that you just needed to do
echo "appTextValue ='".$someArray[$someText]."'";
somewhere (above examples are PHP)
Avatar of Shawn Janes


Thank you. This worked perfectly. I can finally move on to the next problem.

::minor celebration going on here::