Why JQuery Datepicker is malfunctioning? - javascript

I have a page where I am adding textboxes using for loop. There is a table in which there will be 12 rows with 4 columns. In 2nd and 4th column, I have added datepicker which is showing up fine.
The problem is when I select a date from datepicker in 2nd column, the date gets set in 2nd column(correct) but when I select a date in 4th column, the date gets set in 2nd column(incorrect).
Here's is my code:
...
<table class="table table-striped">
<tr>
<th><center>Column1</center></th>
<th><center>Column2</center></th>
<th><center>Column3</center></th>
<th><center>Column4</center></th>
</tr>
<?php
for($i=0; $i<count($time_period); $i++) {
$current_table = $table[$i];
$result = $db->query("SHOW TABLES LIKE '$current_table'");
if($result->rowCount() > 0) {
//Table Exists!
?>
<tr>
<td><center><?php echo $time_period[$i]; ?></center></td>
<td><input type="text" class="form-control datepicker" id="<?php echo $i; ?>" autocomplete="off" name="date_receipt[]" value=""></td>
<td><input type="text" class="form-control" id="<?php echo $i; ?>" autocomplete="off" name="cheque_amount[]" value=""></td>
<td><input type="text" class="form-control datepicker" id="<?php echo $i; ?>" autocomplete="off" name="date_deposit[]" value=""></td>
</tr>
<?php
}
}
?>
</table>
...
JQuery Code to Add Datepicker
<script>
$(function(){
$.datepicker.setDefaults(
$.extend($.datepicker.regional[''])
);
$('.datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
});
</script>
I don't know why this is happening. Any ideas?

I have had a similar issue. Try giving them unique IDs and then using the IDs to select them in jQuery.
Reasoning: My guess is that .datepicker returns an array of the nodes, so when it gets clicked, it puts the value into the class.val which will be the first child in the array.
Update in response:
They both have the same id:
id="<?php echo $i; ?>
Not working: http://jsfiddle.net/snlacks/k3hdzLre/3/
Working: http://jsfiddle.net/snlacks/k3hdzLre/4/
Because they both have the same ID, the browser is going to look through the class by ID (even though you didn't pass the ID), because this is faster. The browser assumes IDs are unique.

Related

Javascript function stops after first while loop in PHP

I have some javascript that creates a datetime picker on each row of a table. The function only works on the first row. I understand that the reason for this is that the datepicker shares the same ID on every row. How can I adjust my code to fix this?
<script type="text/javascript">
$(document).ready(function (){
$('#duedate').datetimepicker({
controlType: 'select',
timeFormat: 'hh:mm tt'
});
});
</script>
<?php $txtJob = $_GET['pickjob']; ?>
<?php
$query2 = "Select Work_Center, Sequence, Est_Total_Hrs from V_schedule WHERE job = '" . $txtJob . "'";
$results2 = sqlsrv_query($connPpp, $query2);?>
<form id="frmpromiseddate" name="frmpromiseddate" action="schedule_job_submit.php" method="POST">
<table class='table table-bordered table-condensed table-striped'>
<tr>
<td>Sequence</td>
<td>Work Center</td>
<td>Due Date</td>
</tr>
<?php while ($row2 = sqlsrv_fetch_array($results2)) {?>
<tr>
<td><?php echo $row2['Sequence']?></td>
<td><?php echo $row2['Work_Center']?></td>
<td><input type="text" name="duedate" id="duedate" value="" /> </td>
</tr>
<?php ;} //End of while ?>
</table>
Jquery treats idas unique identifier and apply on only one element at a time, where as it treats class as a group-identifier and can apply to multiple element at a time so change id to class both in html and Jquery code:-
<td><input type="text" name="duedate" class="duedate" value="" /></td>
And
$('.duedate').datetimepicker({
Use class(.) instead of id(#) for date picker
Javascript code :
$('.duedate').datetimepicker()
HTML code: making id unique
<?php $i=0;
while ($row2 = sqlsrv_fetch_array($results2)) {?>
<tr>
<td><?php echo $row2['Sequence']?></td>
<td><?php echo $row2['Work_Center']?></td>
<td><input type="text" name="duedate" class="duedate" id="duedate_<?php echo $i;?>" value="" /> </td>
</tr>
<?php $i++; } //End of while ?>

Event in JS only works on first checklist inside of a foreach

I have a function that monitors a list of checkboxes to detect if some are selected. If some are selected the button shows, otherwise the button hides. The checkbox lies within of a foreach in PHP to transform into a list of checkboxes.
The problem is that only the first checkbox shows the delete button.
agenda.php:
<tbody>
<form id="delTask" name="delTask" method="POST" action="">
<?php foreach ($tasks as $value): ?>
<tr>
<td>
<div class="checkbox">
<label>
<input name="excluir[]" value="<?php echo $value[0] ?>" id="taskSelect" type="checkbox">
</label>
</div>
</td>
<td><?php echo $value[1] ?></td>
<td><span class="label label-success">+50</span></td>
</tr>
<?php endforeach; ?>
</form>
</tbody>
app.js:
// Hide/Show button of del
$("#taskSelect").click(function () {
if( $("#taskSelect").is(':checked') ) {
$("#writeTask").hide();
document.getElementById("deleteTask").style.display = 'block';
} else {
$("#writeTask").show();
document.getElementById("deleteTask").style.display = 'none';
};
});
The problem is that you have many checkbox inputs with the ID taskSelect. Element IDs must be unique throughout the whole document. Instead you will want to use a class name, as the same class can be attached to multiple elements:
<input name="excluir[]" value="<?php echo $value[0] ?>" class="taskSelect" type="checkbox">
You then use a selector like .classname rather than #id in your jQuery click handler:
$(".taskSelect").click(function () {
...
});
As an aside, rather than doing document.getElementById("id").style.display to show and hide things, as your are using jQuery you can just use $("#id").show() and $("#id").hide() throughout.

AJAX Image Upload from an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I need some help with a multiple upload form. I'm using AJAX to upload an image (without a submit button) and display the image after it has loaded. However, my form is repeated multiple times (table rows) so that only the first form works. My php code:
<table class="datatable tablesort selectable paginate full">
<thead>
<tr>
<th>Part</th>
<th>Price</th>
<th>Upload Image</th>
<th>Categories</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Part</th>
<th>Upload Image</th>
<th>Price</th>
<th>Categories</th>
</tr>
</tfoot>
<tbody>
<?php
$breaker_id = $_SESSION['breaker_id'];
$sql = "SELECT * FROM stock where VehicleID='$vehicle' and breaker='$breaker_id'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr id="<?php echo $row['id']; ?>" class="edit_tr">
<td class="edit_td"><span id="first_<?php echo $row['id']; ?>" class="text"><?php echo $row['stock_item']; ?></span><input type="text" value="<?php echo $row['stock_item']; ?>" class="editbox" id="first_input_<?php echo $row['id']; ?>"/></td>
<td class="edit_td"><span id="last_<?php echo $row['id']; ?>" class="text">£<?php echo $row['price']; ?></span><input type="text" value="<?php echo $row['price']; ?>" class="editbox" id="last_input_<?php echo $row['id']; ?>"/></td>
<td>
<div class='preview'>
</div>
<form class="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image
<div class='imageloadstatus' style='display:none'><img src="images/load.gif" alt="Uploading...."/></div>
<div class='imageloadbutton' >
<input type="file" name="photoimg" class="photoimg" />
<input type="text" name="photoimgid" value="<?php echo $row['id']; ?>">
</div>
</form>
<td><?php echo $row['Item_Specifics_Type']; ?> | <?php echo $row['Item_Specifics_SubType']; ?> </td>
</tr><?php } ?>
</tbody>
</table>
And the javascript:
<script type="text/javascript" >
$(document).ready(function() {
$('.photoimg').die('click').live('change', function() {
//$("#preview").html('');
$(".imageform").ajaxForm({target: '.preview',
beforeSubmit:function(){
console.log('v');
$(".imageloadstatus").show();
$(".imageloadbutton").hide();
},
success:function(){
console.log('z');
$(".imageloadstatus").hide();
$(".imageloadbutton").show();
},
error:function(){
console.log('d');
$(".imageloadstatus").hide();
$(".imageloadbutton").show();
} }).submit();
});
});
</script>
You use duplicated id's. Every time you search (in jQuery) e.q. #imageform or #preview it returns the first element that it found with this id!
$("#imageform").ajaxForm({ // Wrong, catch only first #imageform
$(".imageform").ajaxForm({ // Correct, loop over all elements with .imageform class
You have to change it in whole JS code.
-- edit --
Now you run ajaxForm plugin for every .imageform but target is the same in every execution as well as toggled elements in beforeSubmit, success and error functions.
$('.photoimg').die('click').live('change', function () {
var id = $(this).closest('tr').attr('id');
$(this).closest(".imageform").ajaxForm({
target: '#' + id + ' .preview', // type of hack, don't have plugin source ;)
beforeSubmit: function () {
console.log('v');
$(this).find(".imageloadstatus").show();
$(this).find(".imageloadbutton").hide();
},
success: function () {
console.log('z');
$(this).find(".imageloadstatus").hide();
$(this).find(".imageloadbutton").show();
},
error: function () {
console.log('d');
$(this).find(".imageloadstatus").hide();
$(this).find(".imageloadbutton").show();
}
}).submit();
});

Add Rows dynamically having unique input id's in td

The code below displays the 10 rows having three columns. the input id's are type_1,type_2,type_3,type_4,type_5 (and same for the rest two columns room_1 to room_5, quantity_1 to quantity_5).
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php for($i=1;$i<=5;$i++)
{?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php }?>
</thead>
</table>
Now My question is that I have a button ADD 5 ROWS.I want to generate the above rows dynamically each time the button is clicked and at the same time I want to handle the id's of the input like on first click the id's of first column will be type_1 to type_5 and on second click they should be type6 to type_10.
<button class="btn btn-success">ADD 5 ROWS</button>
You shoudl use ajax for such process.
PHP Script:
if( isset($_POST['send_row_request']) )
{
// process the request
$base_id = $_POST['base_id'];
$_SESSION['next_request_base_id'] = $base_id + 5; // setting this for the next request.
// get the data from DB. You have already written the function for you to get
// 5 rows of DB based on a base id give,
$result_array = get_db_data($base_id);
echo json_encode($result_array)
/***
Or if you are not comfortable with JSON you can loop through array and echo them
on each iteration
***/
}
And HERE is the jQuery AJAX :
$(document).ready(function(){
var base_id = $('#base_id').val();
$('myButton').click(function(){
$.ajax({
url : 'url_to_your_php_script',
data : ({send_row_request : 'true', 'base_id' : base_id});
success : function(msg)
{
// do the stuff here and don't forgot to update base_is hidden field on the last record process
}
})
});
});
And here is a simpel HTML. Note that you should save your last row's id of your first five-records into a hidden input with the id of for example #base_id. This value also should be changed on each use click on the button.
<input type='hidden' value='<?php echo $base_id; ?>' id='base_id' />
You can use the php session variable to dynamically create rows among page request:
<?php
session_start();
if(isseet($_POST['your_button_id']))
{
if(isset($_SESSION['row_id']))
$_SESSION['row_id']=$_SESSION['row_id']+1;
else
$_SESSION['row_id']=1;
}
?>
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php if(isseet($_POST['your_button_id']))
{
$row =$_SESSION['row_id'];
for($i=$row;$i<=$row+4;$i++)
{
?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php } $_SESSION['row_id']=$_SESSION['row_id']+4; } ?>
</thead>
</table>

in php how can i generate dynamic id for each input textbox created in while loop

how to get the selected textbox id generated in while loop for updating the field as in phpmyadmin
<?php
while($fet=mysql_fetch_assoc($sql1))
{
?>
<tr>
<td><input type=text id='hello' name='hello' data-id="<?php echo $fet['username']?>" onchange='loadXMLDoc(this);' value=<?php echo $fet['username']?>>
<td><input type=text id='uid' name='uid' onchange='loadXMLDoc(this).' value=<?php echo $fet['id']?>>
</tr>
<?php
}
?>
Just append i and increment it till your while loop goes on..
<?php
$i=1;
while($fet=mysql_fetch_assoc($sql1))
{
echo '
<tr>
<td>
<input type="text" id="hello'.$i.'" name="hello'.$i.'" data-id="'.$fet['username'].'" onchange="loadXMLDoc(this.value,'.$i.')" value='.$fet['username'].' >
</td>
</tr>';
here write ur code for other fields
$i++;
}
?>
<script>
function loadXMLDoc(a,i)
{ var d= document.getElementById("hello"+i).value; }
</script>
Don't use foreach as bellow way.
foreach($sql1 as $value){
// don't generate html here
}
Because it may brake the html
Use foreach bellow way.
<?php
foreach($sql1 as $value):
?>
<tr>
<td><input type=text id='hello' name='hello' data-id="<?php echo $value['username']?>" onchange='loadXMLDoc(this);' value=<?php echo $value['username']?>>
<td><input type=text id='uid' name='uid' onchange='loadXMLDoc(this).' value=<?php echo $value['id']?>>
</tr>
<?php endforeach() ?>
use the uniqid() function
$str=uniqid("uid") it will make some thing like ti uid1hq7266
and print it in the input

Categories

Resources