Cannot get element id in javascript inside for loop - javascript

I am trying to use getElementById() inside loop as the id of my each div I want to get is in sequence like total_comments1, total_comments2, total_comments3,.. and so on. This ids are assigned by output using php.
Here is my code to display my div:
<?php
$i=0;
while( $row = mysqli_fetch_assoc($ret) ):
$i++;
?>
<tr>
<td class="col3 col">
<div id="<?php echo "total_comments".$i ?>"></div>
</td>
</tr>
Here is my javascript code:
<script>
for(var i in (result.response)) {
var a=document.getElementById("total_comments" + i );
a.innerHTML = result.response[i].posts;
}
</script>
When I use only "total_posts" in document.getElementBy ID it does not give any error. But when I use "total_posts"+i it gives error on next line. Cannot set property 'innerHTML' of null

Array have starting index from 0.
In your case, you are incrementing $i before assigning.
That is causing your ids start from 1 not 0
You should increment it after assigning.
Corrected code:
<?php
$i=0;
while ($row = mysqli_fetch_assoc($ret)):
?>
<tr>
<td class="col3 col">
<div id="<?php echo "total_comments".$i ?>"></div>
</td>
</tr>
<?php
$i++;
endwhile;
?>

The problem is on your php cycle, try to change it like this:
<?php
$i=0;
while($row = mysqli_fetch_assoc($ret) {
echo '<tr><td class="col3 col">'
.'<div id="total_comments'.$i.'"></div>'
.'</td></tr>';
$i++;
}
?>

Related

How to use PHP loop variable in javascript?

I have run an SQL statement to get all the records I need to show in a HTML table.
I have then run a while loop to display the records from the database. (The code for this is below.)
<table class="projects-table">
<tr>
<th>Complete?</th>
<th>Paid?</th>
<th>Project Name</th>
<th>£ / hr</th>
<th>End Date</th>
<th>Hours Logged</th>
<th><i class="fa fa-trash"></i></th>
</tr>
<?php
$select_id_jobs = mysqli_query($mysqli, "SELECT id FROM users WHERE username='$login_user'");
while($row = mysqli_fetch_array($select_id_jobs)) {
$id_jobs = $row['id'];
}
$select_jobs_with_usrid = mysqli_query($mysqli, "SELECT * FROM jobs WHERE username_id = '$id_jobs';");
while($row = mysqli_fetch_array($select_jobs_with_usrid)) {
?>
<tr id="<?php echo $rowId; ?>">
<td>
<!-- Complete Checkbox -->
<input type="checkbox" id="<?php echo $completeCheck;?>" onclick="compTask();">
</td>
<td>
<!-- Paid checkbox -->
<input type="checkbox" onclick="paidTask()">
</td>
<td>
<?php echo $row['project_title']; ?>
</td>
<td>
<?php echo $row['cost_hour']; ?>
</td>
<td>
<?php echo $row['completion_date']; ?>
</td>
<td>
<?php echo $row['time_spent']; ?>
</td>
<td>
<div class="delete-btn"><a onclick="deleteTask()">DELETE</a></div>
</td>
</tr>
<?php } ?>
</table>
As you can see from the checkbox for completing a task. What I want to do is use javascript so that when the checkbox is checked the text from the other records turns green.
I have included the javascript I am trying to use below. I don't know why but I can't access the inputs ID in order to change the css.
<script>
function compTask() {
if (document.getElementById("<?php echo 'complete-' . $row['id'] ?>").checked == true) {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "green";
alert("hello");
} else {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "black";
}
}
Okay easy way to do that is to print id as parameter in js function
something like that:
<input type="checkbox" id="<?php echo $completeCheck;?>"
onclick="compTask( '<?php echo $row['id'];?>' );">
and in js function deal with id from parameter:
function compTask(id) {
if (document.getElementById('complete-' + id).checked == true) {
document.getElementById('tr' + id).style.color = "green";
alert("hello");
}
}
Hy,
You need to add id in onclick="deleteTask('<?php echo $row['id']; ?>')">
Now in you function have id:
function deleteTask(id) { console.log(id) }

Looping through HTML table and store td values as a string using jquery / javascript

I have following table
while($row=mysql_fetch_array($sql))
{
$id=$row['product_id'];
$name=$row['name'];
$stock=$row['stock'];
?>
<tbody>
<tr >
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $name; ?></span>
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php if($stock==0){echo 0;}else{echo $stock;} ?></span>
</td>
<td class="edit_td1" id="<?php echo $id; ?>">
<div class="form-group">
<div class="col-lg-3 inputContainer">
<input class="form-control cls-quantity" id="quanti_<?php echo $id; ?>" name="number" type="text" />
</div>
</div>
</td>
<td class="action_td" id="<?php echo $id; ?>"><span class="glyphicon glyphicon-remove" style="cursor:pointer;color:red;"></span></td>
</tr>
</tbody>
<?php
}
?>
And button:
Generate Bill
Question: Here I want to return a function store_value_as_string(); after td_validation(); which loop through all <tr> and get id of class="edit_td1" and associated value of id="quanti_<?php echo $id; ?>". Then function store_value_as_string(); will gives me two strings
str1 = 121,122,123,124;//id of class="edit_td1"
str2 = 2,3,1,4;//associated value of id="quanti_<?php echo $id; ?>"
these two strings are required for ajax call(pass to other php page).
I actually have code for doing same but it runs onchange of ".edit_td1" but the sequence of operations by -->tester<-- i.e. onchange-blur(leave the textbox for same <tr> -onchange-blure-onchange... gives me wrong output.
Table look likes:
You might wanna use the Jquery each. Iterate over all td's with the class '.edit_td1'. Fetch their id's using .attr('id') and add to an array as well and then later use Jquery's Array join to get your desired output of str1.
For str2 with each loop, find input with the class '.cls-quantity' and get its value. Add that number to a list and then again use Array.join.
I hope my code works fine. Haven't debugged it.
function store_value_as_string(){
var array1= new Array();
var array2 = new Array();
$('td.edit_td1').each(function(index, element){
//Not sure if we need this line.
//Might need if we dont get the element in function's argument
//var element = this;
array1.push($(element).attr('id'));
//find might return an array so can use this line. I have not debugged it.
array2.push($(element).find('input.cls-quantity')[0].val())
//array2.push($(element).find('input.cls-quantity').val());
});
var str1 = array1.join(',');
var str2 = array2.join(',');
}

single id alerting same time in a while loop

I am having a table from where i am fetching activities and displaying in a table ...like this
<table width="1000px;" style="border:0px;" >
<tr>
<?php
$sql_activities="select * from tb_activities";
$query_activities=mysql_query($sql_activities);
while($row_activities=mysql_fetch_array($query_activities))
{
?>
<td width="50">
<input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="activities" onclick="hi() " id="activities" /><?php echo " ".$row_activities["activity_name"]; ?></td>
<?php
}
?>
</tr>
</table>
Now i have applied it in an onlick event of a radio button and the script for the function is:
<script type="text/javascript">
function hi()
{
a = document.getElementById("activities").value;
alert(a);
}
</script>
i want to alert the name of the activity chosen but when i click on any activity, it shows the same. The first activity.ven if i have clicked on any other activity...can anyone help me ??
what you should do is change this:
onclick="hi()"
to this:
onclick="hi(this);
then your function would be:
function hi(who) {
var a = who.value;
alert(a);
}
In PHP side of things change:
<td width="50"><input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="activities" onclick="hi() " id="activities" /><?php echo " ".$row_activities["activity_name"]; ?></td>
To: ( YOU NEED Unique IDs on Input/ Radio Buttons to be generated dynamically & Sent to JS)
<?php $i = 1; ?>
<td width="50"><input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="<?php echo $row_activities['activity_name'].$i; ?>" id ="<?php echo $row_activities['activity_name'].$i; ?>" onclick="hi("<?php echo $row_activities['activity_name'].$i; ?> ")" /></td>
<?php $i++; ?>
In Javascript Change to This:
function hi(elementID) {
var value = document.getElementById(elementID).value;
alert(value);
}
Code may have some escape errors, but logically this should give you idea how to do it, Hope that helps.

Removing a tr widens other tds

I am trying to remove a table row in Javascript but when the row does disappear, the first column of the table widens, I can't figure why.
Does anyone can help me?
Here is my HTML:
<table id="todos">
<?php foreach ($todos as $row) : ?>
<tr todoid="<?php echo $row['id']; ?>">
<td class="isDone"><input type="checkbox" name="done" /></td>
<td class="title" <?php if ($row['dueDate'] == null) echo "colspan='2'"; ?>><i class="delete fa fa-trash-o"></i> <?php echo $row['title']; ?></td>
<?php if ($row['dueDate'] != null) : ?>
<td class="dueDate"><?php echo relativeDate($row['dueDate']); ?></td>
<?php else : ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</table>
And here is my js:
$("tr[todoid] td.title .delete").click(deleteTodoHandler);
...
function deleteTodoHandler(event) {
console.log("deleteTodoHandler");
$(event.target).parents("tr").remove();
}
Thanks!
If you do not specify widths of the cells, they will expand to fit the content.
I removed the top row and the other rows adjusted since the second cell did not need a lot of space due to the large string.
If you do not want the shifting to occur, you need to set widths.

Onchange pop out error javascript

I try to auto calculate the input without any button. I try to do it with javascript onchange function.However, javascript keep pop out the error and I do not know how to solve it.
This is the error : Uncaught SyntaxError: Unexpected identifier
below is my code :
<!DOCTYPE html>
<html>
<script>
function jsfunction()
{
var x=document.getElementById("qty1");
var y =document.getElementById("price1");
var z =document.getElementById("total1");
alert("You entered: " + y.value);
}
</script>
<body>
<?php
$item=array("A"=>"10","B"=>"11","C"=>"12","D"=>"13");
$var=1;
$total=0;
$gtotal=0;
?>
<table border=1 width='600'
<tr>
<th>No</th>
<th>item</th>
<th>Check</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>";
<?php
foreach($item as $myItem=>$pricetag){
echo "<tr>";
echo "<td>".$var."</td>";
echo "<td>".$myItem."</td>";
$price = "price". $var;
$qty = "qty". $var;
$total = "total". $var;
?>
<td><input type="checkbox" id="chkbox" name="chkbox"/></td>
<td><input type="text" name=<?php $price ?> id=<?php $price ?> size =1/><?php echo $price ?> </td>
<td><input type="text" onchange="jsfunction() name=<?php $qty ?> id=<?php $qty ?> size =1/><?php echo $qty ?></td>
<td><input type="text" name=<?php $total ?> id=<?php $total ?> size =1/></td>
<?php
$var++;
}?>
</table>
</form>
</body>
</html>
Well, there are a few problems:
You never have the closing > of the <table> tag:
<table border=1 width='600' => <table border=1 width='600'>
You have a random "; when the code is not even PHP nor JavaScript:
<th>Total</th>
</tr>";
You are using the PHP tag as an echo tag:
<?php $price ?> => <?php echo $price ?>
You never close the double quotes when calling your JavaScript function:
onchange="jsfunction() => onchange="jsfunction()"
EDIT:
If your name property is NULL, it may cause problems because the id will be set to the name, so you should wrap the name in quotes (Just to be safe you should probably do it with everything including id, size, name, etc.):
name=<?php $price ?> => name="<?php $price ?>"
Among other things, this line has a JavaScript error:
<td><input type="text" onchange="jsfunction() name=<?php $qty ?> id=<?php $qty ?> size =1/><?php echo $qty ?></td>
It should probably be:
<td><input type="text" onchange="jsfunction()" name="<?php echo $qty; ?>" id="<?php echo $qty; ?>" size="1" /><?php echo $qty; ?></td>
You must use the echo function to print out a PHP variable to the HTML.
Also, throughout your HTML form, don't forget to wrap all the input parameter values in quotation marks (" ").
What is the value of $price? You are getting element's by their id, e.g. price1, but if $price is not equal to the string 'price1' it will fail to get an element by that id and your javascript will be calling into a null value.

Categories