html - Get wrapped text from textarea

2019-05-29 19:10发布

I'm trying to get the word wrapped line breaks from a textarea without having make any server calls. This answer gets me 90% of the way there. The problem is that the page is reloaded inside of the iframe each time the submit button is clicked. Here's the code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>
  <script type="text/javascript">
    function getURLParameter(qs, name) {
      var pattern = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(pattern);
      var res = regex.exec(qs);
      if (res == null)
        return "";
      else
        return res[1];
    }

    function getHardWrappedText() {
      var frm_url = document.getElementById('frame').contentDocument.URL;
      var text = unescape(getURLParameter(document.getElementById('frame').contentDocument.URL, 'text')).replace(/\+/g, ' ');
      return text;
    }

    function onIFrameLoad() {
      var text = getHardWrappedText();
      console.log(text);
    }

    window.onload = function() {
      console.log("loading")
    };
  </script>
  <form name="form" method="get" target="frame">
    <textarea id="text" name="text" cols=5 wrap="hard">a b c d e f</textarea>
    <input type="submit">
  </form>
  <iframe id="frame" name="frame" onload="onIFrameLoad()" style="display:none;"></iframe>
</body>

</html>

Clicking on the submit button gives the output:

loading
a b c d e 
f

Is there a way to prevent the iframe from reloading the page?

1条回答
混吃等死
2楼-- · 2019-05-29 19:57

You have to return a false to the onsubmit event of the form.

<form name="form" method="get" target="frame" onsubmit="onIFrameLoad">

If it is based on some condition that you do not want to load

function onIFrameLoad() {
    var text = getHardWrappedText();
    console.log(text);
    if(text.indexOf('\n')<0) return false;
}

Am just putting a random thing at text.indexOf('\n')<0, you can have anything that makes sense or always return false (which looks unlikely)

查看更多
登录 后发表回答