Show/Hide elements that are generated in a foreach loop - javascript

I am looping out forum entries and next to each one i have placed a button to show or hide the reply to comment form, i got this to work using a simple JS script. However because the script is looped out it only works for the top one. presumably because it cannot identify each element using an id because id won't be unique (and class would cause all of them to show/hide). I did think of adding something like {{$comment->id}} to the id so it would be unique but i cannot then use the JS script? can i?
Below is the relevant code:
#extends('layout')
#section('head')
<script>
$(document).ready(function(){
$("#showhidereply").click(function(){
$("#replycomment").toggle();
});
});
</script>
#stop
#section('content')
...
<!-- Comments -->
#foreach ($post->comments as $comment)
<span class="pull-right">
<div class=" btn-group">
<button class="btn btn">
<span class="glyphicon glyphicon-picture"></span> Owner's Name Here
</button>
<button class="btn btn btn-primary" id="showhidereply">
<span class="fa fa-reply"></span>
</button>
</div>
</span>
<p>{{ $comment->body }}</p>
</div>
<form method="POST" action="/forum/{{ $post->id }}/comments/{{ $comment->id }}/newresponse" id="replycomment">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="input-group" style="padding-top: 5px;">
<input type="text" name="body" class="form-control"></input>
<div class="input-group-btn">
<button type="submit" class="btn btn-primary">Reply to Comment</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
#stop
I did have someone make a suggestion of changing to:
Button
<button class="btn btn btn-primary" class="showhidereply" data-id="{{ $comment->id }}">
<span class="fa fa-reply"></span>
</button>
Form
<form method="POST" action="/forum/{{ $post->id }}/comments/{{ $comment->id }}/newresponse" id="replycomment-{{ $comment->id }}">
Script
<script>
$(document).ready(function(){
// change the selector to use a class
$(".showhidereply").click(function(){
// this will query for the clicked toggle
var $toggle = $(this);
// build the target form id
var id = "#replycomment-" + $toggle.data('id');
$( id ).toggle();
});
});
</script>
But that still doesn't work but the elements are all now unique.
Many Thanks!

Try using this,
<button class="btn btn btn-primary" data-id="{{ $comment->id }}" onclick="showHide('replycomment-{{ $comment->id }}');">
<span class="fa fa-reply"></span>
</button>
//javascript code
<script>
function showHide(id){
$("#"+id).toggle();
}
</script>

Related

How to get value of appended input div on appended button click?

I have simple HTML like this;
<div id="buildyourform">
<div class="row">
<div class="col-sm-6">
<div class="input-group mb-2">
<select class="form-control" id="language">
#foreach($language as $l)
<option value="{{$l->id}}" >{{$l->name}}</option>
#endforeach
</select>
</div>
</div>
<a href="javascript:void(0)" id="save-button" class="btn btn-light btn-sm ">
<i class="fa fa-ban"></i>
Upload
</a>
</div>
</div>
</div>
I have a plus button, using which I am appending the same fields below. Now I want to retrieve the respective selected language id with the click of the respective upload button.
But every time it returns me the value of first select field.
Here is what I have tried;
$(document).on('click', '#save-button', function(){
var obj=$(this);
//language = obj.closest("div[class=row]").find("select[id=language]").val();
language = $(this).parent().find("select[id=language]").val();
console.log(language);
});
Can anyone let me know how to get respective selected language id on respective button click?
You need to use prev function and change select[id=xxxx] by select#language
https://api.jquery.com/prev/
$(document).on('click', '#save-button', function(){
var obj=$(this);
//language = obj.closest("div[class=row]").find("select[id=language]").val();
language = $(this).prev('.col-sm-6').find("select#language").val();
console.log(language);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buildyourform">
<div class="row">
<div class="col-sm-6">
<div class="input-group mb-2">
<select class="form-control" id="language">
#foreach($language as $l)
<option value="{{$l->id}}" >{{$l->name}}</option>
#endforeach
</select>
</div>
</div>
<a href="javascript:void(0)" id="save-button" class="btn btn-light btn-sm ">
<i class="fa fa-ban"></i>
Upload
</a>
</div>
</div>

How to append a div to another div

Now I have multiples PHP for loop in my project exactly the same like one below but with different PHP variables of course. I also have an add button with appends a div element. The problem is because I have many for-loop and each for-loop has an add button so when I click on one add button of a particular div it appends a new div to all.
<div class="appendOuter">
<?php
foreach($query as $data){
$id = $data['ID'];
$initialAccess = $data['Access'];
if(strlen($initialAccess) > 3){
echo '
<div class="box" >
<input type="hidden" value='.$id.' class="ID">
<textarea class="Access">'.$Access.'</textarea>
</div>';
}
}
?>
<div class="text-center">
<button class="btn btn-success btn-add" type="button" onclick="addMorediv(this)">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
My javascript to append a new div
<script>
function addMorediv(index){
var element =$("<div class='box'><textarea class='Access'></textarea><i class='far fa-flag'></i></div>");
element.appendTo('.appendOuter');
}
</script>
Assuming that all your other HTML structure is similar to what you've demoed:
element.appendTo($(this).parent().parent());
Are you looking for something like this? Where when you click the add button, it adds a new text area under the existing textarea(s) already within that row? This is a jQuery specific answer, and doesn't require the "onclick" of button that you were using. It is also adding your content within a parent "row" div for ease of access navigating the DOM during the click event. So in your PHP for loop, you would echo out 1 of the rows in my example, using your PHP variables in the appropriate places like in your example.
$('.btn-add').on('click', function() {
var $box = $(this).parent().parent().find('.box:last');
var $element = $("<div class='box'><textarea class='Access'></textarea><i class='far fa-flag'></i></div>");
$element.appendTo($box);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appendOuter">
<!-- Assume your PHP generated 3 ".row" div rows in for loop -->
<div class="row">
<div class="box">
<input type="hidden" value="1" class="ID">
<textarea class="Access">1</textarea>
</div>
<div class="text-center" style="padding:10px;">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus">Add +</span>
</button>
</div>
</div>
<div class="row">
<div class="box">
<input type="hidden" value="2" class="ID">
<textarea class="Access">2</textarea>
</div>
<div class="text-center" style="padding:10px;">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus">Add +</span>
</button>
</div>
</div>
<div class="row">
<div class="box">
<input type="hidden" value="3" class="ID">
<textarea class="Access">3</textarea>
</div>
<div class="text-center" style="padding:10px;">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus">Add +</span>
</button>
</div>
</div>
</div>

submit form via jquery on select change event

i am trying to submit a form via Jquery when change event occurs in select field like this:
$('select#slc_level').change(function(event){
event.preventDefault();
console.log('changed')
$('form#formLevel').submit();
But, it seems Jquery can not capture the event. No errors message.
I have three 'widget' in the form but the select field is in level 'widget'.
Curiously, Jquery can to capture change event on input file field in digital object widget in another form that i have in this page.
The whole code in my page is:
<div class='col-md-3'>
<div class="widget">
<!-- Level widget -->
<h4 class="text-info">Níveis</h4>
#if(count($collection->collections) > 0)
<ul class="list-group">
#foreach($collection->collections as $sub_collection)
<li class="list-group-item">{{$sub_collection->name}}</li>
#endforeach
</ul>
<br>
#else
<p class="text-muted">Nenhum cadastrado</p>
#endif
<form method="post" action="{{route('collection.form_level')}}" id="formLevel">
<select id="slc_level" name="level_id" class="custom-select" autofocus>
<option>Selecione ...</option>
#foreach($levels as $level)
<option value="{{ $level->id }}">{{ $level->name }}</option>
#endforeach
</select>
{{ csrf_field() }}
<input type="hidden" name="collection_id" value="{{$collection->id}}">
</form>
</div>
<hr>
<!-- Digital Object widget -->
<div class="widget">
<h4 class="text-info">Objeto Digital</h4>
#if(count($collection->objects) > 0)
<ul class="list-group">
#foreach($collection->objects as $object)
<li class="list-group-item">{{str_limit($object->path,20)}} - {{$object->type}} - {{round(Storage::size($object->path)/(1024*1024),2)}}MB
<a id="{{$object->id}}" href="#" class="delobject text-danger" title="Remover item">(x)</a>
</li>
#endforeach
</ul>
<br>
#else
<p class="text-muted">Nenhum cadastrado</p>
#endif
<form method="post" action="{{route('object.attach')}}" enctype="multipart/form-data" id="formObject">
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" name="path">
<label class="custom-file-label" for="customFile">Escolher arquivo</label>
</div>
{{ csrf_field() }}
<input type="hidden" name="collection_id" value="{{$collection->id}}">
<input type="hidden" name="type" value="jpeg">
</form>
</div>
<hr>
<!-- Dimension widget -->
<div class="widget">
<h4 class="text-info">Dimensão e suporte</h4>
#if(count($collection->dimensions) > 0)
<ul class="list-group">
#foreach($collection->dimensions as $dimension)
<li class="list-group-item">{{$dimension->name}}, ({{$dimension->size}}) {{$dimension->type}}
<a id="{{$dimension->id}}" href="#" class="deldimension text-danger" title="Remover item">(x)</a>
</li>
#endforeach
</ul>
<br>
#else
<p class="text-muted">Nenhum cadastrado</p>
#endif
<button type="button" class="btn btn-primary btn-sm btn-block" data-toggle="modal" data-target="#dimensionModal">Inserir</button>
</div>
<hr>
<!-- Action widget -->
<div class="widget">
<h4 class="text-info">Operações</h4>
Editar
<button type="button" class="btn btn-danger btn-sm btn-block" id="btDelCollection" data-toggle="modal" data-target="#deleteModal" >Excluir</button>
{{($collection->published)?'Não publicar':'Publicar'}}
</div>
What is going wrong?
Try this
$("#slc_level").change(function(){
$('#formLevel').submit();
});
Try Jquery on Method
$(document).on("change",'#slc_level',function(){
$("#formLevel").submit();
});
I think you dont need to put select#slc'_level
$('select#slc_level').change(function(event){
event.preventDefault();
console.log('changed')
$('form#formLevel').submit();
you can directly put the id
like
$('#slc_level').change(function(event){
event.preventDefault();
console.log('changed')
$('#formLevel').submit();

How to get variable class name of jQuery from laravel blade loop

I want to Show/Hide replies for each comment. In order to do that, my jQuery selector has to be variable class name (so that I can show/hide replies of a specific comment without affecting replies of other comments). I've written the PHP code appending comment_id with the class to make the classes different. But I get these IDs from Laravel blade loop and I do not know how to do the same in jQuery. Here's my blade.php -
#foreach($comments as $comment)
<div class="box-comment">
<div class="comment-text">
{{$comment->body}}<br />
<button class="btn btn-link text-muted toggle-replies-{{$comment->id}}">Show/Hide Replies</button>
</div> <!-- /.comment-text -->
</div> <!-- /.box-comment -->
<div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;">
<input type="text" placeholder="Write a reply...">
</div>
#foreach($comment->replies as $reply)
#if($comment->id == $reply->comment_id)
<div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;">
<div class="comment-text">
{{$reply->body}}
</div> <!-- /.comment-text -->
</div> <!-- /.box-comment -->
#endif
#endforeach
#endforeach
And this is jQuery:
<script>
$(document).ready(function() {
$(".toggle-comments").click(function(){
$(".comment-box").slideToggle();
});
$(".toggle-replies-1").click(function(){
$(".reply-box-1").slideToggle();
});
});
</script>
I've manually put a '1' there and it shows/hides the replies of the first comment. I need to do it for all the comments. It shouldn't be difficult but I'm still learning jQuery. I hope someone can help me with it.
Try this :
#foreach($comments as $comment)
<div class="box-comment">
<div class="comment-text">
{{$comment->body}}<br />
<button class="btn btn-link text-muted show_hide_replies" id="{{$comment->id}}">Show Replies</button>
</div>
</div>
<div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;">
<input type="text" placeholder="Write a reply...">
</div>
#foreach($comment->replies as $reply)
#if($comment->id == $reply->comment_id)
<div class="box-comment reply-box-{{$comment->id}} initially-hidden" style="padding-left: 30px;">
<div class="comment-text">
{{$reply->body}}
</div>
</div>
#endif
#endforeach
#endforeach
<script type="text/javascript">
$(document).ready(function() {
$(".toggle-comments").click(function(){
$(".comment-box").slideToggle();
});
$(".show_hide_replies").click(function(ev) {
var getElem = $(this).attr("id");
$(".reply-box-"+getElem).slideToggle()
$(this).text(function(i, text){
return text === "Show Replies" ? "Hide Replies" : "Show Replies";
})
})
});
</script>

retrieve dynamically created values of hidden input with jquery

The following is the form created via php.
<form method="POST" action="http://localhost:8000/resources/11" accept-charset="UTF-8">
<label for="tag">Tagname</label>
<input class="form-control" id="tags" name="tagname" type="text">
</div>
<div id="tagnames" class="control-group clearfix">
<div class="tag-wrapper pull-left">
<button data-original-title='This is about quantum description.' data- placement="top" data-toggle="tooltip" class="btn btn-default tag_tooltip" type="button">
<span class="tagname">
quantum <i class='fa fa-times cancel'></i>
</span>
</button>
</div>
<div class="tag-wrapper pull-left">
<button data-original-title='This is about kids!' data-placement="top" data- toggle="tooltip" class="btn btn-default tag_tooltip" type="button">
<span class="tagname">
kids <i class='fa fa-times cancel'></i>
</span>
</button>
</div>
<input id="tag_ids" name="tag_ids" type="hidden" value="4,5">
</div>
<div id="tagname"></div>
<button type="submit" class="btn btn-primary submit_button">
<span class="fa fa-pencil-square-o"></span>
Update
</button>
<a class="btn btn-default" href="http://localhost:8000/resources">Cancel</a>
</form>
I want to alert(4) or alert(5) whichever corresponding tagname I click on.And I should be able to remove that id from the value.
Can anyone please help me?
I been scratching for two days for this problem.
I would suggest you to do this way by splitting into arrays and get the index:
$('.tag_tooltip .fa-times').on('click', function(){
var o = $('#tag_ids').val().split(','), // creates an array
idx = $(this).closest('.tag-wrapper').index(), // get the index of closest parent
value = o.splice(idx, 1); // remove the value
$('#tag_ids').val(value); // apply the new values
alert($('#tag_ids').val());
});

Categories