0

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 :)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.