简体   繁体   English

如何使用 JavaScript 更改 HTML 选定选项?

[英]How do I change an HTML selected option using JavaScript?

I have option menu like this:我有这样的选项菜单:

<form name="AddAndEdit">
   <select name="list" id="personlist">
      <option value="11">Person1</option>
      <option value="27">Person2</option>
      <option value="17">Person3</option>
      <option value="10">Person4</option>
      <option value="7">Person5</option>
      <option value="32">Person6</option>
      <option value="18">Person7</option>
      <option value="29">Person8</option>
      <option value="28">Person9</option>
      <option value="34">Person10</option>
      <option value="12">Person11</option>
      <option value="19">Person12</option>
   </select>
</form>

And now I want to change the selected option by using an href.现在我想通过使用 href 来更改选定的选项。 For example:例如:

<a href="javascript:void(0);"
  onclick="document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected';">change</a>

But I want to select the option with value=11 (Person1) , not Person12 .但我想选择value=11 (Person1)的选项,而不是Person12

How do I change this code?如何更改此代码?

Change改变

document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'

to

document.getElementById('personlist').value=Person_ID;

Tools as pure JavaScript code for handling Selectbox:作为处理 Selectbox 的纯 JavaScript 代码的工具:

Graphical Understanding:图形理解:

Image - A图像-A

在此处输入图片说明


Image - B图像-B

在此处输入图片说明


Image - C图像-C

在此处输入图片说明

Updated - 25-June-2019 |更新 - 2019 年 6 月 25 日 | Fiddler DEMO提琴手演示

JavaScript Code: JavaScript 代码:

/**
 * Empty Select Box
 * @param eid Element ID
 * @param value text
 * @param text text
 * @author Neeraj.Singh
 */
function emptySelectBoxById(eid, value, text) {
    document.getElementById(eid).innerHTML = "<option value='" + value + "'>" + text + "</option>";
}


/**
 * Reset Select Box
 * @param eid Element ID
 */

function resetSelectBoxById(eid) {
    document.getElementById(eid).options[0].selected = 'selected';
}


/**
 * Set Select Box Selection By Index
 * @param eid Element ID
 * @param eindx Element Index
 */

function setSelectBoxByIndex(eid, eindx) {
    document.getElementById(eid).getElementsByTagName('option')[eindx].selected = 'selected';
    //or
    document.getElementById(eid).options[eindx].selected = 'selected';
}


/**
 * Set Select Box Selection By Value
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByValue(eid, eval) {
    document.getElementById(eid).value = eval;
}


/**
 * Set Select Box Selection By Text
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByText(eid, etxt) {
    var eid = document.getElementById(eid);
    for (var i = 0; i < eid.options.length; ++i) {
        if (eid.options[i].text === etxt)
            eid.options[i].selected = true;
    }
}


/**
 * Get Select Box Text By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxText(eid) {
    return document.getElementById(eid).options[document.getElementById(eid).selectedIndex].text;
}


/**
 * Get Select Box Value By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxValue(id) {
    return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
}
mySelect.value = myValue;

其中mySelect是您的选择框,而myValue是您要将其更改为的值。

I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.我相信博客文章JavaScript 初学者 – 按值选择下拉选项可能对您有所帮助。

<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>

function selectItemByValue(elmnt, value){

  for(var i=0; i < elmnt.options.length; i++)
  {
    if(elmnt.options[i].value === value) {
      elmnt.selectedIndex = i;
      break;
    }
  }
}

You could also change select.options.selectedIndex DOM attribute like this:您还可以像这样更改 select.options.selectedIndex DOM 属性:

 function selectOption(index){ document.getElementById("select_id").options.selectedIndex = index; }
 <p> <select id="select_id"> <option selected>first option</option> <option>second option</option> <option>third option</option> </select> </p> <p> <button onclick="selectOption(0);">Select first option</button> <button onclick="selectOption(1);">Select second option</button> <button onclick="selectOption(2);">Select third option</button> </p>

Your own answer technically wasn't incorrect, but you got the index wrong since indexes start at 0, not 1. That's why you got the wrong selection.从技术上讲,您自己的答案并没有错,但是您弄错了索引,因为索引从 0 开始,而不是 1。这就是您选择错误的原因。

document.getElementById('personlist').getElementsByTagName('option')[**10**].selected = 'selected';

Also, your answer is actually a good one for cases where the tags aren't entirely English or numeric.此外,对于标签不完全是英文或数字的情况,您的答案实际上是一个很好的答案。

If they use, for example, Asian characters, the other solutions telling you to use .value() may not always function and will just not do anything.例如,如果他们使用亚洲字符,则告诉您使用 .value() 的其他解决方案可能并不总是起作用,并且不会做任何事情。 Selecting by tag is a good way to ignore the actual text and select by the element itself.按标签选择是忽略实际文本并按元素本身选择的好方法。

You can use JQuery also你也可以使用 JQuery

$(document).ready(function () {
  $('#personlist').val("10");
}

If you are adding the option with javascript如果您使用 javascript 添加选项

function AddNewOption(userRoutes, text, id) 
{
    var option = document.createElement("option");
    option.text = text;
    option.value = id;
    option.selected = "selected";
    userdRoutes.add(option);
}

一个数组索引将从 0 开始。如果你想要 value=11 (Person1),你会得到它的位置getElementsByTagName('option')[10].selected

It's an old post, but if anyone is still looking for solution to this kind of problem, here is what I came up with:这是一个旧帖子,但如果有人仍在寻找此类问题的解决方案,这就是我想出的:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.forms['AddAndEdit'].elements['list'].value = 11;
  });
</script>

Note: Option Index count starts from 0. That means first option will be indexed at 0.注意:选项索引计数从 0 开始。这意味着第一个选项将被索引为 0。

 document.querySelector(".add__btn").addEventListener("click", function(){ var index = 1; /*change option value here*/ document.querySelector(".add__type").options.selectedIndex = index; document.querySelector(".add__description").value = "Option Index"; document.querySelector(".add__value").value = index; });
 <html> <div class="add__container"> <select class="add__type"> <option value="inc" selected>+</option> <option value="exp">-</option> </select> <input type="text" class="add__description" placeholder="Add description"> <input type="number" class="add__value" placeholder="Value"> <button class="add__btn"> Submit </button> </div> <h4> Default Option Value will be selected after pressing Submit </h4>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript更改选项标签上的“选定”属性 - How do I change the “selected” attribute on an option tag with javascript 如何使用 jQuery、JavaScript 和 HTML 动态设置下拉列表的选定选项? - How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML? 使用JavaScript选择文件后,如何更改HTML标签文本 - How do I change HTML Label Text Once File Has Been Selected using Javascript HTML SELECT - 使用JavaScript更改VALUE选定的选项 - HTML SELECT - Change selected option by VALUE using JavaScript 如何根据选定的选项Javascript更改html中的值 - How to change value in html depending on selected option Javascript 如何编写jQuery / javascript if语句,以便在html时触发 <option>选择特定班级? - how do I write a jQuery/javascript if statement so that it's triggered when a html <option> with a specific class is selected? JavaScript和HTML-如何将组合框的选定选项的值放入跨度? - JavaScript and HTML - How do I put the value of a selected option of a combobox into a span? 如何使用javascript更改jquery selectric元素的选定选项? - How do you change the selected option of a jquery selectric element using javascript? 如何更改所选选项的背景颜色? (HTML) - How can I change the background color of a selected option? (HTML) 如何使用动态添加的选项更改所选选项? - How do I change the selected option with dynamically added options?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM