-2

Not a duplicate question; so please consider the content closely before presumption.

I've been using JQuery for years and have never seen this type of behavior before. Consider the following:

<html>
   <div class="order-form-group">
      <label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
      <textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
   </div>
   <div class="order-form-group">
     <label class="order-form-label" for="guestReason">Reason:</label>
     <textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
   </div>
   <div class="button-container">
      <input class="order-form-submit" type="submit" value="Submit">
   </div>
</html>

I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as having the incorrect selector, having more than 1 id on the page and etc.

<script>
   var specInstr = $("#guestSpecialInstructions").val();
   var guestReason = $("#guestReason").val();
</script>

I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.

The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.

After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:

<script>
    var specInstr = $("#guestSpecialInstructions")[0].value;
    var guestReason = $("#guestReason")[0].value;
</script>

Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.

Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.

If I need to change the wording of the title, let me know.

Mark
  • 1,667
  • 2
  • 24
  • 51
  • If the code is situated *before* the relevant HTML then the jQuery selector won't find it. Also `.val()` does in all cases work for ` – Pointy Jul 20 '18 at 14:01
  • 7
    well inputs/textareas should be using `.val()` not `.text()` – epascarello Jul 20 '18 at 14:01
  • 1
    You need to put you jQuery code into a `ready()` block – Liam Jul 20 '18 at 14:02
  • @espascarello textareas should be referenced using text(). not certain where you referenced that fact. thx – Mark Jul 20 '18 at 14:03
  • 1
    Have used `val()` on textareas for many years with never a single issue – charlietfl Jul 20 '18 at 14:03
  • 4
    @Mark that is just completely wrong. – Pointy Jul 20 '18 at 14:03
  • rtm @Mark: http://api.jquery.com/val/: The `.val()` method is primarily used to get the values of form elements such as input, select and **textarea**. When called on an empty collection, it returns undefined. – Pete Jul 20 '18 at 14:08
  • I'd just like to re-iterate I'm pretty sure your actual issue is the missing `ready` block. Your accessing element sin the form before the DOM is loaded. – Liam Jul 20 '18 at 14:10
  • @Liam - depends where that script is - if it's at the end of the body, it doesn't need to be in a document ready – Pete Jul 20 '18 at 14:11
  • https://stackoverflow.com/questions/8854288/val-vs-text-for-textarea – epascarello Jul 20 '18 at 14:11
  • @Liam I generally always enclose my code inside $(document).ready(function () {})] and in this particular instance it was also enclosed inside of the ready function. Appreciate you pointing it out though – Mark Jul 20 '18 at 14:26
  • @Pointy I regress as I was obviously wrong with the statement regarding the .val() . I responded too quickly without thinking the response through. Should have stated that "I" have always used .text() to retrieve the content from textareas. I forgot .val() is also valid because I'd long stopped the practice of using it due to the discrepancy of interpretation across different browsers. – Mark Jul 20 '18 at 14:30
  • @Mark `.val()` *always* works in all browsers, and it always has. – Pointy Jul 20 '18 at 14:31
  • @charlietfl Perfect! That is a valid answer that I understand. – Mark Jul 20 '18 at 14:32
  • @Pointy I wouldn't be so hasty in making the presumption that because "you" haven't experienced an issue or that the majority hasn't doesn't equate to a fact that it doesn't exist. I've seen instances where .val() hasn't worked in certain versions of browsers whereas .text() has. I've already accepted being wrong on speaking too quickly..... but I can't retract on what I've experienced as fact. :-) – Mark Jul 20 '18 at 14:36
  • @Mark never ever seen that myself and used jQuery since very early 1.1 days. The whole original intent of jQuery was to make cross browser compatible methods – charlietfl Jul 20 '18 at 14:39
  • -2 downvotes but the question is clearly stated, clearly not answered anywhere else and obviously should provide value to someone else under those circumstances.... Some folks just like pushing buttons because they can I suppose. Ashame that effort couldn't be directed to answering the question. ;-( – Mark Jul 20 '18 at 14:40
  • @charlietfl It's probably a reasonable assumption to believe that likely a vast majority of developers have never had or seen the issue. But I for one have (as with other developers I've worked with) and thinking back it may have been with a specific version of IE and every developer who has been coding for a while would be aware that IE has had its share of issues. So it may not have been an issue with JQuery per se but a problem with IE. Even the best language can't be totally invulnerable from the potential issues with platforms and environment they're run in. That was my only point. – Mark Jul 20 '18 at 14:50
  • @Mark possibly some real edge case long ago but I remember using `val()` in IE6 with no issues and versions prior to IE8 were horrible to work with regarding various hacks needed – charlietfl Jul 20 '18 at 14:51
  • hey guys, thanks for all the constructive dialog and information. much appreciated :-) – Mark Jul 20 '18 at 15:07
  • Being forced to change the title since it is being challenged as being a dupe; of which it is not. I'll still accept the answer because it provided clarity with the issue during my testing to find an answer where .text() actually is working in a production environment; but not during my troubleshooting because it was initialized with an empty string before clients entered their content. – Mark Jul 20 '18 at 15:55

1 Answers1

3

You can only use text() on a <textarea> if it is pre-populated and to return the original content

Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content

Always use val() to get and set

var $txt = $('textarea')

console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())

$txt.val( 'Some new content')

console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
  Original text
</textarea>
charlietfl
  • 170,828
  • 13
  • 121
  • 150