1

This logs the values of each of 10 textarea elements as expected:

$('.container').each(function() {

    var textA = $('textarea', this).val();
    console.log(textA)

});

This regex works fine in the console:

"https://hi.com/hey junk nothing https://hi.com/there".match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);

I get back: ["https://hi.com/hey", "https://hi.com/there"]

But when I try this:

$('.container').each(function() {

    var textA = $('textarea', this).val();
    var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
    console.log(matches)

});

I get Uncaught TypeError: Cannot read property 'match' of undefined

Why undefined? Is it because the Type of what is coming in to match hasn't been declared properly? If so, how should I declare so that it can be 'seen'?

5
  • 1
    $('textarea', this).val().trim() Commented Sep 4, 2015 at 13:19
  • @stribizhev how this would prevent textA to be undefined ? Commented Sep 4, 2015 at 13:22
  • 2
    @bahmait, you should check that in each loop $('textarea', this).val(); return something. maybe there is a .container that do not contains a textarea Commented Sep 4, 2015 at 13:23
  • 1
    My guess is that you have some .container with not texterea in it, returning this error. Here the same problem in a fiddle : jsfiddle.net/jvmmxrb1 Commented Sep 4, 2015 at 13:28
  • Of course: that's it -- I was focused only on the relevant containers. Thank you very much! Commented Sep 4, 2015 at 13:31

1 Answer 1

1

To answer the question: you need to check if textarea is present in the .container. You can check it with .length > 0:

$('.container').each(function() {

    var textArea = $('textarea', this);    // Changed here
    if (textArea.length > 0) {             // and here
        var textA = textArea.val();
        var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
        console.log(matches);
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<textarea name="mytextarea" id="" cols="30" rows="10">
https://hi.com/new-url
More
  lines
      https://hi.com/last-url
    </textarea>        
</div>

<div class="container">
  Empty one with no textarea
</div>

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.