Reputation: 73
I am using jquery-mobile package to develop web based mobile application. From a php script I read the button id's from MySQL and send id's to JavaScript method to create a button for it. However I want to add onclick listener also, ofcourse, but I could not manage it. Any help please.
<div data-role="content2" >
<script type="text/javascript">
function createButton(n) {
$('[data-role="page"]').append('<button data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');// here I want to add onclick listener
}
<?php
include './_fonksiyon.php';
$query = ("
SELECT
tbl_ustmenu.Id AS id,
tbl_ustmenu.AdiT AS adi
FROM tbl_ustmenu
WHERE tbl_ustmenu.Aktif=1
AND tbl_ustmenu.UstMenuId=0
ORDER BY tbl_ustmenu.Sira ASC
");
$result = mysql_query($query);
$count = 0;
while ($count < mysql_num_rows($result)) {
$i = (mysql_result($result,$count, ($id)));
$count++;
?>
createButton(<?php echo ($i) ; ?>);
<?php
}
?>
</script>
</div>
Upvotes: 0
Views: 625
Reputation: 9245
Replace your createButton
with the snippet below, or create a separate function using the same snippet.
<script type="javascript">
var button = document.createElement("INPUT");
button.type = "button";
button.name = "button";
button.value = "Click me";
button.id = "<?php echo $i ?>";
button.onclick = function() {
// ...
// function body
};
// you may append it to any element you need
document.body.appendChild(button);
</script>
Upvotes: 1
Reputation: 609
Save the button to a variable first, it's more readable
var btn = $('<button data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');
btn.click(function() {
alert('here we go');
});
$('[data-role="page"]').append(btn);
Upvotes: 0
Reputation: 763
add a class to your button and create a bind on click, like this:
$('[data-role="page"]').append('<button class="mybuttonclass" data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');
$(".mybuttonclass").on("click",function(e){
//..
});
Upvotes: 0