【问题标题】:Show textarea field in the same page with AJAX使用 AJAX 在同一页面中显示 textarea 字段
【发布时间】:2017-02-03 11:46:17
【问题描述】:

我试图在我的showContent div 中使用 keyup 键入时显示 textarea 输入的值(稍后我将添加更多代码)。 但我不擅长Ajax 和/或JQuery,希望得到一些帮助。

formPage.phtml 中的表单(我不知道是否因为它是一个重要的phtml 文件):

<form id="answer_form" class="form" method="post">
   <textarea class="input-text" id="content" name="content" id="answer_content" title="Content"></textarea>
   <div id="showContent"><span></span></div>
</form>

我想在showContent div 同时显示它的内容,换句话说,在每个字母之后。

非常感谢!

【问题讨论】:

  • 你能把它做成 jsfiddle.net 吗?

标签: jquery ajax forms magento


【解决方案1】:

我建议使用input 事件而不是keyup,因为当您跟踪用户输入时它更有效:

$('body').on('input', '#content', function(){
    $('#showContent').text( $(this).val() );
})

希望这会有所帮助。

$('body').on('input', '#content', function(){
    $('#showContent').text($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="answer_form" class="form" method="post">
  <textarea class="input-text" id="content" name="content" id="answer_content" title="Content"></textarea>
  <div id="showContent"><span></span></div>
</form>

【讨论】:

  • 我选择了你的答案,因为 on('input') 是即时的,而另一个答案的 on('keyup') 有一点延迟,你能解释一下为什么吗?
  • 是的,这就是为什么我添加了跟踪用户输入时效率更高这两个事件之间的区别。
【解决方案2】:

希望能解决你的问题

<form id="answer_form" class="form" method="post">
            <textarea onkeyup="setContent()" class="input-text" id="content" name="content" id="answer_content" title="Content"></textarea>
            <div id="showContent"><span></span></div>
</form>

<script>
function setContent(){
       $("#showContent").html($("#content").val());
}
</script>

【讨论】:

  • 您的回答也有效,非常感谢!但是对于我要做的事情,另一个更好。
  • @RodrigoDomingues 没问题快乐编码:)
【解决方案3】:

你可以这样做

$(document).on('keyup','#content',function(){
      $("#showContent").html($(this).val());
});

$(document).on('keyup','#content',function(){
	  $("#showContent").html($(this).val());
	});					
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="answer_form" class="form" method="post">
  <textarea class="input-text" id="content" name="content" id="answer_content" title="Content"></textarea>
  <div id="showContent"><span></span></div>
</form>

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2015-12-22
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多