新增<选项>到所有下拉列表< select>标签使用JavaScript [英] Add new <option> to all dropdown <select> tags using javascript

查看:89
本文介绍了新增<选项>到所有下拉列表< select>标签使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在页面上的每个下拉列表的顶部添加一个下拉菜单选项请选择,默认情况下会使用类似的方式来选择:

Im trying to add a Drop down menu option "Please select" to the top of each drop-down list on a page to be selected by default, using something similar like this:

window.onload = function() {
    $('select option[value="PSC"]').attr("selected",true);
};

这就是即时消息使用的下拉菜单:

and this is what im using for the drop-down:

window.onload = function AddItem(text,value) {
    // Create an Option object
    var opt = document.createElement("option");
    // Add an Option object to Drop Down/List Box
    document.getElementsByTagName("option").options.add(opt);
    // Assign text and value to Option object
    opt.text = 'Please select...';
    opt.value = 'Please Select';  
}

我是javascript新手,有人能指出我正确的方向将它们编译在一起,以便当页面加载每个下拉列表时获得一个名为请选择的默认选择选项。

I'm new at javascript, can someone point me in the right direction to compiling this together so that when the page loads every drop-down list gets a default selected option called "Please select"

在此先感谢

Thanks in Advance

推荐答案

修改了您纯粹的javascript函数,以此函数(这不影响已经选择的选项) DEMO jsfiddle
$ b

Modified you pure javascript function to this function (This does not affect the already selected option) DEMO jsfiddle

     window.onload = function AddItem(text, value) {

        // Get all Drop Down/List Box in document
        var sel = document.getElementsByTagName("select");

        for (var x = 0; x < sel.length; x++) {

           // Create an Option object and set it's value/text
           var opt = document.createElement("option");
           opt.text = 'Please select...';
           opt.value = 'Please Select';

           //prepend in select box
           sel[x].insertBefore(opt, sel[x].options[0])
        }
     }

这篇关于新增&lt;选项&gt;到所有下拉列表&lt; select&gt;标签使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆