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().
Related
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 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.
I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>
My problem has to do with PHP, jQuery and CSS.
I want to make a lightbox in a while loop, and then have the lightbox give me info for each of the rows.
There is a problem because it makes lightboxes for each of the rows, and with position:absolute we can see only the last row from the result. I don't want to see the last but I want the light box to show me info depending on which row I have clicked.
Here is the code:
jQuery:
$(document).ready(function(){
$('.lightbox').click(function(){
$('.boxi').css('display','block');
});
});
PHP:
$result = $db->query("SELECT * FROM destinations WHERE direction=1;");
while ($rows = mysql_fetch_array($result)) {
$name = $rows['name'];
$table .= '<div class="destionations">
<div class="name">Prej: <strong>'.$name.'</strong></div>
<table width="100%" class="extra" cellspacing="1" cellpadding="5" border="0" >
<tr class="bgC3" style="font-weight:bold">
<td width="20"></td>
<td>Deri</td>
<td width="50">Çmimi</td>
'.managment::cmimet_e_caktuara($name).'
</tr>
</table>
<div class="buttoni">
test
<div class="boxi">'.$name.'</div>
<form action="" method="POST">
<input type="text" name="new_city">
<input type="hidden" name="prej" value="'.$name.'">
<input type="submit" name="new_dest" value="Shto destinacionin">
</form>
</div>
</div>';
}
}
It looks like you're wanting to turn a div into a lightbox? You could just try adjusting your current CSS on .boxi to display: none; and set a z-index on it before - then adjust your javascript to something like this:
$('.lightbox').click(function(){
$('.boxi').show();
return false;
});
You could get much more complex with grabbing the next lightobx container when .lightbox is clicked - I'd recommend checking out the plugin Fancybox at fancybox.net, that's the one I typically use. Good luck!
$(document).ready(function(){
$('.lightbox').click(function(){
$('.boxi').css('display','block');
$('.boxi').css('z-index','999999');
});
});
I tried this because I thought that it will give higher z-index to the selected block but no its really primitive and wont ever work.
I am really too far from jQuery!
I'm using the jQuery tag-it plugin, which basically has an input field. Everything works well, but I am unable to receive the input field value by submitting the form with PHP.
Here's the form part:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST[mytags];
echo $tags;
}
?>
The demo of the plugin is here: http://levycarneiro.com/projects/tag-it/example.html
and the javascript code is here: http://levycarneiro.com/projects/tag-it/js/tag-it.js
I'll be thankful for any help.
in tpl
<script type="text/javascript">
$(document).ready(function() {
$("#tags-input").tagit({
fieldName: "tag[]",
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
});
});
</script>
use fieldName: "tag[]" attribute, in backend print_r($_POST) and check what it will display
ul is not a form element which would be submitted, it's a UI element. And you need to use quotes around your array indexes, like this:
if (isset($_POST['submit'])) {
the code should look like this:
<?
if ($_POST['submit']) {
$tags = $_POST['mytags'];
echo $tags;
}
?>
you forgot the enclosing '
if you forget that php treats the submit in $_POST[submit] as a constant
EDIT:
try this:
<?
var_dump($_POST);
?>
The acutal tags are stored in this form field which is created for each tag:
function create_choice (value) {
// some stuff
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
// some other stuff
}
So you must look out not for 'mytags' but for $_POST['item']['tags'] in your PHP Code which will then give you an array of the tags.
There should be NO posted data
your code does not use any input fields!
Looking at your plugin, it seems to create hidden input fields on the fly as you add tags.
Assuming that part of the code is actually working, put the following into your PHP code.
<?php
var_dump($_POST); //this has to be in the page you POST to
?>
See if all your tags are showing up. If it is, then your JS works and your PHP is at fault. As user #ITroubs mentions, you should quote your array indices. See if that fixes it.
If no data is displayed, then your JS plugin is not working properly.
Using firebug, add a couple of tags and inspect inside the LI element of your list and see if any hidden INPUTS are being created.
Also check if there are any JS errors being reported.
Tested and solved:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags" name="item[tags][]"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST["item"]["tags"];
foreach($tags as $i=>$v)
{
$tagsf .= $v;
if($i < (count($tags)-1))
$tagsf .= ",";
}
echo $tagsf;
//This shows the tags with ",". Example: dog,cat,bird,onion
}
?>