简体   繁体   中英

Javascript Validation of dynamic textarea

Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. The text area has a different ID on each different product page. 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. I cant assign an id to the text areas so cant use this script I normally use. 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:

<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.

It returns a NodeList of all the text areas currently in the page which you can iterate.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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