我是jQuery的新手,偶然发现了RegEx的概念,使用.replace来创建漂亮的文本替换。使用RegEx和.replace以用户输入替换文本?
在我的形式,我有一些复选框触发的文字出现在文字区域。还有一些用户输入区域作为字段。
如何使用此jQuery替换某些文本的一部分与用户输入的复选框,但不在其他人?我想用一个if/else参数来触发RegEx,替换是关键,但我不知道如何合并其余的?
这里是我的形式的样机:
<div style="width: 500px;"><br> Static options:<br> <label id="_comLine100"><input id="comLine100" name="comLines" type="checkbox"> OPTION1 </label> <br> <label id="_comLine101"><input id="comLine101" name="comLines" type="checkbox"> OPTION2 </label> <br> Options which can be modified by user text:<br> <label id="_comLine102"><input id="comLine102" name="comLines" type="checkbox"> OPTION3 </label> <br> <label id="_comLine103"><input id="comLine103" name="comLines" type="checkbox"> OPTION4</label> <br> </div> <br> <input id="usrinput1" size="50" placeholder="Enter something to replace the word Text"> <br><br> <form> <input onclick="javascript:this.form.outPut2.focus();this.form.outPut2.select();"
值= “全选” TYPE = “按钮”>
编辑这里是我的新脚本,根据以下建议:
$(document).ready(function(){
var comLines = {
comLine100: 'Text for option1 \n',
comLine101: 'Text for option2 \n',
comLine102: 'Text for option3 \n',
comLine103: 'Text for option4 \n'
};
var mytextbox = document.getElementById('outPut2');
var chosenComm = null;
var Inputs = document.getElementsByName("comLines");
for (var i = 0; i < Inputs.length; i++) {
Inputs[i].onchange = function() {
chosenComm = this;
printComment();
};
}
function printComment(){
if(chosenComm !== null){
var chxbox=chosenComm.id;
var uinput = document.getElementById('usrinput1');
if(uinput.value!=="" && (chxbox=="comLine102" || chxbox=="comLine103")){
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
else {
mytextbox.value += comLines[chosenComm.id] + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
}
}
});
看到我JSfiddle:http://jsfiddle.net/bENAY/2/
现在按我的意思工作。感谢Eric S的解释和指导!
你提到jQuery在你的问题,但你没有标记这是一个jQuery的问题,也没有你在你的例子中使用任何?选中复选框时,您想查找和替换哪些文本? – 2013-03-12 14:15:46
对不起,我添加了jQuery作为标记。你是对的,我没有展示我用过的jQuery,这大多是一些设计元素来上下滑动div。我一直在阅读这个网站和其他人,并试图在表单中加入一些jQuery元素。在这个例子中,当有人点击方框3或方框4时,我希望在输出中用输入字段中的任何内容替换输出中的单词“文本”。这种类型的替代品是否具有替代能力? – user1837608 2013-03-12 14:36:26
[RegExp是一种元语言](http://www.regular-expressions.info/),其中的一个版本已转化为Javascript。这与jQuery无关。 – Barney 2013-03-12 14:37:20