Results displaying one at a time with a delay - javascript

I have the following code that shuffles a selection I have in my database. Rather than having the results display all at one, I want to display a result one at a time with a delay between the results.
ie:
If I have 10 items in my database, I want one item to display, then a 3 second delay, then the second item to display, then a 3 second result, all the way until the last item (#10). Then possibly some sort of animation to it, like flying into the screen or the look of an item coming from a bag or something. (think picking a numbered order from 10 out of a bag).
I have been told that setInterval() could be an approach, but I have no idea how I could make this work with my code or if that is even the right approach.
How could I do this?
Here is how I shuffle the db results.
<form method="post">
<?php
foreach ($array as $result) {
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<div class="shuffle_results"><?php echo $shuffle_firstname . ' ' . $shuffle_lastname; ?></div>
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
}
?>
<input type="submit" value="Finalize Draft Order" name="insert">
</form>
UPDATE:
HTML File
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Users to be given draft order: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
Shuffled results: <br>
<div id="results"></div>
<form method="post">
<input type="submit" value="Finalize Draft Order" name="insert">
</form>
<img id='paperBag' src="http://www.thecuriouscaterpillar.co.uk/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/a/bag_to_white.jpg" width="200px" />
//Test Shuffle
var displayResults = function(data){
var i = 0;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
//i++;
$('#results').append('<div class="result" style="display:none;">' +
'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
$('.result').fadeIn(200);
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End test shuffle
PHP file
<?php
$con = mysqli_connect("localhost", "", "", "");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
if (isset($_POST['shuffle'])) {
shuffle($array);
}
}
echo json_encode($array);
?>

You could try something like this: This is just a test using faux data in the fiddle. Is this close to what you are looking for?
Client (using ctwheels's CSS)
<form method="POST">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<div id="#results"></div>
<script>
var displayResults = function(data){
var i = 0;
var interval = setInterval(function(){
if( i <= data.length){
$('#results').append('<div class="result" style="display:none;">' +
'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * array.length) + 'px'
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.getJSON('path-to-your-script.php', function(data){
displayResults(data);
});
});
});
</script>
Server
<?php
$con = mysqli_connect("localhost", "", "", "");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
}
echo json_encode($array);
?>

One way you can do this is by hiding all the results using CSS and then one by one show the values and animate using jQuery and CSS animate.
The code below hides all the items in shuffle_results by default (in CSS).
Then the jQuery iterates through each item in that class and shows the element, then animates its left and bottom properties to give it the correct positioning. The duration is set with time.
The rotation animations are made with CSS keyframes.
JSFiddle
JS
var time = 3000;
var lineheight = 24;
var angle = 90;
$('.shuffle_results').each(function (i) {
var i = i;
var $this = $(this);
setTimeout(function () {
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * (i + 1)) + 'px'
}, {
duration: time,
queue: false
});
}, time * i);
});
CSS
.shuffle_results {
display:none;
position:absolute;
left:70px;
bottom:100px;
z-index:-1;
-webkit-animation:spin 3s linear;
-moz-animation:spin 3s linear;
animation:spin 3s linear;
}
#-moz-keyframes spin {
0% {
-moz-transform: rotate(110deg);
}
100% {
-moz-transform: rotate(0deg);
}
}
#-webkit-keyframes spin {
0% {
-webkit-transform: rotate(110deg);
}
100% {
-webkit-transform: rotate(0deg);
}
}
#keyframes spin {
0% {
-webkit-transform: rotate(110deg);
transform:rotate(110deg);
}
100% {
-webkit-transform: rotate(0deg);
transform:rotate(0deg);
}
}
#paperBag {
position:absolute;
bottom:0px;
left:0px;
z-index:1;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="shuffle_results">Michael Jackson</div>
<div class="shuffle_results">Bob Saget</div>
<div class="shuffle_results">Indiana Jones</div>
<div class="shuffle_results">Elmo</div>
<div class="shuffle_results">Elmer J. Fudd</div>
<img id='paperBag' src="http://www.thecuriouscaterpillar.co.uk/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/a/bag_to_white.jpg" width="200px" />
EDIT
To use this with AJAX, you can do something like the following for JS
var time = 3000;
var lineheight = 24;
var angle = 90;
var array = ["Michael Jackson", "Bob Saget", "Indiana Jones", "Elmo", "Elmer J. Fudd"]; //For testing purposes. Shows how it adds one item at a time. This 'mimicks' your AJAX script
var i=0;
var interval = setInterval(function () {
j=i;
i++;
if(array.length<=i) window.clearInterval(interval);
// Where array.length is the count returned from PHP (or you can return a boolean value and check if it's true or false. Something like this:
//if(clearInt === true)
//{
// window.clearInterval(interval);
//}
//else
//{
// Do stuff below
$('#paperBag').before("<div class='shuffle_results'>"+array[j]+"</div>");
// Where array[j] represents the value returned from ajax
var $this = $('.shuffle_results:last');
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * (j + 1)) + 'px'
}, {
duration: time
});
}, time);
So you should have something similar to this: (note that this is untested - feel free to edit this answer if you encounter any bugs from it). To prevent duplicate results you can send the array from your JS function to your PHP function and subtract one array from the other to get the remaining values (use the database row's unique index and populate the JS array with those values and then subtract an array with all the values in your PHP script from it to get the remaining values. (using array_diff perhaps: http://php.net/manual/en/function.array-diff.php)
var time = 3000;
var lineheight = 24;
var angle = 90;
var array = [];
var interval = setInterval(function () {
$getJSON("something.php", {array: array}, function(result)
{
if(result.clearInterval === true)
{
window.clearInterval(interval);
}
else
{
array.push(result.firstName+" "+result.lastName);
$('#paperBag').before("<div class='shuffle_results'>"+result.firstName+" " +result.lastName+"</div>");
var $this = $('.shuffle_results:last');
$this.show()
.animate({
'left': 0 + 'px',
'bottom': $(document).height() - (lineheight * array.length) + 'px'
}, {
duration: time
});
}
});
}, time);

Related

Condition 'if' not working with .load()

I'm new here and I ask for your understanding
I am downloading from the script :
echo '<div id="xx">';
if ($nazwa == "1234") {
$nazwa_color = "red";
} else {
$nazwa_color = "black";
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : ' . $nazwa_color . ';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="b" class="wyk_edit"></div>';
echo'</div>';
And in javascript :
$(this).parent().parent().parent().find(".xx").load("setup-wyklady/wyk_edit_proces.php #xx");
does not address the condition 'if'. Why?
Thanks, but not working. Maybe I show all.
This is the portion of the file that you want to replace the method of load:
$wyk_query1 = mysql_query("SELECT * FROM nazwy_wyklady WHERE id_wykladu <> 9999 ORDER BY nr") or die('Błąd zapytania');
while($wyk=mysql_fetch_array($wyk_query1)){ //begin loop
$id_wykladu=$wyk['id_wykladu'] ;
$nr=$wyk['nr'] ;
$nazwa=$wyk['nazwa'] ;
echo '<form action="../wyklady/setup-wyklady/wyk_edit_proces.php" method="post"> ';
echo '<div style="float:left;width:590px;margin-top:2px;background:none" >';
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" readonly="readonly"
style="font-family:Tahoma;text-indent:2px;text-align:center;font-size:12px;width:30px;height:29px;background-color : White ; color : black;border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nr" value="'.$nr.'" class="wyk_edit_nr"></div>';
if($nazwa=="1234")
{
$nazwa_color = "red" ;
}
else
{
$nazwa_color = "black" ;
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;" class="xx"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : '.$nazwa_color.';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="'.$nazwa.'" class="wyk_edit"></div>';
echo '<div style="float:left;margin-left:15px;margin-top:1px;" >
<input style="display:none;cursor:pointer;width:25px;height:25px;background-color:White;color:rgb(193,135,107);" id="edit_button" title="zatwierdź zmiany" value="" class="wyk_edit_button"></div>' ;
echo '<input type="hidden" name="id_wykladu" value="'.$id_wykladu.' " class="wyk_edit_id"> ';
echo '</div>'; // 2a
echo '</form> ';
} //end of loop
and a script that loads (wyk_edit_proces.php):
$wyk_query1 = mysql_query("SELECT * FROM nazwy_wyklady WHERE id_wykladu ='$id_wykladu1'") or die('Błąd zapytania');
$wyk=mysql_fetch_array($wyk_query1) ;
$id_wykladu=$wyk['id_wykladu'] ;
$nr=$wyk['nr'] ;
$nazwa=$wyk['nazwa'] ;
echo '<form action="../wyklady/setup-wyklady/wyk_edit_proces.php" method="post"> ';
echo '<div style="float:left;width:590px;margin-top:2px;background:none" >';
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" readonly="readonly"
style="font-family:Tahoma;text-indent:2px;text-align:center;font-size:12px;width:30px;height:29px;background-color : White ; color : black;border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nr" value="'.$nr1.'" class="wyk_edit_nr"></div>';
if($nazwa=="1234")
{
$nazwa_color = "red" ;
}
else
{
$nazwa_color = "black" ;
}
echo '<div style="padding-left:0px;float:left;margin-left:1px;"><input type="text" autocomplete="off"
style="font-family:Tahoma;text-indent:2px;text-align:left;font-size:12px;width:500px;height:29px;background-color : White ; color : '.$nazwa_color.';border-width:1px;border-style:ridge;border-color:rgb(208,208,208);"
name="nazwa" value="b" class="wyk_edit"></div>';
echo '<div style="float:left;margin-left:15px;margin-top:1px;" >
<input style="display:none;cursor:pointer;width:25px;height:25px;background-color:White;color:rgb(193,135,107);" id="edit_button" title="zatwierdź zmiany" value="" class="wyk_edit_button"></div>' ;
echo '<input type="hidden" name="id_wykladu" value="'.$id_wykladu.' " class="wyk_edit_id"> ';
echo '</div>';
echo '</form> ';
and javascript:
<script>
//-----------------------------------------------------------------ajax - wykłady
$(document).ready(function(){
$(".wyk_edit_button").click(function () {
var id_wykladu1 = $(this).parent().parent().parent().find(".wyk_edit_id").val();
var nr1 = $(this).parent().parent().parent().find(".wyk_edit_nr").val();
var nazwa1 = $(this).parent().parent().parent().find(".wyk_edit").val().trim();
// alert(id_wykladu1 + " " + nr1 + " " + nazwa1)
if(nazwa1 == "")
{
alert("puste");
}
else
{
$.ajax({
type : "POST",
url : "setup-wyklady/wyk_edit_proces.php",
data : {
id_wykladu : id_wykladu1,
nr : nr1,
nazwa : nazwa1
},
context: this,
success : function() {
$(this).parent().parent().parent().find(".wyk_edit").load("setup-wyklady/wyk_edit_proces.php", function(){
alert("Done");
});
if (!$(".popup:visible").length) {
$(".popup").fadeIn(1);
}
},
complete : function(r) {
},
error: function(error) {
}
});
}
});
$(".popup .bg, .popup .container").click(function() {
$(".popup").fadeOut(250);
});
});
</script>
What you think about async:false ?
It's because the jQuery .load-Method works asynchronus as mentioned in this article. Try to use the invoked callback-function:
$(randomstuff).load("test",function()
{
alert("I'm done");
}

Codeigniter and javascript-add dynamic input and radio fields

hi guys I am pretty newbish in javascript and php for that matter. I am making a page where user will choose either to create a radio or input fields for others to solve.
Everything works fine except, when I save the form, fields are not in the order I added them because I first loop over the 'input' fields and then over the 'radio' fields. I know this is probably not the way to do it, feel free to give me an alternative.
Any help would be appreciated, thanks in advance.
VIEW
<h1>Add questions</h1>
<form action="" method="post">
<div id='pit'>
<span id="add_input"><a href="#" class='button' style='font-size:1.5em;'><span>» add input </span></a></span><br>
<span id="add_radio"><a href="#" class='button'style='font-size:1.5em;'><span>» Dodaj yes/no question</span></a></span>
</div>
<input type="hidden" name="id" value="<?= $this->uri->segment(3); ?>" />
<input id="go" class="button" name="submit" type="submit" value="Save" />
</form>
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /></p>' );
a=count;
document.write(a);
});
});</script>
<script type="text/javascript">
var count = 0;
$(function(){
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input id="radio_' + count + '" name="radios[]' + '" type="text" /></p>' );
});
});</script>
CONTROLLER
$id=$this->input->post('id');
if($_POST['fields']){
foreach ( $_POST['fields'] as $key=>$value ) {
$tip='input';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
if($_POST['radios']){
foreach ( $_POST['radios'] as $key=>$value ) {
$tip='radio';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
Something like this might work.
Maintain the same count variable in the JavaScript to keep track of which input is created.
Instead of using name="fields[]", use name="field_' + count + '" so you can iterate with a loop in the controller.
VIEW
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input name="field_' + count + '" type="text" /></p>' );
a=count;
document.write(a);
});
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input name="radio_' + count + '" type="text" /></p>' );
});
});
</script>
CONTROLLER
Use a regular expression to extract the necessary values.
$inputs = array();
$id=$this->input->post('id');
foreach($_POST as $key => $value) {
$matches = array();
if (preg_match('/(field|radio)_([\d]+)', $key, $matches)) {
$tip = $matches[1];
$count = $matches[2];
$inputs[$count] = array($id, $value, $tip);
}
}
Loop through the new $inputs array to call your add_questions method.
ksort($inputs);
foreach($inputs as $array) {
$id = $array[0];
$value = $array[1];
$tip = $array[2];
$this->page_model->add_questions($id,$value,$tip);
}

Text Box not saving in wordpress theme settings

I am creating a wordpress theme with theme options in wordpress. I like to add a dynamic add and remove textbox using jquery inside the theme settings page. My query is,
theme_settings.php
<?php
function theme_settings_init(){
register_setting( 'theme_settings', 'theme_settings' );
}
function add_settings_page() {
add_menu_page( __( 'Theme Settings' ), __( 'Theme Settings' ), 'manage_options', 'settings', 'theme_settings_page');
}
//add actions
add_action( 'admin_init', 'theme_settings_init' );
add_action( 'admin_menu', 'add_settings_page' );
//start settings page
function theme_settings_page() {
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false;
?>
<div>
<div id="icon-options-general"></div>
<h2><?php _e( 'Theme Settings' ) //your admin panel title ?></h2>
<?php
//show saved options message
if ( false !== $_REQUEST['updated'] ) : ?>
<div><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; ?>
<form method="post" action="options.php">
<?php settings_fields( 'theme_settings' ); ?>
<?php $options = get_option( 'theme_settings' ); ?>
<div id='TextBoxesGroup'>
<?php
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
?>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<p><input name="submit" id="submit" value="Save Changes" type="submit"></p>
</form>
</div><!-- END wrap -->
<?php
}
and my javascript file is:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
Now my question is, In the theme settings page, the add action and remove action works very fine but while saving the theme setting options the added textbox dissappears. It happens while refreshing the page too.
Please anyone help me how to keep those added textbox remains same if saving the theme options page.
Use .append() instead of .after().html(). This way your code goes inside the corresponding div element. I made use of jQuery also.
newTextBoxDiv.after().html(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >');
should be
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
To make the text boxes appear you need a while loop like this:
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
When you save them you could do this:
$counter = 0;
while (isset($_POST['theme_settings']['textbox'.$counter']) && $counter <= 10) {
update_option('textbox'.$counter, $_POST['theme_settings']['textbox'.$counter']);
$counter++;
}
// now remove the rest of them if they were previously set
// for example we now set only 5 of them and there were 10 before
// continue with counter from where we left in the previous while loop
while ($counter <= 10) {
update_option('textbox'.$counter, false);
$counter++;
}
EDIT:
function theme_settings_page() {
$updated = false;
if (isset($_REQUEST['updated'])) {
update_option('theme_settings', $_POST['theme_settings']);
$updated = true;
}
// ....
if ($updated) {
echo '<div><p><strong>';
_e( 'Options saved' );
echo '</strong></p></div>';
}
$counter = 1;
$options = get_option('theme_settings');
while (isset($options['textbox'.$counter])) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" value="'.$options['textbox'.$counter].'" />
</div>';
$counter++;
}
echo '<input type="hidden" name="updated" value="1" />';
// the rest of your form
}

Automatically creating the desirable number of radio button questions

I try to make web app for creating radio button questions (like survey). The problem is defining the array of radio button options in order to call it on php page and display it in the desirable order.
In my example below, I only got one radio button of each question, and I want to display all radio buttons input on the index.html page.
This should work like this: User opens index.html, there he add the first question (button Add Question) and the proposal of answers (for example 3, which he will get by pressing the Add option button and inserting text of it). The same he should do and for the question number 2, etc...
After that, by clicking PROCEED, it should lead him to the process.php page where the survey will display radio buttons questions. But there is a mistake, please see it on the link or in the code below:
LINK FOR TESTING
index.html
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
script.js
n=1;
var m = 1;
var moreradio = '<br/><input type="button" onclick="addmoreradio()" value="Add option">';
function addradio() {
m = 1;
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = n + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + moreradio + '<br/><div id="opid' + n + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
n++;
r = n-1;
}
function addmoreradio() {
var radio = '<input type="text" name="tag' + r + m + '"><br/>';
document.getElementById("opid"+r).innerHTML += radio;
m++
}
process.php
<?php
$question = $_POST['question'];
$length = count($_POST['question']);
$r=1;
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
$radioarray = $_POST['tag'];
$area = '<input type="radio" name="'.$r.'" value="'.$r.'">'.$radioarray$j$r.'<br/>';
$bla .= $j.') '.$question[$j].'<br/>'.$area.'<br/><br/>';
$r++;
}}
$content = $bla;
echo $content;
?>
You can did a mistake on form side while naming elements. Also you did mistake on backend while iterating. You can use following;
JS:
<script>
var m = 0;
function addradio() {
var textarea = document.createElement("textarea");
textarea.name = "question[]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = m + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + '<br/><input type="button" onclick="addmoreradio(' + m + ')" value="Add option">' + '<br/><div id="opid' + m + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
m++;
}
function addmoreradio(question_id) {
var radio = '<input type="text" name="tag' + question_id + '[]"><br/>';
document.getElementById("opid" + question_id).innerHTML += radio;
}
</script>
HTML:
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
PHP:
<?php
$question = $_POST['question'];
$content = '';
foreach ($question as $k => $v) {
$area = '';
$options = $_POST["tag" . $k];
foreach ($options as $key => $val) {
$area .= '<input type="radio" name="tag[]" value="'. $key .'">' . $val . '<br/>';
}
$content .= $k + 1 . ') ' . $question[$k].'<br/>'.$area.'<br/><br/>';
}
echo $content;
?>

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Categories

Resources