Change form position on page load - php

Ok, I know this can be done, for I've seen it before. Yet I have no idea how to make it work I have searched everywhere for an answer.
What I need is for my form to randomly change positions when the page loads from 3 different spots on the page. So for example....
[Here] [Here] [Here]
Could all be possible spots the form could load in but only in 1 spot for each time it loads. I don't know what information you need to help me. I will just give my form for now.
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
If you need more just ask.

Just my inital thought, but you could write CSS for the 3 different position class, and call them things like 'position1', 'position2','position3'. Then on page load in javascript (or in PHP) if you want, generate a random number between 1 and 3, add the class "position"+randomNumber to the element, and then it will be in one of those places. This is similar to a technique I used for random background images.
Update
Also, if you want to use more descriptive class names for the locations, you could keep a mapping of a number to a class name (or use something like position in an array), to relate a a random number to the class to apply.
Code
CSS:
<style>
.position1 {
// Whatever style you want for position 1
}
.position2 {
// Whatever style you want for position 2
}
.position3 {
// Whatever style you want for position 3
}
</style>
JS:
$(document).ready( function () {
var randomIndex = Math.floor(Math.random()*3)+1; //3 is the number of options you have; +1 makes the range 1 - 3 instead of 0 - 2
$('#my-form').addClass('position'+randomIndex); //Adds the new class the element with id = 'my-form'
}

If you mean by "load" a page refresh than you will have to persist the previous location of the form either in cookie or some other mechanism. Based on the last location of the form you can decide which location should be next.
If the form is being reloaded based on ajax calls, then I would advise using a var to store the previous location of the form and make the next location not be the same as previous by checking the value of the var. If each time form loads position should be unique than use an array to store previously used display locations.
HTH.

Related

PHP and jQuery Draw numbers animation

I've been working on a program to draw cards. I have 54 cards and I want to have them drawn individually. Here's what I've gotten so far. It reads an array, shuffles it, resets it, and then places them with a foreach.
<?
session_start();
include "array.php";
shuffle($cards);
reset($cards);
$i = 1;
foreach($cards as $card){
print <<<HERE
<div id="$i">\n<img src="img/{$card[1]}.gif" alt="{$card[0]}" width="176" height="276"/><br/>
<h1 style="font-family: sans-serif;">{$card[0]}</h1>\n</div><br />\n\n
HERE;
$i++;
}
?>
Each result of each card comes out as this:
<div id="1">
<img src="img/#.gif" alt="Card Name #" width="176" height="276"/><br/>
<h1 style="font-family: sans-serif;">Card Name #</h1>
</div><br />
In array.php, there is a 2-dimensional array which holds the paths and names of each card. For example:
$array = array();
$array[] = array("Card Name 1", "1");
$array[] = array("Card Name 2", "2");
$array[] ...
Anyways, I'm new at jquery and I need help into creating an animation which shows a card and changes the picture for every click in the order which it outputs until it runs out.
How can I create this animation? Do I need to change my code completely to accomplish this? Is there an easier method?
Thanks in advance!
There are lots of ways to do this, but here's the first that came to mind:
$(document).ready(function(){
var i=0,
$cards = $("div").hide();
$cards.click(function(){
$cards.eq(i).slideUp(function() {
i = (i+1)%$cards.length;
$cards.eq(i).slideDown();
});
}).eq(0).slideDown();
});
You should assign your card divs a common class and change the jQuery selector to use it, e.g., $("div.card"), but the general idea is select all the card divs and hide them, show the first, and on click of whichever one is showing hide it and show the next.
I've coded the above to keep looping around, but you can add your own end-of-deck actions as required.
Demo: http://jsfiddle.net/FrrhZ/
jQuery provides a number of animation methods, and you can make the animation as complicated as you like, but for demo purposes I just went with .slideUp() and .slideDown().
By the way, I'd remove the <br> elements from between your individual divs. You don't need them if only one card is displayed at a time, but even to display multiple cards divs are block elements and will display one under then other by default - if you need more spacing set the margins via CSS rather than adding spacer elements.
For your each individual div set opacity 0 and give class="card"
Then use this function
$(document).ready(function()
{
$(".card").animate({opacity:"1"});
});
Ex: http://jsfiddle.net/FrrhZ/10/
The $(".card") is a jQuery selector to get all elements with class ".card". The above will show each card appearing from nowhere, a cool effect.
This is just an example, you can do many more things with jQuery animate(), have a look http://api.jquery.com/animate/
For example, you can set the speed like this
$(".card").animate({opacity:"1"}, 1000);//animation to be completed in 1000 miliseconds.
Or you can show a metro like animation where the entity goes a little up while appearing, to do that add margin-top:10px and opacity:0 to your divs and then use this function
$(document).ready(function anim()
{
$(".card").animate({opacity:"1", marginTop:"0px"}, 'slow');//animate also excepts some keywords for speed like 'slow', 'fast'
});
Ex: http://jsfiddle.net/FrrhZ/14/
You can get even more creative with animate(), these were just few of many things possible with jQuery animate(), you can even chain animations, everything is provided in the link. Go ahead and explore.

How to make ID's unique on this 'Click to Reveal' script

I'm trying to add this script to my site but there are a list of the same element generated by the script "voucherCode" so am struggling here because when I test it, only the first element will 'reveal' no matter which one is clicked...
<!--EDIT-->
tried calling the script using a class which works but now all of them reveal:
Like Blazemonger said, browsers will not pick up multiple elements with the same ID. Id should be unique, and if you need something that repeats then uses classes.
Update
well first of all you need to add the class instead of ID
<div class="voucherCode">
if you use jquery (call it in the header first, google jquery)
$('.trigger_class').click(function(){
//do what you need to do here when clicked
//to access all of the voucherCode class you use $('.voucherCode').css('display', 'block');
});
Update 2:
if you only want specific ones to reveal then you need identifiers on those ones (class(2 or more) or id(only 1)) then target the ones you want to show. To make it more dynamic, you can add a rev or title attribute to the trigger anchor tag, and use jquery to grab that attribute and use it as the element you want to reveal
<a class="trigger_class" rev="reveal_class_or_ID">....</a>
then in the javascript
$('.trigger_class').click(function(){
//grab the rev from the a, this is use a class (hence the . if it is using id it would be #)
$("." + $(this).attr("rev")).css('display','block');
});
Lastly don't forget to add the reveal_class_or_ID to your items
Update:
I am not good with php but it seems like you have the option to add the iterator or index to
<div class="revealVoucher" id="reveal_dynamicID">
Reveal Code
</div>
<div class="voucherCode" id="show_dynamicID">
<?=$voucher_code?>
</div>
I don't know how iterator works in php but if you know php this should make sense

Jquery show/hide not working until refresh

I have a checkout page that has three fieldsets:
fieldset id="1", fieldset id="2", fieldset id="3". When the page loads, I need it to hide fieldsets 2 and 3 and only show fieldset 1. This is what my jquery looks like:
$(document).ready(function(){
$("#1").show();
$("#2").hide();
$("#3").hide();
$("#4").hide();
});
When I load the page I can see fieldset 1 and fieldset 2. If I refresh the page, it looks perfect, but upon first load, it's weird. Any suggestions?
First thing you need to do is properly name your ID's. ID's can't start with a number.
If you change the name to set_1 you can do the initial hide with CSS.
#set_2, #set_3, #set_4 { display:none; }
No JS needed.
Notwithstanding other issues, your IDs are invalid, which will always cause unpredictable results. Ids MUST begin with a letter.
Beyond that, it is difficult to answer your question without further insight into the code.
$(document).ready(function(){
$("#el_1").show();
$("#el_2, #el_3, #el_4").hide();
});
Should all be valid jQuery, assuming that there is no ID collision (you can only use an ID once per page).

Multi step/page form in PHP & CodeIgniter

I'm trying to build a multi step/page form in PHP and CodeIgniter and I was wondering if any of you could help me.
How can I have a multi step form in CI that updates rather than inserts again when you return to the previous step with the back button? How can I have a form that doesn't have those back button POST form resend messages?
Edit: without JS if possible
Thanks!
Here's my answer from another question. It gives you forward/backward ability without the chance to lose data, instantly jumps between pages, is EASY to code, needs no sessions, and is framework-independent (can be used in any situation):
I develop a product for the Psychology market that does 250 question psychological based testing. To make a test that isn't completely overwhelming, I break the form up into 25 question segments while outputting it in a loop via div tags with a sequential ID appended (ie. div1, div2, div3) Each div is set to display:none but the first.
I then provide the user with a button that toggles the current div + 1 (ie if on div 1, it would do a $(#div2).show() etc. Back buttons do the opposite.
The important part is that the form covers ALL divs. Then its just a matter of swapping out the forward/back button at the end with a submit button.
Voila! Yes, low-tech. But FAST....and no chance to EVER lose values going forward or backward.
So, a rough truncated example:
<form>
<div id="div1">
First 25 Questions
<input type="button">shows next div</input>
</div>
<div id="div2" style="display:none">
Second 25 Questions
<input type="submit">Submit Form</input>
</div>
</form>
Create a unique ID which you use in all steps of your wizard. Save that ID to the database upon the initial saving of your form.
Forward this ID to the next steps using a input type="hidden".
When saving a step, first try to match the ID and, if you find it int the database, perform an update instead of an insert.
To avoid the "do you want to resend post data", perform each wizard step in two CodeIgniter controller actions:
SaveStep5(POST: form instance ID + other "wizards step 5" inputs):
looks up the form instance ID in the database and performs insert/update commands;
redirects to LoadStep6 and passes the form instance ID in a GET parameter;
LoadStep6(GET: form instance ID);
looks up the form instance in the database,
if the instance is not found: error handling
if the instance is found, renders the input form for "step 6"
If you want to avoid those messages which warn the user about resending posts, and you also want to have multiple proper pages rather than just different steps in javascript, you can put the answers in the URL as GET parameters..
so after the first form submission, you will get form2.php? in the URL.. you can add those answers as hidden variables in form2 and so on.
It is not a very elegant solution though. I'd recommend you to use javascript: add a custom handler for form submission and submit form content via ajax, and then load the next form on ajax complete.
Also, like the other person answered, on the server end, you will need a unique ID which fetches/updates the submission data in the database.
I like the approach of waiting on the database update until all steps have been completed. You could store all the data in the intermediate steps in a session. I suppose you could even save the model object you're using (if you're using one) in a session and after all steps have been completed you can do the database insert.
I have a model to store my wizard data with a variable for each field on the form:
class Class_signup_data extends CI_Model {
const table_name="signups_in_progress";
public $market_segment; // there is a field named 'market_segment' in the wizard view
...
...
I have one controller to handle the whole process, with parameters for the session_id and the stage of the process we are at:
class Signup extends CI_Controller {
public function in_progress($session_id=NULL,$stage=1) {
$this->index($session_id,$stage);
}
public function index($session_id=NULL,$stage=1) {
if ($session_id===NULL) $session_id=$this->session->userdata('session_id');
...
...
In this controller I have a switch for which stage we are at - it looks for a 'Prev' button first:
switch ($stage) {
case 2:
if ($this->input->post('prev')) { // if they click Previuous, the validations DON'T need to be met:
$signup_data->save_to_db(array_merge(array('ip'=>$_SERVER['REMOTE_ADDR'],'session_id'=>$session_id,'signup_stage' => '1',
'signup_complete' =>'0'),$this->input->post()),$this->db,$session_id);
$this->load->helper('url');
redirect("/signup/in_progress/".$session_id."/1");
And later in the switch I use CI's Validations to display a form and process 'Next' if it was clicked or it is just being called with /signup/in_progress/session/2:
$this->form_validation->set_rules("your rules");
if ($this->form_validation->run() == FALSE) {
$this->load->view('signupStage2',array('signup_data'=>$signup_data));
} else {
$signup_data->save(array_merge(array('ip'=>$_SERVER['REMOTE_ADDR'],'session_id'=>$session_id,'signup_stage' => '3',
'signup_complete' =>'0'),$this->input->post()),$this->db,$session_id);
$this->load->helper('url');
redirect("/signup/in_progress/".$session_id."/3");
};
At the bottom of each view (eg 'signupStage2.php') I have the prev and next buttons:
<span class="align-left"><p><input type="submit" name="prev" class="big-button"
value="<- Prev" /><input type="submit" name="next" class="big-button"
value="Next ->" /></p></span>

Add and remove form fields in Cakephp

Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.

Categories