Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a value from button to input value

I am trying to pass a value from a button to an input value with Javascript. What i have right now is this

this inside a 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 the script

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

First i tried to make an alert with this code

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

But it didn't alerted anything. Is there any way to pass the value from the button to the input value?

like image 439
Konstantinos Natsios Avatar asked Jan 06 '23 21:01

Konstantinos Natsios


1 Answers

Since you are adding it dynamically you need event delegation here. So just add click as below:

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

DEMO Here

like image 89
Guruprasad J Rao Avatar answered Jan 15 '23 14:01

Guruprasad J Rao