Reputation: 2924
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?
Upvotes: 4
Views: 1816
Reputation: 724
link to a working example of what you wanted is 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;
});
});
Upvotes: 0
Reputation: 55
You have not created the element first.
You forgot $();
var test2 = 5 ;
appendeddatahtml = $('<div class="test1"><button id="btn" type="button" value="'+test2+'">This is it!</button></div>');
$("#test1").append(appendeddatahtml);
Upvotes: 0
Reputation: 4597
working here just remove $(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>
Upvotes: 1
Reputation: 29683
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.");
});
Upvotes: 6
Reputation: 17653
It seems you have created the button dynamically via code during runtime and for such elements you need to use live or on events
this one will help
example:
$(document).ready(function() {
$(document).on('click', "#btn", function() {
alert('here');
});
});
Upvotes: 2