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>
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>
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);
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){
//..
});
Related
I am having trouble getting my button to click after an ajax call. It works fine before the call. However, when i perform a search and return the data from php, the click event stops working.
I have tried the .on event but this just display the form and not the values. I would be grateful if someone could check my code and see where I am going wrong.
I am aware that the element needs to be in the page and I assumed that after he ajax call the dom would contain the element. Obvously i was wrong.
Many thanks
Order of clicks.
1) page load, .edit click works fine.
2) perform search from #btn-search. Pagintes the table but .edit click is no longer firing.
js code
Get inital values from row. works fine on first click. Not after ajax call to display search results
$(function() {
$('.edit').click(function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
service = currentRow.find("td:eq(1)").html();
activity = currentRow.find("td:eq(2)").html();
dept = currentRow.find("td:eq(3)").html();
company = currentRow.find("td:eq(4)").html();
address = currentRow.find("td:eq(5)").html();
user = currentRow.find("td:eq(6)").html();
item = currentRow.find("td:eq(7)").html();
date = currentRow.find("td:eq(8)").html();
var data = id + "\n" + service + "\n" + activity + "\n" + dept + "\n" + company + "\n" + address + "\n" + user + "\n" + item + "\n" + date;
$("#editForm").dialog("open");
$("#id").val(id);
$("#service").val(service);
$("#activity").val(activity);
$("#dept").val(dept);
$("#company").val(company);
$("#address").val(address);
$("#user").val(user);
$("#item").val(item);
$("#datetimepicker").val(date);
});
});
php backend
<?php
if ($_POST['search1'] == '') {
echo 'enter a search term';
exit;
} else {
$search = $_POST['search1'];
$sqlsrch = mysqli_query($conn, "select * from act where item like '%$search%'");
$numsrch = mysqli_num_rows($sqlsrch);
if ($numsrch == 0) {
// what to do if no results found
echo 'No Results Found';
} else {
while ($rowsrch = mysqli_fetch_array($sqlsrch)) {
$id = $rowsrch['id'];
$service = $rowsrch['service'];
$activity = $rowsrch['activity'];
$dept = $rowsrch['department'];
$company = $rowsrch['company'];
$address = $rowsrch['address'];
$user = $rowsrch['user'];
$box = $rowsrch['item'];
$date = $rowsrch['date'];
$date = date('d/m/Y h:i:s', strtotime($date));
$edit = "<button type='button' class='btn btn-primary edit'>Edit</button>";
$action = "<button type='button' class='btn btn-success action'>Action</button>";
$delete = "<button type='button' class='btn btn-danger delete'>Delete</button>";
// Now for each looped row
echo "<tr><td>" . $id . "</td><td>" . $service . "</td><td>" . $activity . "</td><td>" . $dept . "</td><td>" . $company . "</td><td>" . $address . "</td><td>" . $user . "</td><td>" . $box . "</td><td>" . $date . "</td><td>" . $edit . ' ' . $action . ' ' . $delete . "</td></tr>";
} // End our scale while loop
}
}
?>
jquery search click event
$(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
var search = $("#search").val();
$.ajax({
url: "tabletestajax.php",
method: 'POST',
data: {
search1: search
},
success: function(data) {
$("#search").val('');
$(".paginated tbody").empty();
var result = $.trim(data);
if (result === "enter a search term") {
$("input[name='search']").val(result).css({
'color': 'red'
});
return false;
} else if (result === "No Results Found") {
$(".paginated tbody").html('<div>' + result + '</div>');
return false;
} else {
$(".paginated tbody").html(result);
}
}
});
});
});
Probably you need event delegation
$(document).on('click', '.edit', function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
.
.
}
Resource
Event delegation .on()
I've been searching all over, and actually have found some of similar problem, but still can't manage to solve my problem. I'm still struggling learning jquery and still new.
Anywa, I'm trying to add dynamically an input on a table. So far, I've been able to show the adding of row with the new input text. The input text suppose to have autocomplete function. But the new dynamically added input never succeed to show the autocomplete options.
(To make it clear, I put down the code into JSFiddle, here's the link:
http://jsfiddle.net/yodann/6t74T/637/ )
Here is my code:
<?php
echo '<tr class="row_odd"><td class="ui-widget">';
echo form_input(array('id' => 'aff[]', 'name' => 'aff', 'value' => '',
'class' => 'form-control auto_form', 'placeholder' => 'Masukkan nama tempat',
'style' => 'width:100%'));
echo '</td><td><img src="'.getfrontendlink('images/del_button.png').
'" width="24px" height="auto"></td></tr>';
?>
function addRow() {
var count = $('#aff_table tr').length;
var tx = count % 2 == 0 ? 'row_even' : 'row_odd';
$('#aff_table tr:last').after('<tr class="' + tx + '">' +
'<td class="ui-widget">'+
'</td><td><img src="<?=getfrontendlink('images/del_button.png')?>" width="24px" height="auto"></td></tr>');
var dat = $('#aff_table tr:last').children('td.ui-widget');
$("input.auto_form:last").clone(true).appendTo(dat);
$("input.auto_form:last").val("");
}
<?php
if ($datas != '') {
$i = 0;
$php_array = array();
foreach ($datas->result_array() as $row):
$php_array[$i++] = ($row['pp_id'].'>>'.$row['pp_name'].', '.
(strlen($row['address']) > 25 ? substr($row['address'],0,25) : $row['address']).', '.
$row['city_name'].', '.$row['province_name']);
endforeach;
$js_array = json_encode($php_array);
echo "var availableTags = ". $js_array . ";\n";
}
?>
$( ".auto_form" ).autocomplete({
source: availableTags
});
If I properly understood the problem:
At the end of function addRow() you should init .autocomplete property again.
If you instantiate auto-complete once, then after adding dynamic input field jquery does not automatically add the needed property.
function addRow() {
var count = $('#aff_table tr').length;
var tx = count % 2 == 0 ? 'row_even' : 'row_odd';
$('#aff_table tr:last').after('<tr class="' + tx + '">' +
'<td class="ui-widget">'+
'</td><td><img src="<?=getfrontendlink('images/del_button.png')?>" width="24px" height="auto"></td></tr>');
var dat = $('#aff_table tr:last').children('td.ui-widget');
$("input.auto_form:last").clone(true).appendTo(dat);
$("input.auto_form:last").val("");
$(".auto_form").autocomplete({source: availableTags});
}
tried changing clone to simple append:
http://jsfiddle.net/rk27xbce/
i have display data from xml file to the index.php like this
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent=='image')
{
echo '<div><img src="'.$data.'" ></div>';
echo '<div>';
echo '</div>';
}
elseif($agent=='id')
{
echo '<div class = "Left">';
echo '<input type = "button" name="Agent" id = "'.$data.'" class = "subs-btn" value = "Select this Agent" OnClick = Selected(this.id);>';
$_SESSION['Selected'] = $data;
echo '</div>';
echo '<br/>';
echo '<br/>';
}
else
{
echo '<div class = "inline1">';
echo $data;
echo '</div>';
echo '<br/>';
}
processXML($data);
}
}
processXML($xml);
you guys can see here i am generating a button and onclick function is call - Selected(this.id);
So here is the code of function
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
}
So due to this agent is selected. Now i had one button at the end of the page
<input type = "submit" name="Continue" class = "btn btn-primary right" value = "Continue">
now i want to display data which is related to selected agent on another page. So how can i display this data with respect to selected agent?
Please Help.
You would need to something along the lines of the following. This is more just psuedo code than an actual working example, as I don't know what you want to display about an agent
Note: I am assuming you have jQuery included.
JS
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
//Start here
var AgentData = ""//something about the agent. their id or some other identifier
//here you would make an ajax call to a php script
$.ajax({
type:"POST",
data: AgentData,
url: "someurl"
});
}
PHP
$_SESSION["AgentData"] = $_POST["AgentData"];
Now you would be able to access that data about the selected agent anywhere as long as there is a valid session.
So i have a function that i have build for some kind of repeatable text boxes that i can add and remove with click on a button.
But my problem is that now when i want to have 2 separated repeatable boxes on same page i can't separate click on button event.
This is output i use for repeatable options box.
$output .= '<div class="option">';
$output .= '<div class="vf-sortable-holder">';
$output .= '<div class="vf-sortable vf-repeat-text empty-sortable hidden"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>';
$output .= '<input id="' . esc_attr( $value['id'] ) . '" class="vf-input" data-rel="' . esc_attr( $option_name . '[' . $value['id'] . ']' ) . '" type="text" value="' . esc_attr( $value['std'] ) . '" />';
$output .= '<a class="vf-delete-sortable button" href="#">'. __('Remove') .'</a>';
$output .= '</div>';
$output .= '</div>';
$output .= '<a class="vf-new-sortable button" href="#">Add new</a>';
$output .= '</div>';
And this is js function that i use to add a new text box
//Add new field for repeatable option
$('.vf-new-sortable').click( function(event) {
//Get parent element
var loop = $(this).closest('.option');
// Count all repeat group div's
var count = loop.find('.vf-sortable').not('.empty-sortable').length;
//Add new slide
var new_slide = loop.find('.empty-sortable').clone(true).removeClass('empty-sortable hidden').insertBefore('.empty-sortable');
var input = new_slide.find('input');
var input_name = input.attr('data-rel');
input.attr('name', input_name + '[' + ( count ) + ']');
return false;
});
What this should do is when page is loaded to have one vf-sortable div hidden and when i click on button it should clone it and make another vf-sortable field.
And this works. But problem is when i output 2 or more option div's with sortable boxes on button click it add new vf-sortable box on every option. how do i make event only to work on specific option div where add button is clicked?
you need to change your .insertBefore() to insert before the actual loop.find('.empty-sortable') like this
$('.vf-new-sortable').click( function(event) {
//Get parent element
var loop = $(this).closest('.option');
// Count all repeat group div's
var count = loop.find('.vf-sortable').not('.empty-sortable').length;
//Add new slide
var emptysortable=loop.find('.empty-sortable');//get the element to clone
var new_slide = emptysortable.clone(true).
removeClass('empty-sortable hidden').
insertBefore(emptysortable);//insert only in this .option
var input = new_slide.find('input');
var input_name = input.attr('data-rel');
input.attr('name', input_name + '[' + ( count ) + ']');
return false;
});
http://jsfiddle.net/BCRt3/
"how do i make event only to work on specific option div where add button is clicked?"
Perhaps something like adding an id to each option and then tying the button click to that specific option id.
Ive been figuring out how to enable an array of textbox when their corresponding checkbox is being checked using javascript...
Here is my code:
$line_util3 = "Select id_code,description from WEBLOAN_SERVER.webloan.dbo.mis_group where pid_code='$list_count' and group_no = '0' and child_node = '1' ";
$stmt_line_util3=sqlsrv_query($conn, $line_util3);
if(!$stmt_line_util3) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute($stmt_line_util3);
while ($imps_row1 = sqlsrv_fetch_array($stmt_line_util3,SQLSRV_FETCH_ASSOC))
{
echo "<tr>";
echo "<td><input type='checkbox' name='op[]'></td>";
echo "<td>" . $imps_row1['id_code'] . " - " . $imps_row1['description'] . "</td>";
echo "<td><input type='text' disabled='disabled' name='txt[]'></td>";
echo "</tr>";
}
Thank You very much for the Help
Try this i hope this will help you. Which uses jQuery.
$(document).on('click', 'input[name="op[]"]', function () {
var checked = $(this).prop('checked');// true or false
if (checked) {
$(this).parents('tr').find('td input[type="text"]').removeAttr('disabled');
}
else {
$(this).parents('tr').find('td input[type="text"]').attr('disabled', 'disabled');
}
});
here is updated the Demo
add an onclick event to call a javascript function to ur checkbox then assign id to the different text box whom u want to disable or enable/disaapear or appear.in the following code i am enabling text box with id 'tpnr' and disabling the other text boxes(id:bs,as)
<script type="text/javacript">
function(a){
document.getElementById("tpnr").style.position = "static";
document.getElementById("tpnr").style.top = "0px";
document.getElementById("bs").style.position = "absolute";
document.getElementById("bs").style.top = "-10000px";
document.getElementById("as").style.position = "absolute";
document.getElementById("as").style.top = "-10000px";
}
</script>