Pass value from button to input value

I am trying to pass a value from a button to an input value using Javascript. What I mean right now is

inside javascript file

var test2 = 5;
appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="' + test2 + '">This is it!</button></div>';
$("#test1").append(appendeddatahtml);

And this is the form above script

<input type="text" name="latlon" id="latlon" style="display: none; " value="" />

At first I tried to give a warning using this code

$(document).ready(function() {
  $("#btn").click(function() {
    alert("The button was clicked.");
  });
});

But he warned nothing. Is there a way to pass a value from a button to an input value?

+4
source share
5 answers

Since you are adding it dynamically, you need to . So just add a click as shown below: event delegation

$(document).on('click',"#btn",function(){
    alert("The button was clicked.");
});

Demo here

+6
source

, , live

http://api.jquery.com/on/

:

$(document).ready(function() {
    $(document).on('click', "#btn", function() {
        alert('here');
    });
});
+2

working here just removes $ (document) .ready ()

var test2 = 5 ;
appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>';
 $("#test1").append(appendeddatahtml); 

  $("#btn").click(function(){
    alert("The button was clicked.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="latlon" id="latlon" style="display: none; " value="" />
<div id="test1"></div>
Run codeHide result
+1
source

At first you did not create an element.

You forgot $ ();

var test2 = 5 ;

 appendeddatahtml = $('<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>');
   $("#test1").append(appendeddatahtml);
0
source

link to a working example of what you wanted here

html code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="latlon" id="latlon" style="display: block; " value="" />
<div id="test1">
</div>

javascript code

$(document).ready(function() {
    var test2 = 5 ;
    var appendeddatahtml = '<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>';
                        $("#test1").append(appendeddatahtml);
    $("#btn").click(function(){
        alert("The button was clicked. "+this.value);
        document.getElementById('latlon').value = this.value;
    });
});
0
source

Source: https://habr.com/ru/post/1622736/


All Articles