设置下拉列表的选定值

时间:2014-02-24 06:29:51

标签: javascript jquery

我有dropdown list

function getTests() {
  var html = '';
  $.get('/getTests', function (tests) {
       selTest = tests;
       html +=' <option value="">SELECT</option>';
       tests.forEach(function (test) {
          html += '<option value="' + test.id + '">' + test.names + '</option>'; 
       });
       $('#testnames').html(html);
  });
}

HTML代码: -

<select class="lngcombo" id="testnames">
  <option value="">SELECT</option>
  <option value="25">email confirmation</option>
  <option value="72">ttutu</option>
  <option value="44">pagination</option>
</select>

从另一个网页引导我获取值test.id,如下所示,并希望获取下拉列表中选定的值

http://localhost:9080/history.html?testid=25

根据email confirmation

选择作为下拉值testid=25

为此,我正在做以下事情: -

$(document).ready(function () {
    if (window.location.href.indexOf('testid') > -1){

       var testid = window.location.href;
       testid =testid.split('=');
       alert($("#testnames").val(testid[1]))
    }
});

但未获得所选的值

5 个答案:

答案 0 :(得分:1)

由于您使用ajax请求加载内容,因此需要在完成ajax请求并创建选项后设置值。

因此解决方案模板可能看起来像

function getTests(testId) {
    var html = '';
    $.get('/getTests', function (tests) {
        selTest = tests;
        html += ' <option value="">SELECT</option>';
        tests.forEach(function (test) {
            html += '<option value="' + test.id + '">' + test.names + '</option>';

        });
        $('#testnames').html(html);
        if(testId){
            $("#testnames").val(testId)
        }
    });
}

$(document).ready(function () {
    if (window.location.href.indexOf('testid') > -1) {
        var testid = window.location.href;
        testid = testid.split('=');
        getTests(testid[1])
    }else{
        getTests()
    }
});

答案 1 :(得分:0)

您不需要此处的提醒,只需使用:

$("#testnames").val(testid[1]);

<强> Fiddle Demo

答案 2 :(得分:0)

试试这个脚本。

JS

$(document).ready(function () {
    if (window.location.href.indexOf('testid') > -1){
        var testid = getParameterByName('testid');
        $('#testnames').val(testid);
    }
});

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

答案 3 :(得分:0)

你需要在完成ajax调用时调用这个函数,这里的情况不同,js-function首先调用,html稍后呈现。因此,了解我们应首先渲染html然后调用我们的js函数是很重要的。它适用于你。

alert($("#testnames").val(testid[1]).val());

答案 4 :(得分:0)

使用此代码 我测试了它

var val = $(".lngcombo").val(); alert(val);