-1

I've written a form that contains HTML select served by jQuery. The rest of HTML elements is served by pure Javascript. I want to get in Javascript part the value obtaied from jQuery block. Here is a simple code which covers the subject:

<!DOCTYPE html><html>
<head><meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $("#button").click(function() {
     var value = $("#city").val();
     alert(value);
  })
});
//how to get value from jQuery block above ? ?
var pure_value = value; 
. . . . . . . . . . . . //the next code using value 
</script>
</head>
<body>    Select City:
    <select id="city" name="city">
        <option value="delhi"> Delhi </option>
        <option value="mumbai"> Mumbai </option>
        <option value="chennai"> Chennai </option>
    </select>
    <button id="button"> Fetch Value </button>
</body>
</html>
  • You could use a function and pass value into that function. – George Apr 21 '22 at 12:50
  • The value doesn't exist until some time in the future (after the button has been clicked) so you can't have it until then. See the duplicate. – Quentin Apr 21 '22 at 13:32

1 Answers1

0

var value will only have a city value when the user clicks the button, so it does not make sense to try to get the value from the variable declared inside button click callback.

You have some possibilities:

  1. Ask jquery for city val again in this line: var pure_value = $("#city").val();
  2. Create a function 'code_using_value(value)' and call this function inside the button callback.
xrodas
  • 466
  • 2
  • 10