jQuery on click fade in hidden element in while loop - javascript

I have a form in while loop which activates when I click on Reply button. This I can do simply but its in while loop and requires a unique ID. With my code its working till now but it works only for the first result. When I click on the other results nothing happens. Even though I have already assigned a unique ID its not working. My code is given below:
jQuery part:
$(document).ready(function() {
$("#reply").on('click', 'a.click', function() {
var rowid = $(this).attr("data-rowid");
$(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
$(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
});
});
PHP HTML part:
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>
<div id="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="<?php echo $cmt_id?>" style="display:none;">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="cmt_form_id_<?php echo $cmt_id?>">
<input type="hidden" name="status_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id?>" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_<?php echo $cmt_id?>"></textarea>
</form>
</div>
<?php } ?>
Please help with jQuery/Ajax.

HTML
<div class="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="1" style="display:none;">
<form method="post" action="#" class="full-width cmtform" id="cmt_form_id_1">
<input type="hidden" name="status_id" value="1" id="cmtsid_1" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_1"></textarea>
</form>
</div>
<div class="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="2" style="display:none;">
<form method="post" action="#" class="full-width cmtform" id="cmt_form_id_2">
<input type="hidden" name="status_id" value="2" id="cmtsid_2" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_2"></textarea>
</form>
</div>
javascript
$(document).ready(function() {
$(".reply").on('click', 'a.click', function() {
var rowid = $(this).attr("data-rowid");
$(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
$(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
});
});
jsbin is listed in comments above.

Related

How to return second register form on submition?

I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.

JS not running inside modal after dynamically change of it's id

I'm using bootstrap modal and I'm calling a autocomplete function inside of it, it all works well when it's set like this:
Button that has a data-target to call the id of the modal:
data-target="#modalAdicao"
And the div with the id set to match the data-target:
id="modalAdicao"
But because it's called inside a PHP foreach and I need keep the information, I have to set the id of the modal like the id of the mysql line I'm dealing with, like this:
data-target="#modalAdicao<?php echo htmlspecialchars($idModal); ?>"
And:
id="modalAdicao<?php echo htmlspecialchars($idModal); ?>"
After this, the information is kept but the js stops working, it's like I never called it, but it's there, like it always been:
<script src="js/procura-paciente.js"></script>
Anyone can help?
When modal opening, the id is changed and the modal is re-drawn. But the js event is defined.
Try to use this
$(document).on('input','.busca', limpaCampos);
The for loop generate many #busca, the id is unique. Change to use class instead. For example
php form
<form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">
<div class="form-inline">
<div class="form-group">
<label for="busca" class="sr-only">Identidade</label>
<input type="text" id="busca" data-id="<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control busca" required>
</div>
<div class="form-group">
<label for="nascimentoPaciente" class="sr-only">Nascimento</label>
<input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control" required>
</div>
</div>
<div class="form-group">
<label for="nomePaciente"></label>
<input type="hidden" name="nomePaciente" class="form-control nomePaciente">
<input type="hidden" name="cpfPaciente" class="form-control cpfPaciente">
<input type="hidden" name="horaPaciente" value="<?php echo htmlspecialchars($horarios[$i]); ?>" class="form-control horaPaciente">
<input type="hidden" name="dataPaciente" value="<?php echo htmlspecialchars($data_agendamento_convert); ?>" class="form-control dataPaciente">
<input type="hidden" name="medicoPaciente" value="<?php echo htmlspecialchars($medico_completo); ?>" class="form-control medicoPaciente">
<input type="text" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">
<label for="observacaoPaciente"></label>
<input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control" required>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
<button type="submit" class="btn btn-primary">Agendar</button>
</div>
</form>
js
$(function() {
$('#tableteste').on('input', '.busca', function(){
var busca = $(this).val();
var form = $(this).parents().eq(2);
if(busca == ""){
form.find('.nomePaciente').val('');
form.find('.nomePaciente2').val('');
form.find('.rgPaciente').val('');
form.find('.nascimentoPaciente').val('');
form.find('.cpfPaciente').val('');
}
});
.....
});

How to hide an form after form is submitted

I am not that much good at programming. i am working on one feature, that is form hiding after the submit of form data. Here number of forms created dynamically. i need to hide the form once we submit the form data, to prevent multiple submission of form. here i used form inside div i also tried for div hiding. it is not working please let me know the solution.
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
function frmsubmit()
{
var frm = document.getElemetsByName('formdata')[0];
frm.submit();
frm.reset();
return false;
}
$('#submit_0').click(function() {
$.ajax({
url:"section.php?status=result",
data:$('#f_0').serialize(),
success:function(data)
{
alert(data);
$('#f_0')[0].reset();
}
});
});
// Haven written same code for submit_0 to submit_10
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Enter the values:</h3><br>
<ul class="nav nav-tabs">
<?php
foreach($clasarr as $temp)
{
?>
<li><a href="#<?php echo $temp; ?>"> <?php echo $temp; ?> </a </li>
<?php
}
?>
</ul>
<div class="tab-content">
<?php
$y=0;
foreach($clasarr as $temp)
{
?>
<div id="<?php echo $temp; ?>" class="tab-pane fade">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_<?php echo $y; ?>">
<div class="col-md-offset-2 col-md-10">
<h3> CLASS: <?php echo $temp; ?></h3>
</div>
<input type="text" name="idr" id="idr" value="<?php echo $id; ?>" hidden>
<input type="text" name="clss" id="clss" value="<?php echo $temp; ?>" hidden>
<div class="form-group">
<label class="control-label col-sm-2" for="totalb">Budgeted #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="totalb" id="totalb" value="<?php echo $totalarr[$y]; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="received">Received #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="received" id="received_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="deleted"> Deleted data #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="deleted" id="deleted_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/ >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="csvno"> CSV Number #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="csvno" id="csvno_<?php echo $y; ?>" onload="getupload(<?php echo $y; ?>)">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="duplicate"> Duplicate #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="duplicate" id="duplicate_<?php echo $y; ?>" onblur="getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)" onclick="getupload(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="upload"> Upload #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="upload" id="upload_<?php echo $y; ?>">
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-2">
<input class="btn btn-info" type="submit" name="submit" id="submit_<?php echo $y; ?>" value="submit" onclick="frmsubmit()">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</div>
</div>
</form>
</div>
<?php
$y++;
}
You may not need both input type = "submit" and onclick event handler, the submit input will be enough.
Also there is a need to prevent default behaviour of the submit button since ajax is used to submit the form data.
Replace the input type "submit" with this
<input class="btn btn-info" type="submit" name="submit" id="someId" value="submit">
Also while dynamically creating the form use a class instead of id(presuming id is also dynamic so every new form creating will change the id)
<form name="formdata" action="" method="post" class="form-horizontal someFormClass"
id="someDynamicId">
// rest of the code
</form>
To prevent the default behaviour add event.preventDefault();.Inside the ajax success delegate the event of hiding the form from body
$('#submitButtonId').click(function(e) {
e.preventDefault();
var form = $(this).parents('form.someFormClass');
$.ajax({
//Rest of the code
success:function(){
$('body').find(form).hide()
}
})
});
Hopefully this pseudo code will be useful
A ridiculously simplified version of what you're trying to do. A form, in a div, with a jQuery on click hook that will hide the div on submit click.
$('#submit').click(function() {
$('#f_0').hide();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="f_0">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_1">
<input class="btn btn-info" type="submit" name="submit" id="submit" value="submit">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</form>
</div>
#AvinashT But is the ajax call being made or not?
#gurvinder372 ajax is called and form data is entring into table
successfully
Based on above discussion, you just need to add this line in the success handler to hide the form
$('#submit_0').closest( "form" ).hide()
Here number of forms created dynamically. i need to hide the form once
we submit the form data, to prevent multiple submission of form.
Form is being submitted multiple times, because you have two handlers (one is via onclick and other via submit click event handler).
You need to remove the onclick="frmsubmit()" from the form tag since submit click event handler is already taking care of form-submission.

Can I target a specific form for commenting with jquery

I have created a news system on my web page where I use while loop to echo my news on a page. With news I created a form for news where I target it by name and I want to use jquery to process the results. When I use php it works fine but I want to avoid reloading page with submitting form and immediate post comment to page.
my form looks like this:
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
my php code looks like this:
if (isset($_POST['comments' . $row['news_id'] . '']) === true && empty($_POST['comment']) === false) {
global $user_data;
$user_id = $user_data['user_id'];
$connect_id = $_POST['news_id'];
$type = $_POST['type'];
$time = date('Y-m-d H:i:s');
$comment = $_POST['comment'];
$comment = sanitize($comment);
mysql_query("INSERT INTO `comments` (`user_id`, `connect_id`, `type`, `time`, `comment`) VALUES ('$user_id', '$connect_id', '$type', '$time', '$comment')");
}
If I try to do somethink like this:
$(".comment-btn").click(function(e) {
e.preventDefault();
var text = $('.comment-area').val();
console.log(text);
$('.comment-area').val('');
});
It targets only the form where is the first news and doesn't target all the forms.
Is there any way to do this differently???
Thanks for helping.
You could try something like the following:
$(".comment-btn").each(function(){
$(this).click(function(e) {
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
The problem is that while this $(".comment-btn") returns an array of all the button in the forms you mentioned, this $(".comment-btn").click(... attaches a click event handler only for the first item of the array.
$(function(){
$(".comment-btn").each(function(){
$(this).click(function(e){
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
You could use jQuery on function to bind "click" event to all buttons with comment-btn class. However, it'll be important to then identify which comment-area you want to refer to. If that is not done, it'll simply erase the values of all fields / textareas with class comment-area.
$(".comment-btn").on("click", function(e) {
e.preventDefault();
var text = $(this).parent().find('.comment-area').val();
console.log(text);
$(this).parent().find('.comment-area').val('');
});
Working example with the only change being that input type for buttons is changed from "submit" to "button":
https://jsfiddle.net/L87n4Ljo/
Likewise, if you'd like to submit a particular form when the button is clicked, you'll have to do so by specifically identifying that form by using parent() function.
Try this, here we are blocking the default form submit which i think you will need if you don't want to reload the page.
$(".comments").on("submit", function(e) {
e.preventDefault();
var text = $(this).find('.comment-area').val();
console.log(text);
$(this).find('.comment-area').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

multi form ajax php social comment system

I have a lot of these forms that I post with PHP. They are under every article in my page, but when I submit the form with these ajax functions it only sends to the first form of the page. Why? I want send these form separately what am I doing wrong?
<script type="text/javascript" >
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var comment = $("#comment").val();
var post_id = $("#post").val();
var dataString = 'name='+ name + '&comment=' + comment+ '&post_id=' + post_id;
if(name=='' || comment=='')
{
alert('Please Give Valid Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commenti.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
});
});
<script>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
First of all, as has been said in the comments, don't use repetead IDs. If you don't intend to use Ids as a unique identifier, use classes.
<ol class="timeline update">
<div id="flash"></div>
<div >
<form action="#" id="form" method="post">
<input type="hidden" class="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" class="name" value="<?php echo $username; ?>"/>
<textarea class="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
</ol>
In your javascript code, you are trying to get the id name with var name = $('#name'), right? What name?
Also, try to send your requeste with an array rather than a string.
Something like this:
$(".submit").click(function()
{
var name = $(this).parents('form:input.name').val();
var comment = $(this).parents('form:input.comment').val();
var post_id = $(this).parents('form:input.post').val();
var data = {'name': name,
'comment': comment,
'post_id':post_id},
$.ajax({
type: "POST",
url: "commenti.php",
data: data,
success: function(html){
//do stuff
}
}
Access your variable in PHP with $_POST['varName'];
Hope it helps.

Categories