How to clear content of div container using JS/Jquery? - javascript

I have been developing some page and I need to clear a content of some div:
<table>
<tbody>
<div class="records_content">
<?php
$i=0;
foreach ($records as $record) {
echo "<tr class = 'output' style='border-bottom: 1px dotted silver;'>";
echo "<td width='400'>" . strip_tags($record['language_value']) . "</td>";
if ($record['approved_translation'])
{
echo "<td width='200' height='30'><div class='field' id='".$record['label_value']."/".$record['language_id']."'>".
strip_tags($record['approved_translation']['language_value'])."</div></td><td><button class='btn btn-info' id='{$record['label_value']}/{$record['language_id']}' href='#'>More...</button>"."</td>";
}
else
{
echo "<td width='200'>"."<div id='".$record['label_value']."/".$record['language_id']."'><span class='no_translate'>Not translated</span></div>" . "</td>";
}
echo '</tr>';
$i++;
}
?>
</div>
</tbody>
</table>
Piece of JS code:
$(".page_button").click(function () {
$.post("http://"+document.location.host+"/index.php/welcome/update_records_set/"+this.id,
function(data)
{
alert('123');
$(".records_content").empty();
});
});
This script works, because I see '123' notification, but div container with '.records_content' class isn't clear. Please, tell me, how can I fix it? Thank you.
UPDATE:
Now it works. But I have a new problem with pagination:
<br><b>Page:</b><br/>
<?php
for($i=0; $i<$count; $i++)
{
if ($i==0)
{
echo "<div class='selected_page_button'>".($i+1)." "."</div>";
}
else
{
echo "<div class='page_button'>".($i+1)." "."</div>";
}
}
?>
And code for changing class of button:
$(".page_button").click(function () {
$(".selected_page_button").attr("class", "page_button");
$(this).attr("class", "selected_page_button");
});
It works correctly for all buttons without first. When my page is created the first page is selected. When I click by "2", then "1" is simple and "2" is selected. The same thing is with all buttons without "1": if I click by "2" (or other one) then I can't click by first! "1" changes it's view but doesn't change behavior, because simple button is clickable and selected button is not clickable!

It does clear using .empty() as your code already states, except that it clears after the alert. See here: http://jsfiddle.net/YPLeB/
After you click "OK", the DIV is cleared as expected.

Try this:
$(".records_content").html('');

You'll see the alert happening before the HTML is emptied. Try placing the alert after the .empty() function or use a non-blocking command such as console.log() to debug your code.
Your code itself is correct... only the ordering of the commands is tripping you up...

Related

Why combo box is not getting hide on page load?

I'm trying to hide the combobox on page load. The combobox has not getting hide. I can't find any error on webbrowser's inspect element. I've checked the select tag syntax and javascript all are seems fine. But its not getting hide?
PHP CODE:
<?php
$list=mysqli_query($conn,"select * from emp");
echo "<select id='dropbx'>";
echo "<option value=''>emp Code</option>";
while($row = mysqli_fetch_array($list))
{
echo "<option value='" . $row['emp_code'] . "'>" . $row['emp_code'] . "</option>"; //Why Two column mentioned??
}
echo "</select>";
?>
<script type="text/javascript">
window.onload = function()
{
document.getElementById('dropbx').visibility = "hidden";
//alert('hello');
};
</script>
You have to use the code like this. visibility is the property of the style attribute of the element. You can read more here: https://www.w3schools.com/jsref/prop_style_visibility.asp
document.getElementById("dropbx").style.visibility = "hidden";
you can hide dropdown by using hide() like this :
$("#dropbx").hide();
or you can use display property like this :
document.getElementById("dropbx").style.display = "none";
Another option would be to do it in server side.
echo "<select id='dropbx' style='display:none;'>";
or (if you don't want inline styles)
echo "<select id='dropbx' class='hidden'>";
in your css
.hidden {
display:none;
}

PHP - retrieving all the data corresponding to a radio button

I am using php and have less experience in it. I am displaying data in a table, which has a radio button at the start of each row. I want to retrieve all the data that is present in the row corresponding to the radio button I check.
Here is something what I have done till now:
<form name="test" method="POST">
<table>
<tr>
<th></th>
<th>book_id</th>
<th>card no</th>
<th>fname</th>
<th>lname</th>
</tr>
<?php
$conn = mysql_connect("localhost", "root", "");
if ($conn) {
mysql_select_db("library");
} else {
echo 'no such database';
}
$query_test = "select book_id2,a.card_no,fname,lname from book_loans a, borrower b where a.card_no = b.card_no ";
$result = mysql_query($query_test);
if ($result === FALSE) {
mysql_error();
} else {
while ($rows = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='test'></td>";
echo "<td>" .$rows['book_id2']. "</td>";
echo "<td>" .$rows['card_no']. "</td>";
echo "<td>" .$rows['fname']. "</td>";
echo "<td>" .$rows['lname']. "</td>";
echo "</tr>";
}
}
?>
<input type="submit" name="test_val" value="submit"/>
</table>
</form>
Here I want to print the data i.e. book_id, card_no, fname, lname as the submit button is clicked:
<?php
if($_POST)
{
if(isset($_POST['test_val']))
{
// TO PRINT THE DATA CORRESPONDING TO THE RADIO BUTTON
}
}
?>
Add hidden input fields in each of the <td> rows. For example:
echo "<td>".$rows['book_id2']."</td><input type='hidden' name ='book_id2' value='".$rows['book_id2']."' />";
I've tried writing the JavaScript but this is much easier in JQuery. Add these scripts before the end of the closing </body> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var toggleInput = function(){
$('input[type=hidden]').prop('disabled', true);
var selection = $('input:checked').eq(0);
selection.parent().parent().find('input[type=hidden]').each(function(){
$(this).prop('disabled',false);
});
}
$(form).on('submit',toggleInput);
</script>
JQuery is used a lot in manipulating the DOM like this. It cuts out a lot of the repetition that can be seen in JavaScript. Although if it is easier to do something with just JavaScript, then do it!
On form submission, we're disabling all hidden elements. Then we find the active radio box, and activate the hidden elements corresponding to the radio box.
This is one solution and might need to be tweaked. JavaScript and JQuery are your friends for this problem.
You could add the data as the value attribute of your radio button
echo "<input type='radio' name='test' value='".$rows['book_id2']." ".$rows['card_no']." ".$rows['fname']." ".$rows['lname']."'>";
Then the name of the post variable will be the name of the radio button
if(isset($_POST['test']))
{
echo $_POST['test'];
}
Another example, to access individual values:
echo "<input type='radio' name='test' value='".addslashes( json_encode($rows) )."'>";
if(isset($_POST['test']))
{
$result = json_decode( stripslashes($_POST['test']) ) ;
echo $result->book_id2;
echo $result->card_no;
echo $result->fname;
echo $result->lname;
}
Try implementing this:
Create a hidden textarea (which will be holding data corresponding to the radio button)
Assign a dynamic id (unique) to the <tr> and <td> and once the respective radio button is clicked, create JS function which will capture all the data w.r.t the row and if a new radio is clicked, it will clear out the old data and replaces it with new.
Submit the data and you can capture that required data.
Functions you wil require (Inbuilt and User Defined):
1 $( "#tr_unique td_unique" )[.text()][1]; // text() Since you are storing data in td else it would be val()
2 insertData(number){
// Here number is the row # through which you'll track corresponding data
}
3 $( "#hidden_textarea" )[.val][1]('data')
See, if that helps.

Rendered first Javascript before PHP

Assuming in PHP file there're :
function printAllRows(){
for( everyrows in db){
echo "<tr>";
echo "<td> $_POST['..'] <td>";
echo "<td> $_POST['..'] <td>";
echo "<tr>";
}
}
function printSpecifRows($keyword){
.....
}
// When the page loads for the first time
if ($db->preRow() >0){ // count rows in DB , if there already show them as table
printAllRows();
}
At the same time , there is
<input type="text" name="keywoard" />
<input type="submit" name="find" value="search" />
If the user enter the keyword press the button , then just show the rows match the keyword!
so :
if( $_POST["find"]){
?>
<script>
// first clear the current DOM table
document.getElementById("myTable").innerHTML="";
</script>
<?php
// then print again! according to printSpecifRows($keyword)
function printSpecifRows($keyword){
.....
}}
But the problem here is that JS is rendered first before PHP , so printSpecifRows($keyword) won't never be reached , any idea. I really appreciate your help. Thanks.
You are massively over-complicating things. Get rid of the <script> entirely. There is no need or point in involving JS here.
Just change the PHP so it doesn't output all the data in the first place if you don't want it on the page.
if ($_POST["find"]){
printSpecifRows($_POST["find"]);
} else {
printAllRows();
}

Making .next() element slideToggle correctly with jquery?

At the moment, The code below only works for one container. I am looking to make only the description associated with that click slideToggle.
jquery:
$("#closedImage").click(function(){
$('#closedImage').css("display", "none");
$('#openImage').css("display", "block");
$(this).parent().next(".jobDescription").slideToggle("slow");
});
$("#openImage").click(function(){
$('#openImage').css("display", "none");
$('#closedImage').css("display", "block");
$(this).parent().next(".jobDescription").slideToggle("slow");
});
php/html - contents within foreach loop:
echo "<div id=\"theJob\">";
echo "<a href=\"/job/view/".$job['id']."/".$job['url']."\">";
echo "<div id=\"leftContain\" class=\"floatLeft\">";
echo "<h2 class=\"green\">".$job['role']."</h2>";
echo "<div class=\"blue floatLeft\"><h3>".$job['company']." in ".$job['location']."</h3></div><br><br>";
echo "</div>";
echo "</a>";
echo "<div id=\"rightContain\" class=\"floatLeft\">";
echo "<div id=\"closedImage\"><img src=\"/images/side.png\"></div>";
echo "<div id=\"openImage\"><img src=\"/images/down.png\"></div>";
echo "</div>";
echo "<div class=\"jobDescription floatLeft\">";
echo $job['description'];
echo "</div>";
echo "</div>";
Thanks in advance.
You're using a foreach with ids not classes. The selectors in your jquery will only return the first id it comes across, the rest will be ignored.
IDs should never appear more than once on a page and is invalid markup.
Change the IDs to classes and it should fix your issue :)
Hope this helps.
It seems like you are duplicating the ids closedImage and openImage etc in your containers. instead turn them to/add classnames and try .
$(".closedImage").click(function(){
var $this = $(this);
$this.hide().siblings('.openImage').show();; //hide and show are shortcuts to display none / block
$this.parent().next(".jobDescription").slideToggle("slow");
});
$(".openImage").click(function(){
var $this = $(this);
$this.hide().siblings('.closedImage').show();;
$this.parent().next(".jobDescription").slideToggle("slow");
});
Use ids sparingly and turn them into classes. Duplicate ids make your html invalid and selectors to fail as they will select the first one appearing in DOM

javascript does not work with pagination

am doing pagination of table in php with phtml.The problem is I have a javascript to change the color of the row.It works only for my first page,doesnt work with other pages.
foreach($this->paginator as $record)
{echo "<td width='61'> <a href='#' class='test' data-id='" . $record['id']. "'>". $record['id'] . "</td>";
echo "<td width='61' >". $record['firstname'] . "</td>";
echo "<td width='61'>" . $record['emailid'] . "</a></td>";
echo "<td width='38'>" . $record['customdata'] . "</td>";
}
Javascript is
function approve(id) {
var id =id;
$.ajax({
url: 'http://localhost/feedback/public/index/approve/',
type: 'POST',
data:"id="+id,
success:function(data) {
alert('Approved successfully');
var index =parseFloat(id)+1;
$('table tr:eq('+index+')').css("background-color", "54FF9F");//this works only for first page
}
})
}
I'm calling javascript in onclick of a button in popup window.Can anyone help me y it doesnot work for other pages
Your success function is what is coloring the rows; by adding inline styles to the tr tags themselves. Because this function (in all likelihood) does not run again when you go to the next page of your table, the newly rendered rows do not get colored.
I would recommend adding a class to the rows instead, and adding the CSS rule to a stylesheet.
$('table tr:eq('+index+')').addClass('alt-row');
CSS:
.alt-row td { background-color: #54FF9F; }
Also, to play it safe, I apply background colors to cells, not rows, as some older browsers do not support backgrounds on table rows.

Categories