hi everyone i have made 3 stylesheets for different looks for my website i want to load/ change the stylesheet if the user selects the dropdown option and cliks update button heres my code for drop down

<label>Select Theme:</label>
<select name="theme" value="<?php echo $theme; ?>">
<option value="Default">Default</option>
<option value="Dark">Dark</option>
<option value="White">White</option>
</select>

any kind of help will be appreciated

Using javascript:

<head>
<!-- You must have the id set in the next line -->
<link id="stylesheet" rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript">
function switchStyle(el){
    //get selected theme
    var styleSheet = el.options[el.selectedIndex].value;
    //apply the new style using id set earlier.
    document.getElementById('stylesheet').href = styleSheet;
}
</script>

<body>
<!-- (this) refers to the select element -->
<select id="theme" onchange="switchStyle(this)">
<!-- value corresponds to stylesheet filename --> 
<option value="default.css">Default</option>
<option value="dark.css">Dark</option>

In addition you can use alternate stylesheets, which are available also from the browser tools:

<link href="/styles/default.css" rel="stylesheet" title="default style" />
<link href="/styles/dark.css" rel="alternate stylesheet" title="dark style" />
<link href="/styles/white.css" rel="alternate stylesheet" title="white style" />

http://www.w3.org/Style/Examples/007/alternatives.en.html

To update you can set a cookie to save the CSS to load when visiting the website, for example:

<?php

$style = false;
$array_styles = array('default','dark','white');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if(isset($_POST['theme']))
    {
        $time = time()+(60*60*24*7); # a week from now
        $value = in_array($_POST['theme'],$array_styles) ? $value : 'default';

        setcookie("Theme", $value, $time, "/", "mywebsite.tld", false);
        $style = $value;
    }
}

if(isset($_COOKIE['Theme']))
{
    $style = in_array($_COOKIE['Theme'],$array_styles) ? $_COOKIE['Theme']:'default';
}

echo '
    <link rel="'.($style == 'default' || $style === false ? '':'alternate ').'stylesheet" href="/styles/default.css" />
    <link rel="'.($style == 'dark' ? '':'alternate ').'stylesheet" href="/styles/dark.css" title="dark style" />
    <link rel="'.($style == 'white' ? '':'alternate ').'stylesheet" href="/styles/white.css" title="white style" />
';
?>

I didn't tested the code but it should work. More info about setcookie(): http://php.net/manual/en/function.setcookie.php

I only noticed afterwards that the title said 'using PHP':

<?php
//check to see if the form was submitted
if(isset($_POST['submit'])){
    $theme = $_POST['theme'];//set to selected theme
} else { 
    $theme = "default.css";//set to default
}
?>
<html>
<head>
<!-- use PHP to echo the location of the stylesheet -->
<link id="stylesheet" rel="stylesheet" type="text/css" href="<?php echo $theme; ?>" />


<!-- The action of the form will default to self -->
<form method="post">
<select name ="theme">
<option value="default.css">Default</option>
<!-- The PHP code in next part would be better in a separate function -->
<!-- It sets the dropdown to selected on the currently selected theme -->
<option value="dark.css"<?php if ($theme == "dark.css") echo " selected"; ?>>Dark</option>
</select>
<input type="submit" name="submit" />

Learn, don't just copy :)

actually i am using various stylesheets and i have the stylesheets in pre-header.php
which i have included in this page.. so should i set is in that file?? will that be ok??

here is the complete code i should show that i well..

<?php include("../includes/config.php"); ?>
<?php
 if ($_SESSION["isadmin"])
   {

   $con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db($dbname, $con);

$result = mysql_query("SELECT * FROM setup WHERE (id=".$_SESSION["id"].")");
    while($row = mysql_fetch_array($result))
    {
       $title = $row['title'];
       $theme = $row['theme'];
    }
mysql_close($con);
?>

<!DOCTYPE HTML>
<html>
<head>
<?php include("../includes/pre-header.php");?>
<script type="text/javascript" src="../javascript/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="../javascript/jQuery.validity.min.js"></script>


<script type="text/javascript">
$(function() {
                $("form").validity(function() {
                    $("#title")
                        .require("This filed must be Filled!!")
                });
            });
        </script>
<title>Admdin Setup</title>
</head>
<body>
<div class="container">
<?php include("../includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<div id="maincontent">
<?php include("includes/aside.php"); ?>
<br /><br />
<div class="span-18 last">
    <h2 class="alt">Customize</h2>
<?php
  }
}
?>
<form id="form" method="post"  action="setup-action.php" enctype="multipart/form-data" >
<label for="title">Title Of Your Organization:</label>  <input id="title" type="text" name="title" class="text" value="<?php echo $title; ?>" /> <br /> <br />
<label>Select Theme:</label>
<select name="theme" value="<?php echo $theme; ?>">
<option value="Default">Default</option>
<option value="Dark">Dark</option>
<option value="White">White</option>
</select>
 <br /> <br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<label>Choose a file to upload:</label> <input name="uploadedfile" type="file" /> <br /> <br />
<input type="submit" name="Upload" class="button"  value="Upload" />
</form>
</div>
</div>
<?php include("../includes/footer.php"); ?>
</div>
</body>

</html>
<?php
    }
    else
    {
        header("Location: ".$fullpath."login/unauthorized.php");

    }
?>

setup-action.php

<?php include("../includes/config.php");?>
<?php
$target_path = "../graphics/logo.jpg";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
}
else
{
    echo "There was an error uploading the file, please try again!";
}
?>
<?php
$title=$_POST["title"];
$theme=$_POST["theme"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db($dbname, $con);
$result=mysql_query("SELECT * FROM setup WHERE id=".$_SESSION['id']);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0)
{
   {
mysql_query("UPDATE setup  SET title='".$title."' , theme='".$theme."'WHERE id=".$_SESSION['id']);
 header("Location:setup.php?status=1");
    }
}
else {
    header("Location:setup.php?status=2");
}
mysql_close($con);
?>

@adam the method is much easier with javascript i think i should use javascript to change themes... i have almost no idea of javascript, i just can add JS plugins and modify them :D

i have used the first method but it changes to default as i press update button otherwise when i select dark it immediately loads but when i press update it again sets to default...

and thanx for such a good responce :)

Member Avatar for diafol

You may find some sites rubbish the js approach. That may be from a while ago when js was not as ubiquitous as today. Due to that, I used to employ cereal's alternate stylesheet method. This still has some advantages - e.g. browser options. Although the js method may mean that you don't need a refresh/redirect.

Question - are the stylesheets radically different (e.g. layout) - or are they just colour swatches?

yeah the style sheets are change in colors and fonts and the a little bit of button styles are different.

i am serching for so long but didnt get any satifactory resource..

It does look better when the stylesheet changes immediately, but the choice will be lost when the page is reloaded, unless the choice is saved somehow.
You seem to be storing the choice in a database, but a database call for every page load solely to determine the theme is a bit excessive I feel.
The better way is to save the users choice in a session cookie as Cereal has demonstrated.
The only issue I had with this is the browser caching the stylesheet and using an 'old' choice to style the page, but this may have just been with Jquery Mobile.

Member Avatar for diafol

If you have multiple stylesheets loaded at one go, the alternate method gets a bit trickier, unless you use the @import method.

I'm assuming then that you have a main stylesheet and then secondary ones for the 'choice'. I don't think it makes much sense to have loads of 'full' ones, as this can be a pain for maintainability. With the added complexity of media queries (don't know if you're using them), you need to take time to plan this out properly. Rushing into it can cost a lot of time (I know from experience!).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.