Jquery script wont see the difference between the 2 div's - javascript

I have a database with my projects, Table called: Projects. In this table i have 3 columns:
ID, Titel, BLOB
This is my php:
{
echo '<div class="project_box">';
echo '<p class="project_text">' . $row['titel'] . '</p>';
echo '<img class="project_box_image" src="data:image/jpeg;base64,' . base64_encode($row['image']) . '" width="200" height="200"</img>';
echo '</div>';
}
Every ting loads already into my website, but now i want to check if the titel equals to something, with jQuery.
Now I have this code, but it works only for 1 div. If I make a second div in my database it loads in my website but when i click each of them it says alert "test".
It seems my code wont see the difference between the 2 title's in my div's
$('.project_box').click(function() {
if ($('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($('.project_text').text() == "test"){
alert('test');
}
});
.project_box is the div I load my, title and BLOB in, and on click I want to check project text equals to something.
.project_text is the title text of the project.
I hope its clear for you, it would really help my out!
thanks.

When you have multiple <p class="project_text"> how do you think jQuery interprets $('.project_text')? You can use .find() to get the class that is inside the clicked box.
$('.project_box').click(function() {
if ($(this).find('.project_text').text() == "Portefolio"){
window.location.href = "portefolio/";
}else if ($(this).find('.project_text').text() == "test"){
alert('test');
}
});
I think a switch() would be better here as well, saves you writing the .text() part multiple times.
$('.project_box').click(function() {
switch ($(this).find('.project_text').text()) {
case "Portefolio":
window.location.href = "portefolio/";
break;
default:
alert("test");
break;
}
});

it seems that it will solve your problem:
Better Way use children():
replace your jquery by this:
$('.project_box').click(function() {
var strText = $(this).children(".project_text").text();
if (strText == "Portefolio"){
alert("portefolio");
}else if (strText == "test"){
alert('test');
}
});
Demo:http://jsfiddle.net/a6NJk/676/

Related

How to load php vars from an external file with javascript

I had this code inside the <div id="chtmsg"> on a page that shows a messenger...
PHP :
if($perguntas){
for($c=0;$c<count($perguntas);$c++){
$perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
$hora = substr($perguntas[$c]->hora, 0, 5);
echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
$pergunta->marcaRespLida($perguntas[$c]->id);
}
}
}
It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...
HTML :
$(document).ready(function () {
setInterval(function() {
$.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
$('#chtmsg').html(result);
scTop();
});
}, 3000);
});
But its shows the error inside de div...
Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3
I tested other codes inside the msg.php file and works ok without variables...
Just a thought...
Your first line in PHP
if($perguntas){
Should perhaps check if defined like so
if(isset($perguntas)){
My suggestion explained in another answer here
For better code, You should preferably use:
if (isset($perguntas) && is_array($perguntas)){

how to keep checkbox checked even after page refresh

I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ?
Thanx in advance
Here is HTML :
<td><input type='checkbox' class='user_status'
id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status'
onclick="userId(<?php echo $data['user_reg_id']; ?>)" />
Here is JS :
<script>
function userId(user_reg_id){
$(document).ready(function(){
var link = "<?php echo base_url();?>" ;
var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1;
$.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st, ajax : 1}, function(data){
alert (st); //showing status 1 and 0 on alert
if (st == 1){
$("#user_status_").prop(":checked", true)
} else {
$("#user_status_").prop(":checked", false)
};
});
});
}
</script>
store checkbox value in database using ajax when you click on it..
also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)
Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.
function isChecked(user_reg_id){
$(document).ready(function(){
$('#user_status_'+user_reg_id).on('click', function () {
if(localStorage && localStorage.getItem(user_reg_id)){
localStorage.removeItem(user_reg_id);
}else{
$('#user_status_'+user_reg_id).prop('checked', true);
}
}
});
}

concat two strings in JQuery

Just like the title above: how to concatenate two strings in JQuery?
This is my code so far:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.
Any alternatives and solution is much appreciated.
I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
i hope this one solve the issue:
<script>
$(document).ready(function(){
serviceName = '<? echo "./".$_GET["services"].".php";?>';
serviceID = '<? echo "#" .$_GET["services"]; ?>';
serviceClass ='<? echo $_GET["services"]; ?>';
console.log(serviceID);
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
</script>
also check the console in your browser (firebug or chrome developer tools) to see the output ,fit your criteria
Try as but not sure, My change is append "#" Id in jquery
<script>
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= $_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$("#"+serviceID).addClass("it");
}
});
</script>

Error with this.id in Javascript

Ok, so I'm using JS and I am having issues with the following function.
In my PHP file I have:
<?php
$file = fopen("utensils/".$cake.".txt", "r") or exit("Unable to open file!");
while(!feof($file)) {
$image = fgets($file);
echo "<div id='".$image."' class='utensil' onclick='useUtensil(this.id)'>".$image."</div>";
}
fclose($file);
?>
whilst in the JS I have:
function useUtensil(id) {
alert(id);
if (id == "Sandwich Tins") {
alert(id);
} else {
alert("You do not need that utility!");
}
}
It's a very strange bug since I have a practically identical piece of code which works, however, with this code, although the first alert(id) alerts "Sandwich Tins", it does not alert(id), instead running into the else statement.
Any help is much appreciated!
So you're saying that the alert is returning "Sandwich Tins", and yet the comparison is still failing? If that's the case, then as the others have mentioned there's either:
1) Leading or trailing spaces.
2) Case issues (Although from what you claim that doesn't seem to be the case). No pun intended.
3) "Sandwich Tins" is wrong. Maybe it should be id == "Sandwich Tin"?
Test the first one by doing this:
function useUtensil(id) {
if (id.trim() == "Sandwich Tins") {
alert(id);
} else {
alert("You do not need that utility!");
}
}
If that doesn't work, try this:
function useUtensil(id) {
if (id.trim().toLowerCase() == "Sandwich Tins".toLowerCase()) {
alert(id);
} else {
alert("You do not need that utility!");
}
}
If that still doesn't work, I suggest inspecting the input in your console and making sure you're comparing it with the correct string.
put a space
id ==" Sandwich Tins"

Problem showing file info with Ajax and PHP

I have a list of files made by my PHP code
if ($handle = opendir($director))
{
$path="images/files/nou/";
if(Files::is_empty_dir($director))
{
echo "<p>There are no script available.</p>";
}
else
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$size=Files::getSize($director."/".$file);
$exts=Files::getExtension($file);
$filex = str_replace(".".$exts,"",$file);
if(strlen($filex)>10)
{
$filex=substr($filex,0,6);
}
echo "<div class='file' title='".$file."'>".$filex."</div>";
There are functions defined in my own class Files.
Good. I want that on mouseover to show file information with this code
function getInfo($file)
{
$info="<div class='info_public'><table border=0 cellpadding=2><tr>";
$info.="<td>File : </td><td>".$file."</td></tr>";
$info.="<tr><td>Extension : </td><td>".Files::getExtension($file)."</td></tr>";
$info.="<tr><td>Size : </td><td>".Files::getSize($file)."</td></tr>";
return $info;
}
I want to show info dynamically with JQuery. I wrote this
$(".file").mouseover(function()
{
data=$(this).attr("title");
alert(data);
});
It alerts always first filename not what I crossed with mouse. But if I disable mouseover JQuery function, the title appears correctly for each file in part. If I use mouseover function, the selected value from title doesn't appear correctly, it shows first filename in alert no matter what file I crossed with mouse.
I called the alert function to see results before implementing $.ajax function to avoid bad responses.
What's the problem in my script ?
Thank you
Your jquery code works, so check something else, may be you need to onload() that script ?
http://jsfiddle.net/oceog/hJyRm/

Categories

Resources