在JS文本区域中将大小写更改为小写

时间:2011-11-13 23:56:38

标签: javascript

如何将textbox / textarea中字符的大小写更改为小写onchange?

<html>
<head>
<title>Page Title</title>
<script>
function f2(string)
{
string=string.toUpperCase();
alert(string);
}
</script>
</head>
<body>
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea onchange='f2(this.value);'></textarea>
</p>
</form>
</body>

8 个答案:

答案 0 :(得分:2)

你有没有尝试过;

function f2(textarea)
{
    string = textarea.value;
    alert(string);
    string = string.toLowerCase();

    textarea.value = string;
}

将onChange修改为;

<textarea onchange='f2(this);'></textarea>

答案 1 :(得分:1)

只需更改值并将其分配回来。


<textarea onchange='this.value=this.value.toLowerCase();'></textarea>

答案 2 :(得分:1)

因为没有人修理你的代码

<强> HTML:

<p>Here are my text entry objects:</p>
<form>
  <p>
    Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
  <textarea></textarea>
</p>

<强> JS:

document.getElementsByTagName("textarea")[0].addEventListener("change", function () {
    this.value = this.value.toLowerCase(); 
});

您想要添加更改事件处理程序。在事件处理程序中,您只需使用更改为lowerCase的字符串覆盖元素的value属性。

我还在您的HTML中修复了您的在线JavaScript。这是魔鬼,避免它。

Live Example

答案 3 :(得分:0)

只需使用.toLowerCase()方法。

答案 4 :(得分:0)

使用onchange='this.value = this.value.toUpperCase();'将文字设为大写。将toUpperCase替换为toLowerCase,反之亦然。

如果需要,您可以使用自己的函数而不仅仅是toUpperCase,只传递textarea的值或整个textarea。例如(仅限值):

<!-- HTML -->
<textarea onchange='this.value = f2(this.value);'></textarea>

// JavaScript
function f2(oldText) {
    var newText = oldText.toUpperCase();
    return newText;
}

或(整个textarea):

<!-- HTML -->
<textarea onchange='f3(this);'></textarea>

// JavaScript
function f3(ta) {
    ta.value = ta.value.toUpperCase();
}

答案 5 :(得分:0)

我会通过this,然后像DOMNode

一样处理它
<p>Here are my text entry objects:</p>
<form>
 <p>
 Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
  <textarea onchange='f2(this);'></textarea>
 </p>
</form>

function f2(el) {
    el.value = el.value.toLowerCase();
}

http://jsfiddle.net/HDR8t/1

答案 6 :(得分:0)

问题1

我认为onchange事件只有在<textarea>不再具有焦点时才会被触发。相反,您需要使用onkeyup事件。

问题2

您只是将字符串传递给函数。如果要更改<textarea>中的实际文本,则需要将实际的DOM元素传递给函数:

<textarea onkeyup="f3(this)"></textarea>

问题3

将元素传递到函数后,您需要更新其value属性:

function f3(elem) {
    elem.value = elem.value.toLowerCase();
}

答案 7 :(得分:0)

尝试[.toLowerCase()][1]方法。

<textarea onchange='this.value=this.value.toLowerCase();'></textarea>