从下拉表单中获取索引值

时间:2016-04-21 11:59:59

标签: php jquery html

我有一个由数据库填充的下拉列表,一切正常。但是我想根据我可以做的下拉列表的值将参数传递给php。如果我强制var具有特定的数字,它将获得数据库中的相应项。我有问题要获得下拉菜单的价值。我已经在论坛中尝试了所有建议,但在我的代码的这个特定区域中没有任何作用。我让它在我的另一段代码上工作,但不是在这个特定的代码上,我不知道为什么。这是我的代码:

<select id="servicos"  onChange="return selectServ();">
    <option value="item" class="itemoption">Serviço</option>

这是无效的代码:

function selectServ() {
    var e = document.getElementById("servicos");
    var idserv = e.options[e.selectedIndex].value;

    $.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
        console.log(data);
        var tr = data
        for (var i = 0; i < data.length; i++) {
            var tr = $('<tr/>');

            // Indexing into data.report for each td element
            $(tr).append("<td>" + data[i].preco + "</td>");
            $('.table1').append(tr);
        }
    });
}

如果我把

var idserv = "1"

它正在发挥作用,但是:

var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;

没有获得价值。控制台日志给出:

  

selectdynamicpreco.html:76未捕获的TypeError:$(...)。value不是函数

2 个答案:

答案 0 :(得分:0)

您应该考虑使用jQuery来获取下拉列表的值: $(&#39; #downdown&#39;)。val()将为您提供下拉元素的选定值。使用此选项可获取所选选项文本。

$("#dropdown option:selected").text();

应该为您提供下拉列表的文本值。

答案 1 :(得分:0)

这是另一段代码

<script>
function selectCat(){
$('#servicos').change(function() {
  $('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
    var e = document.getElementById("categoria");
    var servSelected = e.options[e.selectedIndex].value;

    var url = "";

  var items="";
  if(servSelected === "1"){
  url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
  }
  if(servSelected === "2"){
  url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
  }
  if(servSelected === "3"){
  url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
  }
  $.getJSON(url,function(data){

    $.each(data,function(index,item) 
    {
      items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
    });
    $("#servicos").html(items); 
  });
};
</script>