Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Cabbit

macrumors 68020
Original poster
Jan 30, 2006
2,128
1
Scotland
Hi there i am working on a javascript problem for a pm client. I want on click to make a element grey and once another element is clicked to grey that one and ungrey any other ones. So far i have it like this.


in the header
Code:
<script language="JavaScript" type="text/javascript"> 
<!-- 
function cc1(){  
document.getElementById("txt1").style.background-color='#999999'; 
} 
//--> 
</script>

in the body
PHP:
<?php
	// New news artical //
		if (isset($_GET['new']))
		{
			include("sub/news.sub.php");
		}
		// end new artical //
		
		// existing news artical //
		
		else {
		
	echo '<div class="buttons"><ul><li><a href="index.php?tab=news&new">New News Artical</a></li></ul></div>';
		
		
		// Call the required table //
		$sql = "SELECT `id`, `title`, `body`, `poster`, `date` FROM `site_news` ORDER BY `date` DESC";
		
		// Preparing the results for use //
		$result = mysql_query($sql) or die("Sorry there seems to be a problem with the database"); 
		
		
		// titles
		
					echo '<div id="record_titles"><ul>';
					echo '<li class="titles">';
					echo '<div class="title">Title</div >';
					echo '<div class="poster">Poster</div>';
					echo '<div class="date">Date Posted</div>';
					echo '<div class="comments">Comments</div>';
					echo '</li></ul></div>';
					
		// start the list //
		echo '<div id="record_list"><ul>';
		
		// Outputting the results //
		if (mysql_num_rows($result)) 
		{
	   		while($row = mysql_fetch_array($result)) 
	   			{
	
				// Printing out the results, "main_block" is the CSS styling //
                      ///******************* This is the area where the JS is  happens **************///
					echo '<li id="txt1"><a onclick="cc1()" href="javascript:ajaxpage(\'class/readmessage.class.php?id='.$row['id'].'\', \'dynamic_block\');">';
					echo '<div class="title">'.$row['title'].'</div >';
					echo '<div class="poster">'.$row['poster'].'</div>';
					echo '<div class="date">'.$row['date'].'</div>';
					echo '<div class="comments">0</div>';
					echo '</a></li>';
			}
		}
		
		// End the list //
		echo '</ul></div>';
		echo '<div id="dynamic_block"></div>';
		
	// end existing news artical //
	}
?>
 
I found your request rather confusing to understand, I think you want it so selecting one div makes it gray background, any others the original background color.

The code below, which is tested and works, assumes all your div's have sequential ID's such as "txt1", "txt2", "txt3" and so on. I wrote a simple function where you pass the number, i.e. "2" (not the ID "txt2") and it'll loop through as many iterations as you specify in the "for" loop using the variable "x" as the counter. If x equals the number passed to the function then set that div with the right ID to gray, else set the div to previous background color (you could hard code a color if you wanted) . In my example code the "for" loop is set for 3 iterations because you'll notice I added 3 divs.

Code:
<script language="JavaScript" type="text/javascript"> 
<!-- 
function MakeGray(myid){
    
    for(x=1; x<=3; x=x+1) {  
        if (x==myid) 
            document.getElementById('txt'+x).style.backgroundColor='#999999'; // Notice no dash in backgroundColor as you used!
        else
            document.getElementById('txt'+x).style.backgroundColor='';
    }
    return false;
} 
//--> 
</script>


<style>
div {border: 1px solid black; width: 200px; height: 200px; margin-top: 20px}
</style>

<div id='txt1'>
<a href="#" onClick="MakeGray('1')">GO</a>
</div>

<div id='txt2'>
<a href="#" onClick="MakeGray('2')">GO</a>
</div>

<div id='txt3'>
<a href="#" onClick="MakeGray('3')">GO</a>
</div>

Note:

In your code you didn't mention specific ID's to use and had extra stuff in there which has no bearing on the task at hand. So I wrote a new and simple script to demonstrate the concept for you. Use your own CSS, div names and links as per your own requirements in your code, of course.

-jim
 
Thats made a great start and i got 1 element working though the issue i have is that the number of items on the list depend on the amount of entries in the database is seems your solution only supports 3.
When i need to be able to have it work for hundreds and not always 1-100 some entries will be deleted.

PHP:
echo '<li><a id="txt'.$row['id'].'" onClick="MakeGray(\''.$row['id'].'\')"; href="javascript:ajaxpage(\'class/readmessage.class.php?id='.$row['id'].'\', \'dynamic_block\');">';

It works just only for 3 of the rows. Perhaps i can send javascript a row count from my sql database?
 
While at this one is there a way to use post to a ajax page.


Basically the "<form name="new_news"action="javascript:ajaxpage(\'class/new_artical.class.php?subpage\', \'dynamic_block\')" method="post">';" should send the data to the ajax page that loads in the dynamic_block div but nothing from post every reaches the other end :(

PHP:
echo '<form name="new_news" action="javascript:ajaxpage(\'class/new_artical.class.php?subpage\', \'dynamic_block\')" method="post">';
// view mail buttons //
echo '<div id="viewmail_buttons"><ul>';
echo '<li><input type="submit" value="Save" name="with_us" style="cursor: pointer" class="mail_button" onmouseover="this.className=\'mail_button_hover\'" onmouseout="this.className=\'mail_button\'"></li>';
echo '<li><a href="javascript:ajaxpage(\'class/clear.class.php\', \'dynamic_block\');">Cancel</a></li>';
echo '</ul></div>';
echo '<div class="form_input_row">';
echo '<label for="title">Title</label> <input type="text" id="title" size="25" name="title" >';
echo '</div>';
// Return the record from the database
include("../../editor/fckeditor.php");
		$oFCKeditor->BasePath = '../editor/' ;	// '/fckeditor/' is the default value.
		$sBasePath = '../../editor/' ;
		$oFCKeditor = new FCKeditor('post') ;
		$oFCKeditor->BasePath	= $sBasePath ;
		$oFCKeditor->Value		= '' ;
		$oFCKeditor->Create();
echo '</form>';		
if (isset($_GET['subpage']))
{
	if (isset($_POST['title']))
	{
		echo $_POST['title'];
	}
	else
	{
		echo 'error';
	}
}
?>
 
the ajax file
Code:
/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var loadedobjects=""
var rootdomain="http://"+window.location.hostname
function ajaxpage(url, containerid,method){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
document.getElementById(containerid).innerHTML=''
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if(method=='POST'){
page_request.open('POST', url, true) 
page_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var pineapple = document.getElementById("new_news").elements;
for(var i = 0; i< pineapple.length; i++) page_request.send(pineapple[i].name + "=" + pineapple[i].value);
}else{
page_request.open('GET', url, true)
page_request.send(null)
}
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
 
...the issue i have is that the number of items on the list depend on the amount of entries in the database is seems your solution only supports 3.

Like I said, my code was a demonstration of the concept. It's up to you to customize the code to suit your specific needs. I am having a tough time understanding you, I am guessing English is not your primary language. You also skipped to another issue (Ajax) without resolving the first issue, and your question there demonstrates you don't have the basic knowledge of how POST works with Ajax classes of this sort. The JS Ajax code you're showing me is not novice level, you just can't cut/paste this stuff and expect it to work - you need to view the help for the class to learn its functions which means learning about OOP in general, POST vs. GET and when to use each, form actions and maybe how to debug server side form submissions. Armed with the basics you can then customize your code and/or integrate the Ajax javascript class knowing how to exploit it to save you time coding.

I'll help you in the long term by providing links so you can learn about the concepts behind what you're trying to do so you can fix your own code:

Javascript Object Oriented Programming tutorial (OOP)
Get vs. Post and PHP/MySQL
Forms processing with PHP
PHP debugging techniques

If anyone else wants to jump in and code for this user or offer additional insight, please do. I am moving on and added these links so at least they can get the help they need if nobody else is willing. OP: Cheers and good luck with the project. I'm sure others will chime in soon! :) :)

-jim
 
Thanks for the help i got the original problem fixed thought the issue with the ajax script appears to have a long and lengthy fix that is on the Dynamic Drive forums as the issue has been discussed before.

Basically it does not handle sending a POST to the external ajax page and only allows sending GET values, but there appears to be a way to mix these values, i am sending 3 values to the ajax page, 1 is ?subpage to inform the page to go to the subpage of the php code and the other 2 are the POST values from the forum. This is where it goes belly up.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.