I am trying to show the results from a poll in the same area and page as the poll question without reloading the entire page. I am able to get the results and show them in a new page but I do not know how to replace the html in where I have the question and replace it with the html with the results.
HTML (with the poll question)
<div id="poll-area">
<!-- Voting poll -->
<fieldset>
<form action="javascript:void(0);" id="pollid" name="myform" method="POST">
<label><input type="radio" name="answer" value="left" id="option_left" />Yes</label>
<label><input type="radio" name="answer" value="right" id="option_right" />No</label>
<input type="submit" name="submit" id="submit" value="Vote" />
<input type="hidden" name="id" value="pollid" />
</form>
</fieldset>
<!-- End voting poll -->
</div>
AJAX call to handle the poll:
var $j = jQuery.noConflict();
jQuery(document).ready(function($j) {
$j("form").submit(function(){
var str = $j(this).serialize();
$j.ajax({
url: "poll_vote.php",
type: "POST",
data: str,
cache: false,
success: function(result) {
window.location.replace("poll_results.php");
}
});
return false;
});
});
I am guessing it is instead of the *window.location.replace("poll_results.php")* that I want to replace the HTML within the #poll-area with the #poll-area in the poll_results.php, but I do not know how do it.
HTML for the poll results (what is contained in poll_results.php)
<div id="poll-area">
<fieldset>
<legend>Results</legend>
<ul>
<li>
<span class="total-votes">Yes</span>
<br />
<div class="results-bar" style="width:52%;">
52%
</div>
</li>
<li>
<span class="total-votes">No</span>
<div class="results-bar right-bar" style="width:48%;">
48%
</div>
</li>
<li>
</ul>
<p>Total votes: 100</p>
</fieldset>
</div>
Thanks for the help!
in the output of poll_results.php you can remove the outer div with the id "poll-area". You don't want duplicate IDs when it is pulled into your current page.
For your jQuery, this should do the trick:
success: function(result) {
$j("#poll-area").html(result);
As I'm aware, anything that currently exiits inside the poll-area div will be overwritten with the result from the ajax query. (The voting options should disappear, and the results will be shown)
Edit (summary of comments): poll_vote.php should output the HTML contained within poll_results.php
Easiest but not the cleanest: use innerhtml and getElementById()
You will get something like:
var div = getElementById('poll-area'); //The poll itself
div.innerHtml = getElementbyId('answers'); //The answers
Note that I used 'answers' as ID, since you use the same ID for the answers and the poll. So you will get a nested which will not work. Give your first child of the answers () a new id called 'answers'.
If you know more of javascript, use the createElement to add a new element. This will improve speed and is better, but a bit more advanced.
Related
I am trying to create a question/answer system where a user can reply to existing questions. The question system is correctly posting and displaying to the database, but I am having difficulties replying to dynamically created questions.
To save space here is the code that is failing
$(document).ready(function() {
//make sure it was the postReply button
$("#postReply").on("click", function(){
//get the questionID the user just clicked on
var questionID=$(this).val();
//hide the reply button
$("#postReply").hide();
//show the reply framework
$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
});
});
Called from this line within a loop:
echo '<p><button type="submit" id="postReply" value='.$questionID.'>Reply</button></p> ';
echo '<div class="reply" id="reply'.$questionID.'">';
The issue that I hit is that I am updating and adding the div to every single question because of the .reply is incorrectly targeting. I can't seem to get it to target the questionID that was clicked. I have tried testing it with alerts but only the most recent question button is parsing to the script.
I can only hide the button from the most recent comment added.
This is the output of the HTML source that is being created from the SQL query
<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<p><button type="submit" id="postReply" value=34>Reply</button></p>
<div class="reply" id="reply34"></div>
When clicking the Reply button to the above question the code should look something like:
<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<div class="reply" id="reply34">
<div class="replycontent">
<p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p>
<p><button id="postAnswer" type="submit">Post Answer</button></p>
</div>
</div>
I am not sure to really understand the problem, but try replace this:
$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
by this:
$('#reply' + questionID).append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
Your fields have all a different ID attribute, so you can use it.
And to hide your button, since they have all the same ID, your selector can look like $('#postRelpy[value="' + questionID + '"]').
In the following example i have a script with a loop that fetches comments from database, and gives every comment a form with a textarea and submit button so that users can interact with every comment separately.
The follow code makes the page looks a big mess and disturbing due to the repetition of the texareas.
What i need is a jQuery code that will hide the textareas and allow me to show a selected textarea individually when a link or div is clicked. I will simplify what i want in the following code.
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
This can be done quite easily with JQuery. http://api.jquery.com/ will be helpful.
In this example, the client can click on the comment_header div to view or hide the comment box. Note I added an additional identifier to the divs. There are many different ways to select individual div elements - you might consider wrapping both the comment_header and comment_box divs under a container div with a unique id attribute. Here, I choose to use the .data() JQuery capability.
PHP:
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div data-index="<?= $i; ?>" style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div id="<?= $i; ?>" class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
JS/JQuery:
$(document).ready(function(e) {
$('.comment_box').hide();
$('.comment_header').on('click', function(e) {
$('#' + $(this).data('index')).toggle();
});
});
Hope this is helpful. Here is the JSFiddle: http://jsfiddle.net/EUQG2/
To hide unselected textarea when a particular textarea is focused
$(document).ready(function(){
$('textarea').focus(function(){
$('textarea').not(this).hide();
});
});
You can play around this. I hope it helps
At its simplest, assuming that all you want to do is to hide the textarea elements (in this case by hiding the parent .comment_box element), and to show them by clicking the preceding div element:
$('.comment_box').hide().prev('div').on('click', function(){
$(this).next('.comment_box').toggle();
});
JS Fiddle demo.
If you want only one .content_box/textarea visible at any given point:
$('.comment_box').hide().prev('div').on('click', function(){
var target = $(this).next('.comment_box');
$('.comment_box').not(target).hide();
target.toggle();
});
JS Fiddle demo.
References:
hide().
next().
not().
on().
prev().
toggle().
I'm working on a PHP self-evaluation form that has 5 question categories with 10 questions each. In the beginning of the application, I have 5 checkboxes to represent these categories, and they are automatically checked. The idea is that whenever user unchecks a category, the questions of that category instantly disappear from the form, and when they check it again, they come back. Something that should be achievable with the help of jQuery and AJAX.
I made the checkboxes with CodeIgniter's form_helper:
for($i = 1; $i<=5; $i++) {
$this->formapp_model->printCatName($i);
$data = array('name'=>'category$i', 'id'=>'category$i', 'value'=>'$i', 'checked'=>TRUE);
echo form_checkbox($data);
}
And I have a function to printing all 10 questions of the category from database after their category id, which works fine when I just post them as they are:
$this->formapp_model->printCategory(1);
$this->formapp_model->printCategory(2);
$this->formapp_model->printCategory(3);
$this->formapp_model->printCategory(4);
$this->formapp_model->printCategory(5);
Using the help of this:
Passing whether a checkbox is checked, via jQuery, to PHP
I was able to gather that for the jQuery, I need something like
var category1 = $('#category1:checked').val();
in order to check if the checkbox has been selected. I also tried
var category1 = $('#category1:checked').post();
as it seemed logical to use post in order to PHP to recognize it.
And for the print selection something like
if (isset($_POST['category 1'])) { $this->formapp_model->printCategory(1); } else { echo "This category is not selected."; }
I tried this, but PHP doesn't recognize the message that jQuery is giving it, meaning the category's questions disappeared permanently, whether the checkbox was checked or not. I checked with echo var_export($_POST); and noticed that all the jQuery is printing out is: array ( ). The question mentioned above was very informative, but missed some info that I would have needed to get it to work. The asker was also using an array instead of separate variables so I don't know how to edit it properly.
I'm a complete newbie with jQuery and AJAX so I have a hard time grasping what I need in order to get jQuery and PHP communicate dynamically the way I described. I have run around stackoverflow to find similar cases, but none of them have quite had what I need. However, I deeply apologize in case this is a repeativive question. Thank you to anyone who helps!
PHP is server side, you need the questions to appear/disappear client side meaning you want to make that happen using jQuery itself (or regular js but since you're already loading jQuery it's quicker just to use the library itself).
To be honest I'm not really following how your view is working so I'll just give some basic code to give you the idea. You create the checkboxes and the questions giving each a unique ID. Then in the on click method for the check boxes you determine which questions to show.
HTML:
<div id="checkboxes">
<input type="checkbox" id="box1" class="check" checked="checked"/>
<input type="checkbox" id="box2" class="check" checked="checked" />
<input type="checkbox" id="box3" class="check" checked="checked" />
<input type="checkbox" id="box4" class="check" checked="checked" />
<input type="checkbox" id="box5" class="check" checked="checked" />
</div>
<div id="question1" class="question">
<p>Question 1</p>
</div>
<div id="question2" class="question">
<p>Question 2</p>
</div>
<div id="question3" class="question">
<p>Question 3</p>
</div>
<div id="question4" class="question">
<p>Question 4</p>
</div>
<div id="question5" class="question">
<p>Question 5</p>
</div>
jQuery:
$(".check").on("click",function(){
var id = $(this).attr("id");
var id2 = id.substr(id.length -1);
var question = "question"+id2;
if($(this).is(":checked"))
{
$("#"+question).css("display","block");
} else {
$("#"+question).css("display","none");
}
});
Demo: http://jsfiddle.net/calder12/taSPX/1
I'm using the http://www.advancedcustomfields.com plugin to create custom fields in Wordpress. I'm specifically using the repeater field functionality.
On a page I have a repeater that has an unlimited amount of rows. The usual way of echoing out all the data is the following:
<?php $counter = 1; if(get_field('step_by_step_training')): ?>
<?php while(the_repeater_field('step_by_step_training')): ?>
<p class="training-<?php echo $counter; ?>"><?php the_sub_field('introduction'); ?></p>
<?php $counter++; endwhile; ?>
<?php endif; ?>
Is it possible to show one row of data at a time with a next button that when pressed will show the next row of data? I only want one row of data showing at a time so if row 1 is originally showing, when next is clicked it hides row 1 and shows row 2. Essentially creating a step by step process.
Eventually I'd like to include a form so the user can submit data.
UPDATE:
<form class="form" method="POST" action="<?php the_permalink(); ?>">
<?php $counter = 1; if(get_field('step_by_step_training')): ?>
<?php while(the_repeater_field('step_by_step_training')): ?>
<div class="form-row">
<p class="training"><?php echo the_sub_field('introduction'); ?></p>
<button class="next">Next Form Element</button>
</div>
<?php $counter++; endwhile; ?>
<?php endif; ?>
</form>
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
// hide all form-rows, but not the first one
$('.form-row').not(':first').hide();
$('button.next').click(function(e) {
// prevent the next buttons from submitting the form
e.preventDefault();
// hide this form-row, and show the next one
$(this).parent('div.form-row').hide().next('div.form-row').show();
});
});
});
</script>
You could do something simple like this using jQuery (I think this is what you wanted?):
$(document).ready(function() {
// prepend a 'previous' button to all form-rows except the first
$('<button>').addClass('previous').text('Previous').prependTo($('.form-row').not(':first'));
// hide all form-rows, but not the first one
$('.form-row').not(':first').hide();
// add the submit button to the last form-row
$('<input>').prop('type', 'submit').val('Submit Form').appendTo($('.form-row:last'));
// handle the previous button, we need to use 'on' here as the
// previous buttons don't exist in the dom at page load
$('.form-row').on('click', 'button.previous', function(e) {
e.preventDefault();
$(this).parent('div.form-row').hide().prev('div.form-row').show();
});
$('button.next').click(function(e) {
// prevent the next buttons from submitting the form
e.preventDefault();
// hide this form-row, and show the next one
$(this).parent('div.form-row').hide().next('div.form-row').show();
});
});
some example markup:
<form action="index.php" method="post">
<div class="form-row">
<label for="forename">Forename</label>
<input type="text" name="forename" />
<button class="next">Next Form Element</button>
</div>
<div class="form-row">
<label for="forename">Surname</label>
<input type="text" name="surname" />
<div style="clear: both;"></div>
<label for="another">Another</label>
<input type="text" name="another" />
<button class="next">Next Form Element</button>
</div>
<div class="form-row">
<label for="last">Last Form Element</label>
<input type="text" name="last" />
</div>
</form>
You can add as many form elements to each form-row as you want, here's a fiddle to play with
edit
Things to note here are that the previous buttons are injected to the DOM dynamically, and so is the forms submit button (notice how I've removed it from the last form-row in the markup)
Here's an updated fiddle
You could start with a jQuery accordion menu. Some CSS will allow you to minimize the real estate occupied by the deselected rows. If you want to actually discard and retrieve certain rows based on some identifiable characteristic (for instance, ID number), you'll need to go with AJAX.
You could write your own custom method with something like JQuery.
Assign a class to each row, and keep track of which one is selected, when viewing another row simply .hide() the one that was showing and .show() the one you wish to display.
If you want to keep your HTML cleaner, you could use the JQuery .data() functionality to assign identifiers to each element and refer to them that way as well.
Most of this all depends on your constraints with wordpress, how it looks & your actual HTML layout
After it's all written to the screen, can't you just hide everything but the first row? And then each time you click the button, have it hide everything and show the next row. Try using jquery's next() function. jquery - next()
Ah, looks like deifwud beat me to it with a better explanation.
I toggle a div using something like this -
<input type="radio" name="myRadio" value="myDiv_1" />MyDiv
<input type="radio" name="myRadio" value="myDiv_2" />MyDiv2
<input type="radio" name="myRadio" value="myDiv_3" />MyDiv3
<div id="myDiv_1"> 1 Some input fields, text </div>
<div id="myDiv_2"> 2 More input fields, text </div>
<div id="myDiv_3"> 3 More input fields, text </div>
JAVASCRIPT
$('#myDiv_1').hide();
$('#myDiv_2').hide();
$('#myDiv_3').hide();
$('input[name="myRadio"]').change(function() {
var selected_type = $(this).val();
switch(selected_type) {
case "myDiv_1":
$('#myDiv_1').slideDown();
//if others are visible just slideup
$('#myDiv_2').slideUp();
$('#myDiv_3').slideUp();
break;
case "myDiv_2":
$('#myDiv_2').slideDown();
//if others are visible just slideup
$('#myDiv_1').slideUp();
$('#myDiv_3').slideUp();
break;
case "myDiv_3":
$('#myDiv_3').slideDown();
//if others are visible just slideup
$('#myDiv_2').slideUp();
$('#myDiv_1').slideUp();
break;
}
}
);
This works fine. My question is how I can improve it and make it more flexible as if I have to MORE divs I have to modify all cases of switch.
Also should enclose the switch functionality in a function and bind this function to events such as click and change (just to ensure that toggling works)??
Thanks for your help.
This works, I just tested it.
<script type="text/javascript">
$(document).ready(function(){
$('.MyDiv').hide();
$('input[name="myRadio"]').change(function(){
var selected = $(this).val();
$('.MyDiv').slideUp();
$('#'+selected).slideDown();
});
});
</script>
The radio buttons should look like this, where the value is the id of the element that should be shown.
<form action="example.com" method="post">
<input type="radio" name="myRadio" value="myDiv_1" />MyDiv<br />
<input type="radio" name="myRadio" value="myDiv_2" />MyDiv2<br />
<input type="radio" name="myRadio" value="myDiv_3" />MyDiv3<br />
<input type="radio" name="myRadio" value="myDiv_4" />MyDiv4
</form>
And finally, the divs should look like this, all having the class MyDiv:
<div id="myDiv_1" class="MyDiv">Div number 1!</div>
<div id="myDiv_2" class="MyDiv">Div number 2!</div>
<div id="myDiv_3" class="MyDiv">Div number 3!</div>
<div id="myDiv_4" class="myDiv">Div number 4!</div>
The following is based on the code you pasted here - before using, read below:
$("div").hide();
$("input[name='myRadio']").change(function(){
$("div:not(#"+$(this).val()+")").slideUp();
$("div#"+$(this).val()).slideDown();
});
Before Using...
I would suggest you add a class to each of the collapsable panels, maybe .panel. And then update the selectors to modify only div.panel instead of every div on the page.
your solution doesn't work in IE 8-- actually has the opposite behavior. Use the "click" function instead of "change"
$('.myDiv').hide();
$('input[name="myRadio"]').click(function(){
var selected = $(this).val();
$('.myDiv').slideUp();
$('#'+selected).slideDown();
});