我是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