如何在两个选择元素之间切换选定的值

时间:2017-07-09 21:44:59

标签: javascript jquery html

如何切换包含相同信息的2 select个html元素的选定值。

目前的情况如下:选择要翻译的语言,然后翻译成。 为了方便用户,我想提供将源语言切换为目标语言的可能性,反之亦然。

HTML标记的简化版本如下:

<select name="LangA">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="sv">Swedish</option>
    <option value="tr">Turkish</option>
    <option value="uk">Ukrainian</option>
</select>

<select name="LangB">
    <option value="en">English</option>
    <option value="es">Spanish</option>
    <option value="sv">Swedish</option>
    <option value="tr">Turkish</option>
    <option value="uk">Ukrainian</option>
</select>

两个select元素的语言相同。我试图实现的功能与谷歌翻译交换语言箭头非常相似。

原因是这些框用于翻译文本区域。使用更多语言,整个代码要大得多,我只是为了保持简短而拿出了所需要的东西。

1 个答案:

答案 0 :(得分:1)

假设两者都有相同的语言,您只需将选择从一个框更改为另一个框。此脚本将在两个选择下拉列表中读取当前选定的值,然后在单击交换时搜索另一个中的选项。

如果语言真的在同一个地方,我能想到的最简单的选择就是:

function swapBySelectedIndex( selector1, selector2 ) {
  // get both elements and save the selectedIndex of the first element
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = elem1.selectedIndex;

  // set the first element to the second elements selectedIndex
  elem1.selectedIndex = elem2.selectedIndex;
  // set the second elements' selectedIndex to the saved index
  elem2.selectedIndex = selectedOption1;
}

function getSelectedOption( elem ) {
  return elem.options[elem.selectedIndex].value;
}

function setSelectedOption( elem, value ) {
  for (let i = 0; i < elem.options.length; i++) {
    elem.options[i].selected = value === elem.options[i].value;
  }
}

function swapByOptionValue( selector1, selector2 ) {
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = getSelectedOption( elem1 ),
      selectedOption2 = getSelectedOption( elem2 );
  setSelectedOption( elem1, selectedOption2 );
  setSelectedOption( elem2, selectedOption1 );
}

function swapBySelectedIndex( selector1, selector2 ) {
  var elem1 = document.querySelector(selector1),
      elem2 = document.querySelector(selector2),
      selectedOption1 = elem1.selectedIndex;
      
  elem1.selectedIndex = elem2.selectedIndex;
  elem2.selectedIndex = selectedOption1;
}
<select name="LangA">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="sv">Swedish</option>
<option value="tr">Turkish</option>
<option value="uk">Ukrainian</option>
</select>

<select name="LangB">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="sv">Swedish</option>
<option value="tr">Turkish</option>
<option value="uk">Ukrainian</option>
</select>

<button type="button" onClick="swapByOptionValue('select[name=\'LangA\']', 'select[name=\'LangB\']')">Swap selected languages</button>

<button type="button" onClick="swapBySelectedIndex('select[name=\'LangA\']', 'select[name=\'LangB\']')">Swap selected languages (using selectedIndex)</button>