简体   繁体   English

动态文本区域的Javascript验证

[英]Javascript Validation of dynamic textarea

Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. 嗨,我正在使用CMS,该CMS可在电子商务网站的产品页面上动态创建文本区域。 The text area has a different ID on each different product page. 文本区域在每个不同的产品页面上都有不同的ID。 I am in need of some javascript that will check if all textareas on a page are empty and if so display a warning message. 我需要一些JavaScript,这些JavaScript将检查页面上的所有textareas是否为空,如果显示,则显示警告消息。 I cant assign an id to the text areas so cant use this script I normally use. 我无法为文本区域分配ID,因此无法使用我通常使用的脚本。 Any help is much appreciated! 任何帮助深表感谢!

function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val)) {
    alert('Wrong content!');
}
} 

Hey Benjamin thanks for your reply, I couldn't get the code working in comments, thinking I'm having a bad day. 嘿,本杰明,谢谢您的回覆,我以为我今天过得很糟糕,无法在注释中使用代码。 So as i was trying to say I'm not the greatest at Javascript (but eager to learn!) I've added this to my page but it doesn't appear to work: 因此,正如我试图说的那样,我不是Java语言方面的佼佼者(但渴望学习!),我已将其添加到我的页面中,但似乎不起作用:

<script> 
var areas = document.getElementsByTagName("textarea"); 
// now iterate them for
(var i=0;i<areas.length;i++){ 
 var val = areas[i].value; 
 if (/^\s*$/g.test(val)) { 
 // whatever 
 } 
} </script>

With this as in the body 像这样在体内

<div class="description">Further Details <br>
<textarea id="catProdInstructions_6486638" class="productTextarea"></textarea>
</div>

Thanks for your time on this :) 谢谢您的时间:)

You can use getElementsByTagName to fetch all <textarea> s. 您可以使用getElementsByTagName来获取所有<textarea>

It returns a NodeList of all the text areas currently in the page which you can iterate. 它返回页面中当前可以迭代的所有文本区域的NodeList

var areas = document.getElementsByTagName("textarea");
// now iterate them
for(var i=0;i<areas.length;i++){
    var val = areas[i].value;
    if (/^\s*$/g.test(val)) {
        // whatever
    }
}

The NodeList returned is live , this means that it'll update itself automatically as new textarea elements are added dynamically even if you fetch them with ajax or create them with code. 返回的NodeList是live ,这意味着它会自动更新,因为动态添加了新的textarea元素,即使您使用ajax获取它们或使用代码创建它们也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM