Accessing a HTML element using javacript variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dhillarun
    New Member
    • Mar 2007
    • 18

    Accessing a HTML element using javacript variable

    Hi All,

    I am passing ID of the HTML SELECT element to a javascript function.
    In that function I need to access the value selected in that select box.
    I tried the following code. but it didn't work.

    Code:
    function save()
    { 
       var x='bid';
       res=document.bform.x.options[document.x.selectedIndex].value;
       alert(res);
    }
    [HTML]
    <form name="bform" >
    <select id="bid" name="bid">
    <option value="1">1
    <option value="2">2
    </select>
    <input type="button" onClick="save() ;">
    </form>
    [/HTML]

    My problem is , I am having id value of the select box in a variable.
    How can I use that value while calling "document.frm_n ame.select_elem ent_name.select edIndex;"

    Pl. do reply me.
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Replace
    Code:
    .x.
    with
    Code:
    [x]
    in your code or try:
    [CODE=javascript]document.getEle mentById(x).val ue;[/CODE]

    Comment

    • gaya3
      New Member
      • Aug 2007
      • 184

      #3
      Originally posted by dhillarun
      Hi All,

      I am passing ID of the HTML SELECT element to a javascript function.
      In that function I need to access the value selected in that select box.
      I tried the following code. but it didn't work.

      Code:
      function save()
      { 
         var x='bid';
         res=document.bform.x.options[document.x.selectedIndex].value;
         alert(res);
      }
      [HTML]
      <form name="bform" >
      <select id="bid" name="bid">
      <option value="1">1
      <option value="2">2
      </select>
      <input type="button" onClick="save() ;">
      </form>
      [/HTML]

      My problem is , I am having id value of the select box in a variable.
      How can I use that value while calling "document.frm_n ame.select_elem ent_name.select edIndex;"

      Pl. do reply me.

      Hi,
      Instead of giving like
      res=document.bf orm.x.options[document.x.sele ctedIndex].value;

      u may give like....
      res=document.bf orm.x.options[document.bform. x.selectedIndex].value;

      i have tried out.. its working fine..

      -Thanks,
      Hamsa

      Comment

      Working...