2015-11-02 222 views
2

我需要一个textarea在textarea值的开始和结尾包含一组双引号。以下代码的作用是将双引号添加到字段的开始和结尾,但如果用户输入文本然后返回到字段,则可以添加多个双引号集。我怎样才能防止这一点? jQuery解决方案也是可以接受的。如何正确地将双引号添加到Textarea

<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea> 

function quotes(){ 
    var quoteValueBefore = document.getElementById("quoteName").value; 
    var ensureQuotes = "\"" + quoteValueBefore + "\""; 
    document.getElementById("quoteName").value = ensureQuotes; 
} 
+1

你为什么想要报价?我个人认为在服务器端应用它会更容易。无论哪种方式,您都可以检查quoteName的第一个字符和最后一个字符,如果它等于不预先/附加它的引号。 – kyle

回答

0

检查文本是否已经以引号开头,是否已经以一个引号结尾。如果缺少任何一个,请添加它。

同时检查长度> = 2,否则"将通过测试(与报价结束?检查。开始报价?检查。)

function quotes() { 
 
    var quoteValue = document.getElementById("quoteName").value; 
 

 
    if (!quoteValue.match(/^"/)) 
 
    quoteValue = '"' + quoteValue; 
 

 
    if (!quoteValue.match(/"$/)) 
 
    quoteValue += '"'; 
 

 
    if (quoteValue.length < 2) 
 
    quoteValue += '"'; 
 

 
    document.getElementById("quoteName").value = quoteValue; 
 
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>

+0

谢谢,保罗!如果我点击文本框并键入test,它在离开字段时成功添加了双引号,如果我回到字段并在第二次测试后键入test,它不会删除中间的双引号集。我怎样才能防止呢?再次感谢。 例如:“测试”测试“ –

+0

您可以在其他任何事情之前执行'quoteValue.replace(/”/ g,“”);'然后如果某人*想要*引号的值,该怎么办?如果你需要服务器端或其他地方的引号,为什么不把它们添加到那里呢? –

0

function checkQuotes(id) { 
 
    str = document.getElementById(id).value; 
 
    if (str[0] != '"') { 
 
    str = '"'.concat(str); 
 
    } 
 
    if (str[str.length - 1] != '"') { 
 
    str = str.concat('"') 
 
    } 
 
    return str 
 
} 
 

 
function quotes() { 
 
    withQuotes = checkQuotes("quoteName"); 
 
    document.getElementById("quoteName").value = withQuotes 
 
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onchange="quotes()">testing the quotes feature</textarea>

这个片段将检查第一characte r是一个引号,如果不是,它会预先设定它。它还会检查最后一个字符是否是一个引号,如果不是则会附加引号。这可能不是最友好的用户界面解决方案,并且我建议通过CSS添加它,如果您将它用于显示目的,或者使用PHP或您正在做的后端表单提交。