jQuery AJAX/ PHP/MySQL live filtering - php

I am building a image gallery where, you can filter images by city, category and gender.
The problem I am faced with is how to update the results live (real-time).
The logic I apply is:
Select a filter criteria, click on a radio button.
Send query via jQuery AJAX to a PHP script that runs a MySQL query and returns HTML.
It works, but is largely clunky.
once I select the city, I have to select gender, and then city again to get results.
I know the problem lies in the way I run the MySQL. I need your guidance here.
Code for the gallery.php file:
<html>
<head>
<title>EQUIMATIC GALLERY</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="jcarousel.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="jcarousel.css">
<script>
function displayFullImage(link)
{
//alert(link);
$("#currentlystaged").attr('src', link);
}
$(document).ready(function(){
$('#thumbs').jcarousel({
vertical: true,
scroll: 13
});
//first load
$.ajax({
type:"POST",
url:"sortbystate.php",
data:"city=new york&gender=m&category=",
success:function(data){
//alert("whoa, careful there!");
$('#thumbs').html(data);
}
});//end ajax
// normal operation
$(".statelist :input").click(function(){
var state = $('.statelist input:checked').attr('value');
var gender = $('.gender input:checked').attr('value');
var category =$('.category input:checked').attr('value');
$.ajax({
type:"POST",
url:"sortbystate.php",
data:"city="+state+"&gender="+gender+"&category="+category,
success:function(data){
//alert("whoa, careful there!");
$('#thumbs').html(data);
}
});//end ajax
});
});
</script>
</head>
<body>
<?php include 'conndb.php';?>
<div class="container">
<div class="sublogo"><img src="images/galogo.png"></div>
<div class="sidebaropen">
<div class="statelist">
SORT ENTRIES BY:<br/>
<h2>01 LOCATION </h2>
<input type="radio" value="New York" name="state" /> NYC <br>
<input type="radio" value="Los Angeles" name="state" /> Los Angeles <br>
<input type="radio" value="San Francisco" name="state" /> San Francisco <br>
<input type="radio" value="Chicago" name="state" /> Chicago <br>
<input type="radio" value="Miami" name="state" /> Miami <br>
<input type="radio" value="Texas" name="state" /> Dallas <br>
<input type="radio" value="District of Columbia" name="state" /> DC <br>
<input type="radio" value="Boston" name="state" /> Boston <br>
</div><!-- state list -->
<div class="gender">
<h2>02 GENDER </h2>
<input type="radio" value="m" name="gender" /> Male <br>
<input type="radio" value="f" name="gender" /> Female <br>
</div>
<div class="category">
<h2>03 CATEGORY </h2>
<input type="radio" value="balance" name="category" /> Balance <br>
<input type="radio" value="confidence" name="category" /> Confidence <br>
</div>
</div>
<div class="staging">
<img src="http://www.byequinox.com/equinox_images/24447ddec24d22102eebf8a0a1d14e87.jpg" id="currentlystaged" />
</div>
<div id="results">
<ul id=thumbs class='jcarousel jcarousel-skin-tango' style='width:250px; list-style:none; height:400px' >
</ul>
</div>
</div>
</div>
</body>
</html>
Code for the sort by State:
<?php
include "conndb.php";
$city = $_POST['city'];
$gender = $_POST['gender'];
$category = $_POST['category'];
$filter_query= "SELECT * FROM equinox where city LIKE CONVERT( _utf8 '$city' USING latin1 ) AND gender = '$gender'";
$filter_result = mysql_query($filter_query);
while($filter_row= mysql_fetch_array($filter_result))
{
$link = $filter_row['link'];
echo("<a href=# >");
echo("<li style='width:60px; margin:0 10px 0 35px; float:left;'><img src=".$filter_row['link']." width=100 border=0 onclick=displayFullImage('$link'); > </a></li>");
//echo($filter_result);
}
?>
THE LINK FOR THE ACTUAL WORKING GALLERY: http://rjwcollective.com/equinox/rishi_gallery/eqgall.php

The problem is that you're only updating the photos when the city is chosen. Extract the photo retrieving functionality into its own function then call that function from the click event on all 3 radios

Related

Uploading file to MySQL blob field file_get_contents(): failed (from input type="file")

I am uploading a file from my local directory to a MySQL Databases' MEDIUMBLOB field using file_get_contents and I am receiving the following error:
Warning: file_get_contents(test.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\Craisins\forms\new_scenario.php on line 265
Yet the file is definitely there since I pick it with input type="file"
This seemed to be working yesterday and now suddenly today it's no longer working correctly and I'm not sure why.
Here is the full file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<!--Normal CSS Sheets-->
<link rel="stylesheet" type="text/css" href="../includes/style.css">
<link rel="stylesheet" type="text/css" href="../includes/style_form.css">
<!--BSM Select CSS Sheet-->
<link rel="stylesheet" type="text/css" href="../includes/bsmselect/css/jquery.bsmselect.css">
<!--jQuery-->
<script src="../includes/jquery-2.1.4.min.js"></script>
<!--jQuery for BSMSelect-->
<script src="../includes/bsmselect/js/jquery.bsmselect.js"></script>
<!--jQuery selector for BSMSelect-->
<script>
$(document).ready(function() {
$("select[multiple]").bsmSelect();
});
</script>
<style type="text/css">
<!--
.style1
{
font-size: 12px;
font-weight: bold;
}
textarea
{
resize: none;
}
-->
<?php include ("../includes/formSuccess.php");
include ("../includes/sql.php");
require_once "../WindowsAzure/WindowsAzure.php";
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;
?>
</style>
<title>****</title>
</head>
<body>
<div id="pageContainer">
<!--This section is for the upper half of the page. From the "Title" bar up.-->
<?php include ("../includes/formNav.php");?>
<!--End of the Header Section-->
<br>
<!--This section is where we add the main content for the page.-->
<div id="contentArea">
<div id="mainContentAdmin">
<h1 style="text-align:center">Add New Scenario</h1>
<?php
// display form if user has not clicked submit
if (!isset($_POST["btn_submit"]))
{
?>
<!--This will be the form that will hold the information of the entire page.-->
<form class="elegant-aero" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<!--Scenario Title-->
<label>
<span>Title:</span>
<input type="text" name="title" placeholder="Enter the full scenario name here">
</label>
<!--Scenario Description-->
<label>
<span>Description:</span>
<textarea name="desc" placeholder="Enter the scenario description here"></textarea>
</label>
<!--Scenario Times-->
<label id="time">
<span>Estimated Times:</span>
<!--Scenario Execution Time-->
<b>Execution:</b>
<input type="number" name="execHr" min="0" placeholder="Hours">
<input type="number" name="execMin" min="1" placeholder="Minutes">
<br><br>
<!--Scenario Debriefing Time-->
<b>Debriefing:</b>
<input type="number" name="debriHr" min="0" placeholder="Hours">
<input type="number" name="debriMin" min="0" placeholder="Minutes">
</label>
<br>
<!--Origin-->
<label>
<span>Origin:</span>
<input type="text" name="origin" placeholder="Enter the origin here (if any)">
</label>
<!--Target Users-->
<label>
<span>Target Users:</span>
<select name="users[]" multiple="multiple" title="Please select user type...">
<?php
selectMySQL("valid_trainee_type","trainee_type");
?>
</select>
</label>
<br>
<!--Capabilities-->
<label>
<span style="">Capabilities Required:</span>
<select name="capabilities[]" multiple="multiple" title="Please select capabilities...">
<?php
selectMySQL("valid_capability","name");
?>
</select>
</label>
<br>
<!--Prerequisites-->
<label>
<span style="">Prerequisite Knowledge:</span>
<select name="prerequisites[]" multiple="multiple" title="Please select prerequisites...">
<?php
selectMySQL("valid_prerequisite","prerequisite");
?>
</select>
</label>
<br>
<!--Equipment-->
<label>
<span>Equipment Required:</span>
<select name="equipment[]" multiple="multiple" title="Please select equipment...">
<?php
selectMySQL("valid_equipment","equipment");
?>
</select>
</label>
<!--Parameters-->
<label>
<span>Parameters to Monitor:</span>
<select name="parameters[]" multiple="multiple" title="Please select parameters...">
<?php
selectMySQL("valid_parameter","parameter");
?>
</select>
</label>
<br>
<!--Learning Objectives-->
<label>
<span>Learning Objectives:</span>
<textarea name="object" placeholder="Please list the learning objectives for the procedure..."></textarea>
</label>
<!--Setting-->
<label>
<span>Setting:</span>
<textarea name="set" placeholder="Please describe the ideal setting for the procedure..."></textarea>
</label>
<!--Preparation-->
<label>
<span>Preparation Required:</span>
<textarea name="prep" placeholder="Please list any steps that are required in order to perform this procedure..."></textarea>
</label>
<!--Participants-->
<label>
<span>Participants Required:</span>
<textarea name="part" placeholder="Please list the participants that will be required in order to perform this procedure..."></textarea>
</label>
<!--Patient Information-->
<label>
<span id="patient">Patient Information:</span>
<br>
<!--Patient Name-->
<b>Name</b>
<input type="text" name="patName" style="width:63%;" placeholder="Enter the patient's full name here">
<!--Patient Vitals-->
<b>Vitals</b>
<select name="patSex" style="width:15%;" title="Male or Female?">
<option value="male">male</option>
<option value="female">female</option>
</select>
<b>Age</b>
<input name="patAge" type="text" style="width:5%;">
<b>Height</b>
<input type="text" name="patHt" style="width:6%;" placeholder="(in)">
<b>Weight</b>
<input type="text" name="patWt" style="width:6%;" placeholder="(lbs)">
<span style="width: 30%; border-right:0; margin-right:0; padding-right: 5px;">Other Info</span>
<textarea style="width:63%;" name="patInfo" placeholder="Any other medical details?"></textarea>
</label>
<!--Scoring-->
<label>
<span>Scoring:</span>
<textarea name="score" placeholder="Please detail the scoring rubric for this scenario..."></textarea>
</label>
<!--Debrief-->
<label>
<span>Debrief:</span>
<textarea name="debrief" placeholder="Please detail the debriefing process for this scenario..."></textarea>
</label>
<!--Scenario File-->
<label>
<span>Scenario Details:</span>
<br>
<input type="file" name="fileScenDetails" value="Upload File">
<br>
<textarea name="textScenDetails" placeholder="Please any other scenario details here..."></textarea>
</label>
<!--Submit Button-->
<label>
<span> </span>
<input type="submit" name="btn_submit" class="button" value="Add Scenario"/>
</label>
</p>
</form>
<?php
} //end if
else
{
//Setup the MySQL server
$servername = "localhost";
$username = "root";
$password = "****";
$dbname = "****";
//Create connection to the MySQL server
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if($conn -> connect_error)
{
die("Connection failed: " . $conn -> connect_error);
} //end if
//Organize Execution Time
$exec_time = "00:".$_POST['execHr'].":".$_POST['execMin'];
//Organize Debriefing Time
$debrif_time = "00:".$_POST['debriHr'].":".$_POST['debriMin'];
//Organize BLOB
$blob = addslashes(file_get_contents($_POST['fileScenDetails']));
$sql="INSERT INTO scenario (title, description, est_scenario_time, est_debriefing_time,
origin, objectives, setting, preparation, participants,
patient_name, patient_sex, patient_age, patient_height,
patient_weight, patient_info, scoring, debrief,
scenario_file, scenario_text)
VALUES ('".$_POST['title']."','".$_POST['desc']."', '$exec_time', '$debrif_time',
'".$_POST['origin']."','".$_POST['object']."',
'".$_POST['set']."','".$_POST['prep']."',
'".$_POST['part']."','".$_POST['patName']."',
'".$_POST['patSex']."','".$_POST['patAge']."',
'".$_POST['patHt']."','".$_POST['patWt']."',
'".$_POST['patInfo']."','".$_POST['score']."',
'".$_POST['debrief']."','$blob',
'".$_POST['textScenDetails']."');";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
} //end else
$conn->close();
/*
//Insert Target Users (Trainee Types)
insert_Scen_Dev('scenario','title', 'title','users',
'valid_trainee_type','trainee_type', 'scenario_trainee_type',
'scenario_id', 'valid_trainee_type_id');
//Insert Capabilities
insert_Scen_Dev('scenario','title', 'title','capabilities',
'valid_capability','name', 'scenario_capabilities',
'scenario_id', 'valid_capability_id');
//Insert Prerequisites
insert_Scen_Dev('scenario','title', 'title','prerequisites',
'valid_prerequisite','prerequisite', 'scenario_prerequisites',
'scenario_id', 'valid_prerequisite_id');
//Insert Equipment
insert_Scen_Dev('scenario','title', 'title','equipment',
'valid_equipment','equipment', 'scenario_equipment',
'scenario_id', 'valid_equipment_id');
//Insert Parameters
insert_Scen_Dev('scenario','title', 'title','parameters',
'valid_parameter','parameter', 'scenario_parameters',
'scenario_id', 'valid_parameter_id');
*/
echo "<div class='sqlSuccess'>A new Scenario has been added!</div>";
} //end else
?>
</div>
</div>
<!--End of the Content Section-->
<!--This section is for the lower half of the page. From the copyright bar down.-->
<div id="footer">
<div id="footerCenter">
Copyright ©
<script language="javascript" type="text/javascript">
var today = new Date();
var year = today.getFullYear();
document.write(year);
</script>
</div>
</div>
<!--End of the Footer Section-->
</div>
</body>
There are several problems with this code. At first, file won't upload unless you specify a correct enctype attribute on a form element:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Also the file address is available under $_FILES['fileScenDetails']['tmp_name'], not under $_POST['fileScenDetails'], so:
$blob = addslashes(file_get_contents($_FILES['fileScenDetails']['tmp_name']));
Note, that you should check if file upload was successfull, as otherwise your code will trigger warning (eg. when user won't specify file). Add something like this:
if(isset($_FILES['fileScenDetails']['error']) && UPLOAD_ERR_OK == $_FILES['fileScenDetails']['error']) {
// do your stuff here
} else {
// display 'no-file' error to the user
}
Also, you should definitely check if the specified file was really uploaded, to avoid stealing your code with malformed requests. Check is_uploaded_file function here: http://php.net/manual/en/function.is-uploaded-file.php
There are also some possible SQL injections and other security issues.

php Page and star rating plugin full rendered only after refresh

I'm using fyneworks jquery star-rating with jQuery mobile and in one page created dynamically with a PHP function everything is working fine. But in another page where the "rating tab" is included in the PHP page, the stars are not rendered until I refresh the page.
PAGE
<?php
session_start();
if (!session_is_registered('autorizzato')) {
echo "<h1>Area riservata, accesso negato.</h1>";
echo "Per effettuare il login clicca <a href='login.php'><font color='blue'>qui</font></a>";
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="jquery-1.8.2.min.js"></script>
<script src="jquery.mobile-1.2.0.min.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.2.0.min.css" />
<script src='rating/jquery.MetaData.js' type="text/javascript" language="javascript"></script>
<script src='rating/jquery.rating.js' type="text/javascript" language="javascript"></script>
<link href='rating/jquery.rating.css' type="text/css" rel="stylesheet"/>
<script src="logged.js"></script>
</head>
<body background="#000000">
<div data-role="page" id="lista">
<div data-role="header" data-position="fixed">
<input type="submit" onClick="back()" data-icon="back" class="ui-btn-left" value="Indietro" />
<h1>TITLE</h1>
Logout
</div>
<div data-role="content" data-theme="a">
<form id="save" action="saveComment.php" method="post" data-ajax="false">
<div data-role="fieldcontain">
<label for="textarea">Comment:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<label>Rating:</label>
<div data-role="content" >
<input data-role="none" name="stars" type="radio" class="star" value="1"/>
<input data-role="none" name="stars" type="radio" class="star" value="2"/>
<input data-role="none" name="stars" type="radio" class="star" value="3"/>
<input data-role="none" name="stars" type="radio" class="star" value="4"/>
<input data-role="none" name="stars" type="radio" class="star" value="5"/>
</div>
<input type="hidden" name="id" value="<?php echo $_GET["id"]; ?>" />
<input type="hidden" name="rating" id="rating" value="1" />
<fieldset id="actions">
<input type="submit" id="submit" value="Invia">
</fieldset>
</form>
</div>
</div>
</body>
</html>
logged.js
$(document).load(function () {
$('#rt').click(function () {
var div = $(this);
div.children('input').each(function () {
if ($(this).is(':checked')){
$('#rating').attr("value", $(this).val());
}
});
});
});
I noticed that the page created dynamically by PHP is accessing my database, and takes about 2-3 seconds to display, and everything is rendered. This second page is rendered only after I press F5 and refresh the page.
What am I missing?
Have you tried .ready?
$(document).ready(function() {
// Handler for .ready() called.
});

don't want to refresh & retain last inserted values

In my htm page i want to use a button which submit my form by using function. I use validations on my fields and when i press submit button it displays error message but doesnot retain last values it refresh my form. I just want that the values that i entered will be exist there and just the field that has only error message will be disappear. all other fields remain there.
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--<meta http-equiv="refresh" content="text/html; charset=iso-8859-1" />-->
<!--
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
-->
<title>Phone Registration</title>
<link rel="stylesheet" type="text/css" href="file:///C|/xampp/htdocs/track/css/view.css" media="all"/>
<script type="text/javascript" src="file:///C|/xampp/htdocs/track/javascript/view.js"></script>
<script type="text/javascript" src="file:///C|/xampp/htdocs/track/javascript/external.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body id="main_body" >
<img id="top" src="file:///C|/xampp/htdocs/track/images/top.png" alt=""/>
<div id="form_container">
<h3>
Phone Registration
Officer Registration
Customer Registration
Task Entry
</h3>
<form name="order" id="form_532698" class="appnitro" method="post" action="" >
<div class="form_description">
<h2>Phone Registration</h2>
</div>
<ul >
<li>
<span>
<label class="description">IMEI # : </label>
<input name="imei" id="imeinum" class="element text medium" type="text" maxlength="15" value=""/>
</span>
</li>
<li>
<span>
<label class="description" >Phone Number </label>
<input name="phone" id="phnum" class="element text medium" type="text" maxlength="11" value="" onblur="validate(this)"/>
</span>
</li>
<li>
<span>
<label class="description" >From Date </label>
<input id="datepicker" name="fdate" class="element text medium" maxlength="10" value="" type="text"/>
</span>
</li>
<li>
<span>
<label class="description" for="element_4">Active </label>
<input name="r1" id="rad" class="element radio" type="radio" value="Yes" checked="checked" />
<label class="choice">Yes</label>
<input name="r1" id="rad" class="element radio" type="radio" value="No" />
<label class="choice">No</label>
</span>
</li>
<li>
<input type="button" name="save" value="Save" />
</li>
<!--
<li class="buttons">
<input type="hidden" name="form_id" value="532698" />
<input class="button_text" type="submit" name="save" value="Save" id="" />
<input class="button_text" type="reset" name="cancel" value="Cancel" />
<input class="button_text" type="submit" name="search" value="Search" id="" />
<input class="button_text" type="submit" name="up" value="Update" id="" />
<input class="button_text" type="submit" name="del" value="Delete" id="" />
</li>
-->
</ul>
</form>
</div>
<img id="bottom" src="file:///C|/xampp/htdocs/track/images/bottom.png" alt=""/>
<script type="text/javascript" language="JavaScript">
//submit form
document.order.submit();
</script>
</body>
</html>
Kindly guide me how can i do this?? I'll be thankful to you
You can use this code to prevent form from submiting to server if validation fails:
$("form").on("submit", function(event){
if(!isValidForm($(this)){
event.preventDefault();
}
});
supposingly isValidForm() method takes form selector and returns true if form is valid and false if it's not.
use e.preventDefault(); or return false;
Check the validation is success or not in $(function()) if not then return false in that.. else return true...
<script>
$(function() {
$( "#datepicker" ).datepicker();
if(!validation) {
return false;
}
return true;
});
</script>
There are 2 major ways of doing this: PHP(server-side) and javascript(client-side).
The PHP solution isn't that clean, you need to refresh the page, check the values there and set the correct value in every input (removing the ones you want to delete)
The javascript/jQuery solution is cleaner: instead of a <input type='submit' /> use a button that calls a javascript function, checks every input (if you need server information to check them you can use Ajax) and displays the errors, setting only the ones that were wrong to blank.
Both ways are ok, but the javascript method is much easier to control/update, and it's more user-friendly since it doesn't refresh the page.

Populating Many checkboxes in tree structure inside Dropdown

Guys Here is the checkboxes, where it displays in tree structure. I need it to be displayed inside the dropdown.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.team').on('click',function(){
if($(this).is(':checked')){
$(this).next().next().show();
}else{
$(this).next().next().hide();
}
});
});
</script>
</head>
<body>
<form name="FootballClubs">
<input type="checkbox" class="team" value="RealMadrid"/>Real Madrid<br />
<div style="padding:10px 10px 10px 15px;display:none;">
<input type="checkbox" class="player" value="CR"/>Cristiano Ronaldo<br />
<input type="checkbox" class="player" value="SA"/>Shabi Alanso<br />
<input type="checkbox" class="player" value="IC"/>Iker Casillias<br />
</div>
<input type="checkbox" class="team" value="ManCity"/>Man City<br />
<div style="padding:10px 10px 10px 15px;display:none;">
<input type="checkbox" class="player" value="SA"/>Sergio Aguero<br />
<input type="checkbox" class="player" value="SM"/>Super Mario<br />
</div>
</form>
</body>
</html>
I am trying to populate inside a dropdown. Help me.
Thanks in Advance.!!
Look at jquery UI widget and jSTree

Hiding divs based on a selected radio button

I'm having an issue with radio buttons showing one div and hiding the rest. I have my code which I'll post below (tested and working in jsfiddle but not when I put it onto my page).
To give you an idea of what I'm after, I am making a registration page. The radio buttons will control a div that has the form placed inside it, so radio 1 checked, div 1 is selected, and the rest hidden and so on.
Here's my jquery:
<script type="text/javascript">
$('#accountchoice').change(function() {
if ($('#personalfan').attr('checked')) {
$('#personalfan1').show();
$('#soloartist1').hide();
$('#band1').hide();
$('#venue1').hide();
$('#business1').hide();
$('#service1').hide();
} else if ($('#soloartist').attr('checked')) {
$('#soloartist1').show();
$('#personalfan1').hide();
$('#band1').hide();
$('#venue1').hide();
$('#business1').hide();
$('#service1').hide();
} else if ($('#band').attr('checked')) {
$('#band1').show();
$('#personalfan1').hide();
$('#soloartist1').hide();
$('#venue1').hide();
$('#business1').hide();
$('#service1').hide();
} else if ($('#venue').attr('checked')) {
$('#venue1').show();
$('#personalfan1').hide();
$('#soloartist1').hide();
$('#band1').hide();
$('#business1').hide();
$('#service1').hide();
} else if ($('#business').attr('checked')) {
$('#business1').show();
$('#personalfan1').hide();
$('#soloartist1').hide();
$('#band1').hide();
$('#venue1').hide();
$('#service1').hide();
} else if ($('#service').attr('checked')) {
$('#service1').show();
$('#personalfan1').hide();
$('#soloartist1').hide();
$('#band1').hide();
$('#venue1').hide();
$('#business1').hide();
}
});
</script>
and here's the HTML
<body>
<?php include_once "header_template.php"; ?>
<div id="signupwrapper">
<div id="signupinner">
<h3 align="left"> GETSCENE REGISTRATION ! </h3>
<hr />
<div id="signup" style="border:thin; border-color:#666">
<h4 align="left">Please Choose One of The Following Account Types</h4>
<div id="accountswrapper">
<form id="accountchoice" name="accountchoice" method="post" action="">
<label for="radio">personal/fan</label>
<input type="radio" name="radio" id="personalfan" value="radio1" checked="checked" />
<label for="radio2">Solo artist</label>
<input type="radio" name="radio" id="soloartist" value="radio2" />
<label for="radio3">band</label>
<input type="radio" name="radio" id="band" value="radio3" />
<label for="radio4">venue</label>
<input type="radio" name="radio" id="venue" value="radio4" />
<label for="radio5">business</label>
<input type="radio" name="radio" id="business" value="radio5" />
<label for="radio6">service</label>
<input type="radio" name="radio" id="service" value="radio6" />
</form>
<hr />
<div id="personalfan1">1</div>
<div id="soloartist1">2</div>
<div id="band1">3</div>
<div id="venue1">4</div>
<div id="business1">5</div>
<div id="service1">6</div>
</div>
</div>
</div>
</div>
<?php include_once "footer_template.php"; ?>
</body>
Any help here will be really appreciated as I've been banging my head against this for hours.
This script
<script type="text/javascript">
$('#accountchoice').change(function() {
Will only work if it's at the end of your body tag. If it's in the head, it won't do anything, since the dom won't be ready when the script runs.
The easiest way to fix this is to put this code into a document.ready handler:
$(function() {
//this will run when the dom is ready
$('#accountchoice').change(function() {
});
You should be able to trim this code down and do it all in one shot by looking at the radio that's checked
var allDivs = ['venue1', 'personalfan1', 'soloartist1', 'band1', 'business1', 'service1'];
var radio = $("input[type='radio']:checked");
if (radio.length === 0)
return;
$('#' + allDivs.join(',#')).hide();
$("div#" + radio[0].id + "1").show();
You could restructure your HTML to make your life MUCH easier.
Here is an example:
<style type="text/css">
#account_types > div { display: none; }
</style>
<div id="signupwrapper">
<div id="signupinner">
<h3 align="left"> GETSCENE REGISTRATION ! </h3>
<hr />
<div id="signup" style="border:thin; border-color:#666">
<h4 align="left">Please Choose One of The Following Account Types</h4>
<div id="accountswrapper">
<form id="accountchoice" name="accountchoice" method="post" action="">
<label for="personalfan">personal/fan</label>
<input type="radio" name="radio" id="personalfan" value="radio1" checked="checked" />
<label for="soloartist">Solo artist</label>
<input type="radio" name="radio" id="soloartist" value="radio2" />
<label for="band">band</label>
<input type="radio" name="radio" id="band" value="radio3" />
<label for="venue">venue</label>
<input type="radio" name="radio" id="venue" value="radio4" />
<label for="business">business</label>
<input type="radio" name="radio" id="business" value="radio5" />
<label for="service">service</label>
<input type="radio" name="radio" id="service" value="radio6" />
</form>
<hr />
<div id="account_types">
<div class="personalfan">1</div>
<div class="soloartist">2</div>
<div class="band">3</div>
<div class="venue">4</div>
<div class="business">5</div>
<div class="service">6</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#accountchoice').change(function() {
var divToShow = $(this).find('input:checked').attr('id');
$('#account_types > div').each(function() {
if($(this).hasClass(divToShow)) { $(this).show(); }
else { $(this).hide();}
});
});
$('#accountchoice').trigger('change');
});
</script>
Now, if you'll take a note at the restructuring, you'll see a few things. First, the Divs that contained the different account types are inside a holding Div. You don't need to do that, but it makes it easier to isolate them. You could just as easily have given them all a similar class to accomplish the same task.
Secondly, they now have class names that are the same as their associated input ID. This makes it very easy to reference the exact one you are looking for, while still making it easy to touch the rest of them too. So now you can loop through the array of these elements, show() the Div that goes along with the selected radio, and hide() the ones that aren't. All in a few small steps.
This also makes it much easier to add new parts to your code. Otherwise, if you added a new section, you'd have to edit each if() statement you made, adding the new section to make sure it shows and hides properly.
This is where you can see some of the power of the DOM. Much simpler code, easier to maintain, and you can reuse it later on.
I also fixed the labels for you too.
Here is another example, though it does require a little change to HTML to make it neat/easy to manage.
HTML
// Added class "choice" to the radio inputs
<input type="radio" name="radio" id="venue" class="choice" value="radio4" />
<input type="radio" name="radio" id="business" class="choice" value="radio5" />
<input type="radio" name="radio" id="service" class="choice" value="radio6" />
<div class="account_types">
<div class="dynamic" id="venue1">
4</div>
<div class="dynamic" id="business1">
5</div>
<div class="dynamic" id="service1">
6</div>
</div>
SCRIPT
$('input.choice').click(function () {
var eleToShow = this.id + "1";
$('div', '.account_types').hide();
$('#' + eleToShow).show();
});

Categories