.on detects only first change

时间:2019-01-09 22:16:03

标签: javascript jquery

Trying to pass changes in input field to a variable simultaneously with the change. But for some reason, my code detects only first change. For example, if I enter "100" into the field, it only detects "1". Nothing happens afterwards.

Here is my jquery

$(document).ready(function() {
  var wholeshort = $(".shorcodeval").val();
  a = wholeshort;
  var w = /width="(.*?)"/.exec(a)[1];
  $(".widthinput").on('input', function() {
    nw = $(this).val();
    wholeshort = wholeshort.replace(w, nw);
    $(".shorcodeval").val(wholeshort);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>

here is the fiddle

https://jsfiddle.net/3a6n1fux/

1 个答案:

答案 0 :(得分:0)

问题在于,在第一个input之后,您将[example width="1"]保存在wholeshort中,但是w300px,因此您尝试替换{{1} }在300px中。

要解决此问题,您需要将[example width="1"]的结果保存在自己的变量中,或将其直接传递给wholeshort.replace(w, nw)

.val(wholeshort.replace(w, nw))
$(document).ready(function() {
  var wholeshort = $(".shorcodeval").val();
  var w = /width="(.*?)"/.exec(a)[1];
  
  $(".widthinput").on('input', function() {
    var nw = $(this).val();
    $(".shorcodeval").val(wholeshort.replace(w, nw));
  });
});