4

I am trying to get the updated value of the input field. actually i am updating the value using keyup function of jquery. and trying to get it on button click. but not able to update please help.

$('#simple').keyup(function() {
   var keyed = $(this).val();
   $("#code").val(keyed);
 });

 var htmlString = $('#code').val();

   $(document).ready(function() {
      $("#snippet").click(function(){
          alert(htmlString);
      }); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="simple"></textarea>

<input type="hidden" id="code" value="">

<button id="snippet">Click</button>

2
  • What do you mean you're 'updating the value using keyup' and then 'trying to get it back on click.' Do you mean you're changing the value on keyup, and then you want to alert the updated value on click? Commented May 5, 2020 at 5:17
  • 1
    javascript basics, var htmlString = $('#code').val(); is in global scope already evaluated at the beginning as empty. By the time you use it, its using the already empty value. Change scope or time of value invocation Commented Jul 4, 2022 at 19:28

2 Answers 2

4

You need to put your holder variable htmlString inside to your onclick function so that you can get the updated value.

$('#simple').keyup(function() {
  var keyed = $(this).val();
  $("#code").val(keyed);
});


$(document).ready(function() {

  $("#snippet").click(function() {
    var htmlString = $('#code').val();
    alert(htmlString);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="hidden" id="code" value="">
<input type="text" id="simple" value="">
<button id="snippet">Click</button>

I hope this will help you. Thanks

Sign up to request clarification or add additional context in comments.

Comments

1

Scope is wrong. Global value htmlString is ""

Part one: Rewrite

$("#simple").keyup(function () {
  var keyed = $(this).val();
  $("#code").val(keyed);
});

$(document).ready(function () {
  $("#snippet").click(function () {
    alert($("#code").val());
  });
});

And

<textarea id="simple"></textarea>
<input type="hidden" id="code" value="" />
<button id="snippet">Click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you understand whats going on, then just do this

$(document).ready(function () {
  $("#snippet").click(function () {
    alert($("#simple").val());
  });
});

AND

<textarea id="simple"></textarea>
<button id="snippet">Click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.