javascript - 使用 JavaScript 中的选择选项 onchange 更改文本区域内容

标签 javascript html server onchange

这是我的第一个问题,如果我做错了什么,我很抱歉。 我有一个 textarea 和一个选择。我想更改在更改选择选项时输入的 textarea 内容。但是,当我更改回 select 中的上一个选项时,我希望 textarea 显示我之前输入的内容。

例如,当我在选择中选择“英语”选项时,我希望 textarea 显示“英语文本”。然后,当我选择“法语”时,我希望 textarea 显示“法语文本”,但是当我再次选择“英语”选项时,textarea 需要再次显示“英语文本” .

编辑:我需要在服务器端存储数据,以便可以从任何计算机读取数据!抱歉没有早点定义它。

这是我的 HTML 代码:

<select class="dropdown no-border" id="dropdownLanguage">
     <option>Choose language</option>
     <option>English</option>
     <option>French</option>
 </select>

 <textarea name="agencyDescription" id="agencyDescription" class="about-agency" placeholder="Write something about your agency..." maxlength="5000">
     <?php echo $agency->getData('agencyDescription'); ?>
 </textarea>

@OliverRadini 的 JS 代码:

var languageDropdown = document.getElementById("dropdownLanguage");
var lastSelected = languageDropdown.options[languageDropdown.selectedIndex].value

console.log(lastSelected);

languageDropdown.onchange = function(){

    var textBox = document.getElementById("agencyDescription");    
    currentText = textBox.value;

    var selected = this.options[this.selectedIndex].value;

    //load the current text into the last selected value
    sessionStorage.setItem(lastSelected, currentText);


    //load the new text in to the text box
    textBox.value = sessionStorage.getItem(selected);

    lastSelected = selected;
};

我想继续使用 JS 而不是 jQuery。 谢谢您,先!

最佳答案

这是我制作的 fiddle ,它可以工作,但如果它不完美,我会很感激反馈:

https://jsfiddle.net/szmnforr/

var languageDropdown = document.getElementById("dropdownLanguage");

var lastSelected = languageDropdown.options[languageDropdown.selectedIndex].value

console.log(lastSelected);

languageDropdown.onchange = function(){

    var textBox = document.getElementById("agencyDescription");    
    currentText = textBox.value;

    var selected = this.options[this.selectedIndex].value;

    //load the current text into the last selected value
    sessionStorage.setItem(lastSelected, currentText);


    //load the new text in to the text box
    textBox.value = sessionStorage.getItem(selected);

    lastSelected = selected;
};

它非常丑陋,而且我不喜欢全局变量的使用,但它基本上可以工作。

关于javascript - 使用 JavaScript 中的选择选项 onchange 更改文本区域内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870041/

相关文章:

javascript - jquery 每 50 秒显示一个警报,如何?

css - 我在这里缺少的标签规范是什么?

Java 定时器只触发一次(仅服务器问题)

javascript - 如何导出从 HTML DOM Parser 检索到的所有图像?

javascript - 当元素集并不总是在同一个父元素中时,如何找到下一个匹配元素

javascript - 跳房子按钮点击不起作用

wordpress - 更改名称服务器后出现 500 HTTP 错误 (WORDPRESS)

server - 需要帮助让 Rails 服务器正常工作

javascript - 需要用Javascript替换 "$"为 "_"

javascript - 在没有 session 变量的情况下在经典 asp 中发布和取回 html 元素进行验证的最佳方法