When do I use .val() vs [removed]?

后端 未结 5 872
慢半拍i
慢半拍i 2020-12-10 13:29

In JQuery when trying to access elements, I see that if I have a form (lets say a textarea), and I want to get the text inside of it, I must use

相关标签:
5条回答
  • 2020-12-10 13:56

    you could use h1.text() or h1.html() which map to innerText and innerHTML respectively.

    As for val() that maps to input.value.

    Using the jquery equivalents gives you cross-browser compatibility, although that's probably more of a historic relic. New browsers probably implement these features the same way.

    As a general rule: value is used on input elements, innerHTML on non-input fields.

    0 讨论(0)
  • 2020-12-10 13:57

    .val() is used to get value from input elements in jQuery. Alternative in JavaScript is .value.

    .innerHTML is used to put some value between some tags. So innerHTML is a DOM property to insert content to a specified id of an element, and with .val() you just get value from some input tags.

    0 讨论(0)
  • 2020-12-10 14:18

    .val() is used to get/replace input elements values in jQuery, alternative in JS is .value.

    innerHTML or jQuery's .html() is used to get/replace the whole markup inside an element, not input elements.

    text() is used almost the same as JS innertHTML, only it gets/replaces the text inside an element, not all the tags etc. It's bassically the equivalent of JS innerText

    Reference links about innerHTML, innerText, val(), text(), html()

    0 讨论(0)
  • 2020-12-10 14:21

    Because all the inputs in Html have val() and they can send their values to be processed by a form, such as textarea, text, submit, ...

    but tags like h1, span, ... dont participate in form and wont be processed, and also they may have inner tags and html as well.

    0 讨论(0)
  • 2020-12-10 14:22

    textarea.innerHTML actually will work to get the html content of the textarea as it's initially rendered, whereas val() will get the current value based on user input. val() as others have stated only works on form elements so it would have no result for an <h1>.

    $('textarea').on('input', function() {
      $('#innerhtml').text(this.innerHTML);
      $('#val').text($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    Type in the textarea below to see results:
    <br>
    <textarea>test123</textarea>
    <div>textarea innerHTML:</div>
    <div id="innerhtml"></div>
    <div>textarea val:</div>
    <div id="val"></div>

    0 讨论(0)
提交回复
热议问题