jQuery - Display a textbox when a link/button is clicked - php

I'm trying to put a reply button for each comment so when someone click on the button (for example "Reply"), a textbox will come up automatically where users can fill in a form.
I didn't do much so far...
PHP
<div id='replycomment' class='reply' onclick='jsReply($comment_id);'>Reply</div>
<div id='showreply'></div>
jQuery
function jsReply(comment_id) {
var form = '<form id="showReplyForm" action"add_reply.php" method="post">';
form += '<textarea name="replybody" cols="35" rows="2" maxlength="299"</textarea>';
form += '<input type="hidden" name="replybodyId" value="' + comment_id + '" />'
form += '<input type="submit" name="replysubmit" value="Reply"/></form>';
jQuery('#replybody').replaceWith(form); }
Can anyone PLEASE help me with that? it would be much appreciated.
I'm a bit confused with the way I need to link the id from jquery to php...
Thank you

To make your code work, do this: http://jsfiddle.net/MaqLQ/1/
within head:
var jsReply = function(comment_id) {
var form = '<form id="showReplyForm" action"add_reply.php" method="post">';
form += '<textarea name="replybody" cols="35" rows="2" maxlength="299"></textarea>';
form += '<input type="hidden" name="replybodyId" value="' + comment_id + '" />';
form += '<input type="submit" name="replysubmit" value="Reply"/></form>';
jQuery('#showreply').replaceWith(form);
}
you were missing a semi-colin at the end of one of your form concatenations. you were looking at 'replyBody' rather than the 'showreply' that exists in your html, and if your code wasn't global your html it wouldn't have been defined for the onclick. you were also missing the end angle bracket for your opening textarea tag.
also, i don't know your context and i'm not here for a code review, but among a few other things... you should really avoid using onclick within your html elements.

I recommend using the jQuery library.
Hide #showreply via CSS display: none; and place the HTML form within it.
$('#replycomment').click(function() {
$('#showreply').show();
});
I also recommend changing your IDs to classes since you will have multiple instances.

PHP
<div class='reply'>Reply</div>
<form action='add_reply.php' method='POST' class='reply-form'>
<textarea name='replybody'></textarea>
<input type='hidden' name='comment_id' value='<?php echo $comment_id; ?>' />
<input type='submit' value='Reply' />
</form>
CSS
.reply-form {
display: none;
}
Javascript
$(".reply").click(function() {
$(this).siblings(".reply-form").show();
$(this).hide();
});

Related

Need help assigning a php variable based on which button I press

I have a table with 20 buttons. I want to assign a php variable the same value as the button I press, something I figured would be easy but it's been two hours now without success.
foreach ($soccerseason->getTeams() as $team) {
if (($i % $number_per_row) == 0) {
echo '<tr>';
}
?>
<td style="background-image:url(<?php echo $team->crestUrl ?>);background-position: 50% 50%;background-repeat:no-repeat;background-size:100px 100px; width: 110px; height: 110px;">
<form action="JavaScript: showQuiz()" method="post" value="<?php echo $team->name ?>">
<button class="tableButton" value="<?php echo $team->name ?>"style="width:110px; height:110px"></button>
</form>
</td>
<?php
if (($i % $number_per_row) == $number_per_row - 1) {
echo '</tr>';
}
$i = $i + 1;
}
Say I want to echo the value of the button I press - how would you proceed? The function of the javascript is currently to hide/show different divs, nothing else. Thanks
One solution is to make the button call a Javascript function, that uses JQuery's ajax request to do whatever you want to do in PHP, and have the PHP output the name, which the Javascript will receive back, and change the div, or span to. I think the code would look something like this(in the Javascript):
function ajaxRequest(buttonName){
var data = "name=" + buttonName;
$.ajax({
url: "showPHP.php",
type: "post",
data: data
}).done(function(data){
document.getElementById("currentButtonSelectedDiv").innerHtml = data;
});
}
I am pretty sure you might need some other flags, but that is the basics of the javascript. The PHP would look something like this:
<?php
// Your php stuff
echo $_POST['name'];
?>
You generally keep the name attribute on the buttons the same as you have done, but vary the value.
Without seeing the rest of the table, you could potentially wrap the whole table in the form tag also.
<form method="post" action="readValue.php">
...
<button type="submit" name="teamName" value="team1">team1</button>
<button type="submit" name="teamName" value="team2">team2</button>
<button type="submit" name="teamName" value="team3">team3</button>
...
</form>
When the data is posted back, read the teamName value from the $POST variable.
<?php
$teamName = $POST["teamName"];
It's not entirely clear what you are doing with the javascript, but you can attach event handlers when the buttons are clicked also.

How to show/hide textareas in a loop with jQuery?

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().

Rendering javascript code in php document

I'm a beginner to PHP and I have a quick question. Is it possible to have javscript code injected into a document through php?
For example, suppose I wanted to inject a button that called a function after a form is filled out:
<html>
<head>
<script type = text/javascript>
function func() {
...
}
</script>
</head>
<body>
<form action = 'welcome.php' method = 'post>
Name: <input type = 'text' name = 'fname' />
<input type = 'submit' value = 'submit' />
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type = button onclick = func />'
}
?>
</body>
</html>
Would this work? If not, why not?
Any help would be great
Will work fine - just remember to close your quoted strings :
<form action='welcome.php' method='post'> // add ' here
Name: <input type='text' name='fname' />
<input type='submit' value='submit' /> // removed a couple of spaces (not required)
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type="button" onclick="func" />'; // added some quotes and a semicolon
}
?>
I have removed the spaces between the attributes and the values in HTML from type = "something" to type="something" although I can't find the "official" specification on this. It seems that the spaces are perfectly valid ...I think its my personal preference to have no white space there .....
Try:
echo '<input type="button" onclick="' . $_POST['fname'] . '" />';
SAMPLE
If fname=doSomething then use:
echo '<input type="button" onclick="' . $_POST['fname'] . '()" />';
and your rendered HTML would be:
<input type="button" onclick="doSomething()" />
Then you'd just need your function somewhere:
<script>
function doSomething() { }
</script>
If your current page is welcome.php and you ran this code, you would press the Submit button and the page would reload and have your new button.
But the best way to see whether this works for you or not is to run it. Why don't you try that first?

Using a JS variable inside php code?

I'm attempting to make it so that when you click a button, it'll add new fields to the page. I know that onclick can only take JS functions so I decided to try my luck making a JS script. At first I had tried to do
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
texters='';
num=nomnom+1;
for (var i=0; i<nomnom; i++)
{
texters+='<p>\
Please specify a file, or a set of files:<br>\
<input type="file" size="40">\
</p>\
<p>\
Caption : <br> \
<input type="text" size="30">\
</p>';\
}
document.write(texters+'<div>\
<input type="submit" value="Send">\
</div>\
</form>\
<br>' + '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>');
}
newInput(num);
</script>
</body>
</html>
but that didn't work. So I tried instead to add a little bit of php being that I know it better. I tried this :
<html>
<head><title>multiple line test</title><head>
<body>
<script type="text/javascript">
var texters='';
var num=0;
function newInput(nomnom)
{
document.write(<?php
tex='';
for (var i=0; i<=(nomnom); i++)
{
tex.='<p>
Please specify a file, or a set of files:<br>
<input type="file" size="40">
</p>
<p>
Caption : <br>
<input type="text" size="30">
</p>';
}
echo tex . '<div>
<input type="submit" value="Send">
</div>
</form>
<br>' . '<input type="button" value="new entry" onclick="newInput(num)">' . '</body></html>';
?>);
}
newInput(num);
</script>
</body>
</html>
But I know that won't work because I can't get the variable I'm using for the number of fields to use out of the JS and into the PHP. Is there any way I could force JS to put that number in $_POST so I can retrieve it without having to make another form? Or is there a better way to do what I'm trying to do?
You can set a hidden input field on the form, and have the Javascript populate that.
You should try using jquery http://jquery.com/ or a simialr scripting library as it will make manipulating the DOM much easier. Using jquery you can create an onClick function that will do what you want in a few lines of code:
var onClickAddInput = function()
{
$('div#your_div_id').append('<input type="text" size="30" />');
}
If you need to add more input boxes you could loop the append statement and give the individual input boxes ids that equal the loop number.
As commented PHP is for serverside, javascript for clientside. html is the ui elements which either can create. If you need something done on the server, do it in PHP, if it needs to be done on the client, do it in javascript. Here is a sample of javascript for you.
function newInput(nomnom)
{
var tex='';
for (var i=0; i<=(nomnom); i++)
{
tex+='<p>Please specify a file, or a set of files:';
tex+='<br/><input type="file" size="40"></p>';
tex+='<p>Caption :';
tex+='<br/><input type="text" size="30"></p>';
}
document.getElementById('form_id').innerHTML += tex;
}
when this function is called, it will create a number of new inputs and add them to the form with the id "form_id".

How to assign the value of a javascript variable to a php variable

I've a form.
<form action="inc/genxml.php" method="post">
<input id="nameTxt" name="name" type="text" value="test"/>
<button id="nameSave" class="left">Save</button>
</form>
And a div element #name
When I click the save button, I want to pass the position of the div #name to the form action file.
To get the position, I'm using jQuery .position().
Something like below. (which just prints out the coordinates)
$('#nameSave').click(
function() {
var pos = $('#name').position();
alert("left: " + pos.left + ", top: " + pos.top );
}
);
I want to pass the coordinate values (pos.left & post.top) to the form action file (in this case to the file genxml.php).
How should I do that?
The easiest way would be to use a hidden input field and use jQuery to set the value for this input field or these input fields in your case.
HTML:
<form action="inc/genxml.php" method="post">
<input id="nameTxt" name="name" type="text" value="test"/>
<input id="posLeft" name="posLeft" type="hidden" />
<input id="posRight" name="posRight" type="hidden" />
<button id="nameSave" class="left">Save</button>
</form>
JS:
$('#nameSave').click(
function() {
var pos = $('#name').position();
$('#posLeft').val(pos.left);
$('#posRight').val(pos.right);
}
);
add two hidden input to your form and use jQuery to change their value
Try this:
var pos = $('#name').position();
$("form").append('<input type="hidden" name="name_position" value="' + pos.left + ',' + pos.top + '" />');
Then read name_position value from the POST data in the server side code.

Categories