Run Jquery Slide Toggle on while elements - javascript

I have a problem in running jquery . Here the table sample:
table database
id | name | value
1 data1 10
2 data2 20
3 data3 30
4 data4 40
5 data5 50
Here is my code:
<?php
$sql = "SELECT * FROM database ORDER BY id"
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{?>
<div id="flip">
<?php echo $row['name']?>
</div>
<div id="panel">
<?php echo $row['value']?>
</div>
<?php
}
?>
But the slide toogle jquery only execute once, on the first element. How to make slide toggle execute every row in while looping?
Here is my slidetoggle()Jquery:
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
And the CSS :
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>

Based on Jack A. answer, build first your HTML with classes instead of multiples IDs. Then, in your script, use jQuery.next() to find the next panel element and toggle it:
$(document).ready(function(){
$(".flip").click(function(){
$(this).next('.panel').slideToggle("slow");
});
});
Here is a jsfiddle illustrating this.

You are using the same id in multiple elements. Build a unique id for every element. E.g. flip1, flip2, etc. and panel1, panel2, etc.

You are creating multiple HTML elements with the same ID ("flip" and "panel"), which is not correct; IDs should be unique.
An alternative is to use a class instead of an ID:
while($row = $result->fetch_assoc())
{?>
<div class="flip">
<?php echo $row['name']?>
</div>
<div class="panel">
<?php echo $row['value']?>
</div>
<?php
}
JavaScript:
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
This will act on all of the elements simultaneously.

Related

Retrieving and Formatting Data Properly From MYSQL

Okay so I'm trying to create a replica of the Billboard Hot 100. I have already a database and the page with the proper format I want. But when I tried to retrieve the data from the database, the format I used became a huge mess and a lot of errors appeared.
Here's my code:
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
while($row = mysqli_fetch_array($songQuery)) {
$i = 2;
foreach($songQuery as $songId)
echo "<li class='chartsRow'>
<div style='width:10%;height:100%;float:left; text-align: center;color:black;font-size: 40px;line-height: 150px;font-weight: 600;'>$i</div>
<img style='height: 30%; float: right; position: relative; top: 50; right: 89%;'src='" . $row['movement'] . "'>
<img type='button' style='float: right;width: 25px;position: relative;top: 60;'onclick='myFunction()'src='assets/icons/expand.png'>
<div style='width:90%; height:100%; display: block;''>
<div style='width:15%;height:100%;float:left'>
<img style='height: 90%;margin-top: 8;'src='". $row['coverArt'] . "'>
</div>
<div style='width:85%; height: 100%;margin-left: 26%;''>
<a style='font-size: 30px; font-weight: 600; position: relative; top: 30;'>" . $row['title'] . "</a>
<p style='position: relative;top: 10;''>" . $row['artist'] . "</p>
</div>
</div>
<div id='moreinfo'>
<div class='lefty'>
<a>" . $row['lastWeek'] . "</a>
<p>LAST WEEK</p>
</div>
<div class='lefty' style='border-left-style: solid;border-left-width: 1px;border-right-style: solid;border-right-width: 1px;border-right-color: #b7b7b7; border-left-color: #b7b7b7;'>
<a>" . $row['peak'] . "</a>
<p>PEAK POSITION</p>
</div>
<div class='lefty'>
<a>" . $row['woc'] . "</a>
<p>WEEKS ON CHART</p>
</div>
</div>
</li>";
$i = $i + 2;
}
?>
</ul>
</div>
Current Issue:
"Warning: mysqli_fetch_array() expects parameter 1 to be
mysqli_result, boolean given in C:\xampp\htdocs\billboard\hot-100.php
on line 52"
What I'm trying to achieve is something that looks like this: https://www.billboard.com/charts/hot-100 but with the rows from 2-100 taking up 60% of the screen and a lower portion that can appear/disappear when clicking the extend icon.
Not sure what all the errors are but the main issue here is that you need to turn on error reporting and check for connection errors before trying to use the query and then also check for errors after running the query but before accessing the result set.
I have removed the inner foreach loop because it is redundant. You can create a counter by simply incrementing a variable. See comments in code.
<?php
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Turn MySQL errors into PHP exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// I assume you have a procedural-style connection setup here.
$con = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$counter = 0;
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
// Now, check if your query has an error
if ($songQuery === false){
die('Error in query: ' . mysqli_error($con));
}
while ($row = mysqli_fetch_array($songQuery)) {
// Your HTML appears to be malformed. I'm getting all sorts of errors in my IDE.
// Removing the HTML here but you should be able to merge that back in without issues.
// If you need a counter to display row numbers, you can just create one.
// Notice I created a $counter variable above.
// increment it by:
// $counter++; to increment by 1 OR
// $counter = $counter + 2; to increment by 2
// Now, use $row['column_name'] where you need it.
} ?>
</ul>
</div>
EDIT
Sounds like you're also having CSS/styling issues. Get the DB query going first and then ask a new, specific question with more details including screen shots.

Apply hover statement to this item from php value?

I'm having some post in php, my table is configuring like this:
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$id = $row['id'];
$title1 = $row['title1'];
$thumb = $row['thumb'];
$link = $row['link'];
$hex = $row['hex'];
$archiveID= $row['archiveID'];
$recordListingID= $row['recordListingID'];
?>
With that, each item have a specific image, color, etc
Which I display int he front-end like that:
<div id="artist-image">
<img src="<?php echo $thumb ?>"></img>
</div></a></li>
<?php
}
?>
On hover a title, the image of the post display, using jquery:
$('#artistlistdesktop ul li a').hover(function(){
$(this).children('#artist-image').toggleClass('active');|
It's all working fine, but what I'm trying to achieve is on hover a title, to change the color of the title with the hex color assign previously in php via $hex = $row['hex'];
I tried the following css:
#artistlistdesktop li > a:hover{
color:#<?=$hex?>;;
}
but it's changing into the same color to all the list instead of the color assign.
Do you know how can I achieve this?
----EDIT ----
original color is light grey which is this css:
#artistlistdesktop li > a {
display: block;
text-decoration: none;
font-family: Arial Black, Arial, Helvetica, sans-serif;
color: rgba(146,146,146,0.5);
font-weight: bolder;
line-height: 35px;
font-size: 53px;
letter-spacing: -5px;
padding: 0;
margin: 0;
}
--EDIT 2 --
I got it via:
<li><a onMouseOver="this.style.color='#<?php echo $hex ?>'"
onMouseOut="this.style.color='rgba(146,146,146,0.5)'"
id="" target="_blank" href=" ">
You should apply style=":hover{color: #<?=$hex?>;}" in your object !
First of all, img is a self-closing tag. Check example here.
What's more, are you sure that the $hex value is a string?
I've tested and it seems to be working like that:
<?php
$id = 1;
$link = "http://example.com";
$title1 = "This is a link";
$hex = "ff0000";
?>
<style>
li > a:hover{
color:#<?=$hex?>;
}
</style>
<li><a id="<?php echo $id ?>" target="_blank" href="<?php echo $link ?> "><?php echo $title1 ?></a></li>
EDIT: https://jsfiddle.net/goran90/z1e7d3mv/1/ - Here's an alternative for what you are trying to achieve. Although, it's not a best practice, but in your case it should do the trick. You only need to set a data attribute with the corresponding color for each a element.

How to create interactive images with PHP, Javascript/Jquery?

I am trying to make code that lets me add checkmarks to clicked images from my database. I am able to get the images to display, however I am unable to select the image/get the check to appear.
index.php
<?php
$result = mysql_query("select * from db");
$count = 0;
while ($row = mysql_fetch_array($result)) {
$count++;
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['img']) . '" width="290" height="290" class = box>';
}
?>
click.js
$(document.ready(function(){
$('.box').live("click", function() {
if($(this).find('.check_image').length == 0){
$(this).append("<div class='check_image'><img src='check.png' /></div>");
}else{
$(this).find('.check_image').remove();
}
});
Ok so I would suggest getting CSS to do display the tick. It will mean wrapping your echoed img tab in a div (you can't use the pseudo selector :after directly on an img tag alas. I have used a font library (font-awesome) this is a great way of getting icons like ticks and trashcans etc into your pages. They scale and can be coloured.
as has been mentioned in other posts you are using some depreciated calls in both your PHP and jQuery. Have a play with this:
$('.clickable').on('click',function(e){
$(this).toggleClass('clicked');
})
.clickable.clicked:after{
font-family: FontAwesome;
content: "\f00c";
color:lime;
position:absolute;
top:2px;
right:2px;
font-size:40px;
text-shadow: -2px 3px 2px rgba(150, 150, 150, 0.8);
}
.clickable{
cursor:pointer;
position:relative;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickable" style="width:320px;height:240px;">
<img src="http://www.richardhulbert.com/wp-content/uploads/2011/04/New-Forest-11.jpg" alt="nice van bros!" />
</div>

Change Height of Div After Ajax Call

PROBLEM:
I have a dynamic form that is using JQuery steps to make it a wizard. Right now, there is a step where a drop down box selection triggers an AJAX call that then adds form fields to the form. I need the height of the div that this field is in to become longer based off of the amount of fields added.
IMAGES:
The form starts with two drop downs:
Once something is selected for the second dropdown, the AJAX call is made and the form appends fields.
The grey box should resize to accomodate the appended fields.
CODE:
The CSS for the div is as follows:
.wizard > .content
{
background: #eee;
display: table-cell;
margin: 0.5em;
min-height: 35em;
position: relative;
width: auto;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
I can add a permanent height here, but it's not dynamic.
The form is a Zend Form, so the HTML is as follows:
<div class="container-fluid">
<?php if ($this->error) : ?>
<div class="row-fluid">
<?php echo $this->error; ?>
</div>
<?php else : ?>
<?php echo $this->form()->openTag($form); ?>
<h3>Details</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_NAME, false, true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DUE_DTTM, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DESCRIPTION); ?>
</section>
<h3>Options</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_REVIEW_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WTL_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_JOB_TABLE); ?>
</section>
<h3>Project Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_TYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_SUBTYPES, !($this->uberAdmin)); ?>
<?php
echo $this->partial('project/project/dynamicFormElements.phtml', array('form' => $this->projectForm, 'div' => 'project-config-elts'));
?>
</section>
<h3>Workflow Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_TYPES, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_SUBTYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_WORKFLOW_CONFIG, !($this->uberAdmin)); ?>
</section>
This generates HTML with the structure below:
The highlighted div is the div in question.
My AJAX call is done here:
// Handle AJAX dynamic form creation results
function updateProjectForm(resp) {
$('div#project-config-elts').html(resp.html);
}
// Handle ajax error
function projectFormError(req, status, err) {
var errorString = '<div class="row-fluid alert alert-error">' +
'Error retrieving project form.' +
'</div>';
$('div#project-config-elts').html(errorString);
}
// AJAX request to get dynamic Project config form
function requestProjConfigForm() {
var request = {project_type: $('select[name=project_types]').val(),
project_subtype: $('select[name=project_subtypes]').val()
};
var ajaxOptions = {
url: 'projectform',
type:'POST',
dataType: 'json',
success: updateProjectForm,
error: projectFormError,
data: request
};
// Initiate the request!
$.ajax(ajaxOptions);
}
$('select[name=project_types]').change(function(){
updateProjectSubtypes();
});
// Handle a change in the selection of the particular project
$('select[name=project_subtypes]').change(function(){
requestProjConfigForm();
});
$('select[name=workflow_types]').change(function(){
updateWorkflowSubtypes();
});
$.validator.addMethod("validJSON", function(val, el) {
try {
JSON.parse(val);
return true;
} catch(e) {
return false;
}
}, "*Not valid JSON");
form.validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "label[for='" + element.attr( "id" ) + "']" )
.append( error );
},
rules: {
project_config: { validJSON: true }
}
});
I'm thinking that here I can dynamically change the height, but I'm not quite sure how to do so.
It looks like you're running into an issue that has been discussed on the jQuery Steps plugin github page: https://github.com/rstaib/jquery-steps/issues/147
basically, since the body of the step content is positioned absolutely with a percent height, it's height is no longer based on the content within it. A few things people used to try to fix this are:
By waqashsn:
.content > .body{
/*position: absolute*/
float:left;
width:95%;
height:95%;
padding:2.5%
}
Here's another alternative by AneeshRS that instead causes overflowing content to scroll:
.wizard.clearfix > .content.clearfix{
min-height: 500px;
overflow-y: auto;
}
Checkout the link to the issues page for a better explanation of either of these. Note however that any solution that involves removing the absolute positioning will likely cause transitions to no longer work.

change position depending on DB value

I let people fill in a form, and insert distances etc. They get stored in a db.
Then I lead them to a page, where I show the number of axles (12 in this case) and make a circle of them (in css)
Then it looks like this:
The code for this:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position">
<?php
foreach($show_axle as $axlefigure){ ?>
<div id='number_of_axles'> <?php echo $axlefigure['axle'] ?></div>
<?php
}
?>
</div>
</div>
The axle_border make the Train image (The black rectangle)
The axle_position take care that the axles (Numbers actually) Don't go in the image but slightly below it (So it looks like wheels/axles).
The Number_of_axles make the numbers look like a circle (Like wheels/axles).
Now the function:
function axles($id){
$sql = "SELECT * FROM axle WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
The function selects everything from the table axle (See first image).
Now, I actually want the axles to take a position. And I'm thinking about doing that via the Distance row.
So:
Axle 1 has the number 5 for distance. So it goes 5px from the far left
Axle 2 has the number 10. So i want it 10 pixels next to the axle 1.
Axle 3 has the number 5. So i want it 5 pixels next to the axle 2.
Etc.
Eventually it needs to look like this:
My question: Is this posible. If yes, how?
EDIT:
it is working now :)
I did the following:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position2">
<?php
foreach($show_axle as $axlefigure){ ?>
<div style="margin-left:<?php echo $axlefigure['distance'];?>px;">
<?php echo $axlefigure['axle'] ?>
</div>
<?php
}
?>
</div>
</div>
And the css:
#axle_position2 {
margin-top: 9%;
position: relative;
float: left;
}
#axle_position2 div {
background: green;
float: left;
position: inline-block;
width: 40px;
height: 40px;
border-radius: 50px;
}

Categories