0

选择下拉列表选项后,我想将该选定选项保留为 javascript 变量。

为了使这更复杂一点,该变量应该保存在页面的主要 Ajax 编码中,因此在加载不同的 Ajax 内容时它不会丢失。

这是我奇妙的基本表单代码:

<form name="searchLocations" method="POST">
        <select name="locationName">
            <?php 
            $sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
            while ($row = mysql_fetch_array($sql)){
            echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
            }
            ?>
        </select>
        <button onclick="loadXMLDoc(indexSearchingSubmit);" id="searchingSubmit">Search</button>
    </form>

这是我的主要 ajax 代码,其中应保存表单下拉变量,以便以后使用:

<script>
window.onload = function () {
    var everyone = document.getElementById('everyone'),
        searching = document.getElementById('searching'),
        searchingSubmit = document.getElementById('searchingSubmit');

    everyone.onclick = function() {
        loadXMLDoc('indexEveryone');
        everyone.className = 'filterOptionActive';
        searching.className = 'filterOption';
    }

    searching.onclick = function() {
        loadXMLDoc('indexSearching');        
        searching.className = 'filterOptionActive';
        everyone.className = 'filterOption';
    }

     searchingSubmit.onclick = function() {
        loadXMLDoc('indexSearchingSubmit');  
    }

    function loadXMLDoc(pageName)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
            }
          }

        function get_query(){
          var url = location.href;
          var qs = url.substring(url.indexOf('?') + 1).split('&');
          for(var i = 0, result = {}; i < qs.length; i++){
            qs[i] = qs[i].split('=');
            result[qs[i][0]] = decodeURIComponent(qs[i][1]);
          }
          return result;
        }

        xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
        xmlhttp.send();
        }
}
</script>
<!-- ends ajax script -->
4

1 回答 1

0
Using jQuery:
    $('[name="locationName"]').change(function() {
      YOUR_VAR = $(this).attr('value');
    });


Not using jQuery- 
Add onChange() to your SELECT element, also added id attribute.
Add javascript onchange handler function, which just retrieves the selected value and sets your var

    <select name="locationName" onChange="setSelected()" id="locationSelect">

    function setSelected(){
      var myselect= document.getElementById("locationSelect");
      YOUR_VAR = myselect.options[myselect.selectedIndex].value;
    }
于 2013-11-07T17:33:22.237 回答