Trigger the form submit button from $().html() - javascript

I have such a template when the user clicks the edit glyphicon, it will prompt a form for further editing:
<div class="post-menu pull-left">
<a class="editCommentLink" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a> &nbsp
<a class="delCommentLink" id="{{ comment.id }}" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
I employed ajax to send the get request and update the content with $commentNew.html(commentEditForm);
<script>
$(document).ready(function(){$(".editCommentLink").on("click", function(e) {
e.preventDefault()
var comment_id= $(e.target).attr("id")
// Retrieve the top node of comment-right
var $commentRight= $(e.target).closest(".comment-right")
$.ajax({
type: "GET",
url: `/ article/comment/edit /${comment_id}`,
success: function(data){
var ret=JSON.parse(data)
var body=ret['body']
var commentEditForm= `
<form action="#" method="post" > {% csrf_token % }
< div class="form-group" >
< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >
< button class="btn btn-primary" id="editSubmitBtn" > Save Edits < /button >
<a href="#" > cancel < /a >
< / div >
< /form >
`
var $commentNew= $commentRight.find(".post-text");
$commentNew.html(commentEditForm);
}, // success
});//end of ajax
})//end edit click
</script>
However, there's no feedbacks when I am triggering button id="editCommentBtn" to submit the form data,
});//end of ajax
})//end edit click
$(document).ready(function (e) {
//still in edit click event
$("#editCommentBtn").on("click", function (e) {
e.preventDefault();
alert('button clicked');
...
});//submit click event
})
I experiment to solve the problem, what confused me is that if I change $(".editCommentBtn") to its grandparent $(".post-text"), the browser alert me ('button clicked'),
I attempted to break the bulk of var commentEditForm= to single elements like:
$newForm = $('<form action="#" method="post" > {% csrf_token % } < /form >');
$newFormGroup = $('< div class="form - group" >< / div >');
$newText = $('< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >');
$newSubmit = $('< button class="btn btn-primary" id="editCommentBtn" > Save Edits < /button >')
$(.post-text).append($newForm);
$newForm.append($newFormGroup);
$newFormGroup.append($newText);
$newText.after($newSubmit);
There are many manual labors,
How to solve the problem elegantly?

I don't see element with Id #editCommentBtn in your unrendered code. But test this:
$(document).on("click","#editCommentBtn",function (e) {
e.preventDefault();
alert('button clicked');
});
With this way all elements that you inject them to your document (and have this id), will respond to this click function.

Related

Ajax bind click to another element

I have a button (is anchor tag with class vote) which should be clicked to vote for an article via ajax request. After that I want to update the votes count in my blade view (its a laravel application). The div with the class points should be updated but I dont know how to bind points on click to the ajax call?
I want to bind the .point to ajax call like I did it with $button to then update the div with the class points.
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}"></a>
Main code:
<div data-id="{{ $article->id }}" class="points">{{ $article->votes->count() }}</div>
$(document).on('click','.vote',function(){
var $counter = $(this).next();
var $button = $(this);
var id = $button.data('id');
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type:'POST',
url:"{!! URL::to('article/vote/') !!}/" + id,
dataType: 'JSON',
data: {
"_method": 'POST',
"_token": token,
"id": id,
},
success:function(data){
$counter.html(data.count);
var color = data.voted ? '#bbb' : '#38c172';
$button.css('background-color', color);
console.log('success');
console.log(data);
},
error:function(xhr){
if (xhr.status == 401) {
window.location.href = "{!! URL::to('login') !!}";
} else if (xhr.status == 403) {
window.location.href = "{!! URL::to('email/verify') !!}";
}
},
});
});
So you want your .points to be updated and not the a button you clicked.
First, make sure your a and .points are children of the same div element and there like:
<div>
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}">
button
</a>
<div data-id="{{ $article->id }}" class="points">
{{ $article->votes->count() }}
</div>
</div>
...
<div>
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}">
button
</a>
<div data-id="{{ $article->id }}" class="points">
{{ $article->votes->count() }}
</div>
</div>
Then in your JavaScript define the counter element like
var $counter = $(this).parent().find('points');
and update your success: method to apply CSS class and put data count:
$counter.html(data.count);
var color = data.voted ? '#bbb' : '#38c172';
$counter.css('background-color', color);
Let me know if it makes sense and you can finish the implementation.

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

Search with ajax on click and show results in same page laravel

I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?
It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method
You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});

pass variables to a bootstrap modal

I have a javascript confirm / cancel pop up box that dynamically unchecks a checkbox and also dynamically hides or shows a menu_entry that is part of a list that appears on the form, only when the user selects the ok button on the js confirm pop up box.
I am now trying to change the js confirm to a bootstrap modal, but I am uncertain how to pass the variables to the bootstrap modal code and get the same functionality of the js confirm pop up box.
Here is my working html code that has the call to the javascript confirm pop up box:
{% for id, menu_entry, selected, item_count in menu_entries %}
<div class="available_resume_details_height">
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});"
/>
<span style="cursor: pointer;"
rel="popover"
data-content="{{ menu_entry.tooltip }}"
data-original-title="{{ menu_entry.label }}"
{{ menu_entry.label }}
</span>
</div>
{% endfor %}
Here is my javascript code to display the confirm pop up and uncheck the checkbox and show/hide the list entry:
function checkboxUpdated(checkbox, count, label, id) {
if (checkbox.checked) {
$('#menu_entry_' + id).show();
} else {
if (count > 0) {
if (! confirm('{% trans "You have '+ count +' saved '+ label +'.\n\nAre you sure you want to delete your ' + count + ' saved ' + label +'?" %}')) {
checkbox.checked = true;
return;
}
}
$('#menu_entry_' + id).hide();
}
}
Here is the new html code that has the call to the bootstrap modal. This does make the bootstrap modal appear:
{% for id, menu_entry, selected, item_count in menu_entries %}
<div class="available_resume_details_height">
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
{% if selected %}
data-confirm="{% blocktrans with entry_label=menu_entry.label %}Are you sure you want to remove your {{ item_count }} selected {{entry_label}} Resume Details?{% endblocktrans %}"
{% endif %}
/>
<span style="cursor: pointer;"
rel="popover"
data-content="{{ menu_entry.tooltip }}"
data-original-title="{{ menu_entry.label }}"
{{ menu_entry.label }}
</span>
</div>
{% endfor %}
Here is my bootstrap modal code that is not working. I am unsure how to pass the variables and get the same functionality of the js confirm pop up:
$(document).ready(function() {
$('input[data-confirm]').click(function(ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal modal-confirm-max-width" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"><icon class="icon-remove"></icon></button><h4 class="modal-title" id="dataConfirmLabel">{% trans "Confirm" %} - {{ resume_detail_temp_value }}</h4></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">{% trans "Cancel" %}</button> <a class="btn-u btn-u-blue" id="dataConfirmOK">{% trans "Confirm" %}</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').html($(this).attr('data-confirm'));
$('#dataConfirmModal').modal({show:true});
$('#dataConfirmOK').click(function() {
// handle checkbox function here.
});
return false;
});
});
The bootstrap modal should show/hide the list entry and only uncheck the checkbox when the confirm button is selected.
EDIT: ADDED CHECKBOX CODE:
<input type="checkbox"
style="width:1.5em; height:1.5em;"
name="selected_items"
value="{{ id }}"
{% if selected %}checked="checked"{% endif %}
onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});"/>
Data attributes may help you pass the data you need in the function in a seamless manner and also help you avoid maintenance unfriendly inline JavaScript. Set up three event listeners as follows:
function checkboxUpdated(checkbox, count, label, id) {
var checkbox = this,
count = $(checkbox).data('count'),
label = $(checkbox).data('label'),
id = checkbox.value;
if(checkbox.checked) {
$('#menu_entry_' + id).show();
} else {
if (count > 0) {
$('#confirm_modal').data('element', checkbox).find('div.modal-body p:first')
.html( 'You have ' + count + ' saved ' + label + '. Are you sure you want to delete your ' + count + ' saved ' + label + '?' ).end()
.modal('show');
return;
}
$('#menu_entry_' + id).hide();
}
}
$(function() {
$(':checkbox').on('change', checkboxUpdated).change();
$('.confirm-no').on('click', function() {
var element = $('#confirm_modal').data('element');
element.checked = true;
});
$('.confirm-yes').on('click', function() {
var element = $('#confirm_modal').data('element'),
id = element.value;
$('#menu_entry_' + id).hide();
});
});
DEMO
UPDATE
http://jsfiddle.net/n0ypwceo/3/
**HTML**
<div class="available_resume_details_height">
<input type="checkbox" data-confirm='Are you sure you want to remove? [1] ' value="id1" /> <span style="cursor: pointer;">Checkbox</span>
<br/>
<input type="checkbox" data-confirm='Are you sure you want to remove? [2]' value="id2" /> <span style="cursor: pointer;">Checkbox</span>
</div>
<div id="dataConfirmModal" class="modal modal-confirm-max-width" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"><icon class="icon-remove"></icon></button><h4 class="modal-title" id="dataConfirmLabel">Confirm?</h4></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">"Cancel"</button> <a class="btn-u btn-u-blue" id="dataConfirmOK">"Confirm"</a></div></div>
<div id="menu_entry_id1" style="display:none">menu entry id 1</div>
<div id="menu_entry_id2" style="display:none">menu entry id 2</div>
JQ:
// global vars
//checkbox that is clicked
var $checkboxClicked;
//If the confirm button is clicked
var confirm=false;
$(document).ready(function () {
$('input[data-confirm]').click(function (ev) {
//box that is clicked placed in a variable
$checkboxClicked = $(this);
//get and store confirm text
var dataConfirmTxt=$checkboxClicked.attr('data-confirm')
confirm = false;
//var href = $(this).attr('href');
//append confirm text
$('#dataConfirmModal').find('.modal-body').html(dataConfirmTxt);
//show moadl
$('#dataConfirmModal').modal('show')
//if confirm button selected
$('#dataConfirmOK').click(function () {
// the confirm button is clicked
confirm=true;
// hide modal
$('#dataConfirmModal').modal('hide')
});
return false;
});
//modal event: before hide
$('#dataConfirmModal').on('hidden.bs.modal', function (e) {
//get menu id
var id=$checkboxClicked.val();
//alert(id+'/'+confirm);
if(confirm==true)
{
// check checkbox
$checkboxClicked.prop('checked', true);
// show menu entry
$('#menu_entry_' + id).show();
}
else
{
// uncheck checkbox
$checkboxClicked.prop('checked', false);
// hide menu entry
$('#menu_entry_' + id).hide();
}
})
});
I hope this could help you. You could see my code from here http://jsfiddle.net/p0mpv9e0/3/.
Why your code is not working is because you forget to put attribute 'data-confirm' to input element. It should be:
<input type="checkbox" data-confirm ... />
I'm not sure what do you mean by pas variables but if you want to get data that stored in input element you could get it using variable "this" inside the event callback.
$('input[data-confirm]').click(function() {
var self = this; // it's object that store data from input element
});

How to display the updated data in front end without refreshing page?

I want to save the edited data into DB and also display in frond-end on clicking save button in the form .. i did the first part but i struggling to show this in frond end with out refreshing the page
<div class="leftbar_menu">
<div class="short_res_header">
<h3 style="margin-top: 10px;">
<span style="float:left;">About</span>
<span style="font-size:small;float: right;"><a data-edit-id="40322" data-clickmode="edit" class="pers" data-id="40322" style="display: inline;">edit</a></span><span style="font-size:small;float: right;"><a class="pers" data-close-id="40322" data-clickmode="close" data-id="40322" style="display: none;">close</a></span> </h3>
</div>
<div class="leftbar_content">
<div data-id="40322" style="display: none;" class="about_toggle formarea">
<script type="text/javascript">
window.onLoad = imageRefreshBig();
$(document).ready(function(){
$('#profileshortresume').attr('maxlength','250');
$("#profileshortresume").css({
"max-width": "350px"
});
});
</script>
<div class="ajaxfiy_edit_profile">
<form enctype="multipart/form-data" method="post" action="http://10.0.1.21/firstplanet/dev/action/profile/edit/" onsubmit="return validateForm()" style="margin-left: 10px;" id="profile_edit_form" class="profile_edit_form_40322" name="profile_edit_form" novalidate="novalidate">
<div style="float:left;width:100%;" id="mypage_about" class=""><dl class="profileshortresume"><dt>About you<font style="color:#FF1800;font-size: 11px;padding-left: 3px;"> *</font><br></dt><dd>
<textarea title="" required="" id="profileshortresume" name="profileshortresume" class="input-textarea" maxlength="250" style="max-width: 350px;">good</textarea></dd></dl></div><input type="hidden" value="90d0e928746b45b9886292d1d0e08d5e" name="__elgg_token"><input type="hidden" value="1396426813" name="__elgg_ts"><input type="hidden" value="40322" name="cat_id"><input type="hidden" value="39242" name="custom_profile_type"><input type="hidden" value="job_1394777243" name="username">
<div class="subt_butt">
<a class="buttonS"><span><input type="button" value="Save" class="edit_save_button" style="text-align:center;"></span></a>
</div>
<br>
</form>
</div>
</div>
<div style="padding-right: 6px; display: block;" class="short_res" data-content-id="40322">
good
</div>
</div>
</div>
// Below script will open the form when edit is clicked
<script type="text/javascript">
$('a.pers').click(function(){
var formid = $(this).attr('data-id');
var clickmode = $(this).attr('data-clickmode');
/*Closing All Open Div */
$('div.short_res').show();
$('div.formarea').hide();
if(clickmode == 'edit') {
$('a[data-clickmode=create]').show();
$('a[data-clickmode=edit]').show();
$('a[data-clickmode=close]').hide();
$('a[data-create-id='+formid+']').show();
$('a[data-close-id='+formid+']').show();
$('a[data-edit-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
if(clickmode == 'close') {
$('a[data-create-id='+formid+']').show();
$('a[data-edit-id='+formid+']').show();
$('a[data-close-id='+formid+']').hide();
$('div[data-id='+formid+']').hide();
$('div[data-content-id='+formid+']').show();
}
if(clickmode == 'create') {
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$('a[data-close-id='+formid+']').show();
$('a[data-create-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
});
// am using below script for update the data in db and display in front end
$(".edit_save_button").click(function(){
var formid = $(this).parent().parent().parent().parent().attr("class");
var url = $("form."+formid).attr('action');
var data = $("form."+formid).serialize();
$(".thewire_previous_img").show();
var details = $(this).parent().parent().parent().parent().parent().parent().next().attr("class");
$.ajax({
type: "POST",
url: url,
data: data,
context: details ,
success: function(data){
$(".formarea").hide();
$('div.short_res').show();
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$(".thewire_previous_img").hide();
}
});
});
That's simple if you not want the page to refresh just not use <form> element and button as <input>,
Just get the elements value with JQuery .val() and get click event of a <button type="button"> element.
When you send a form the navigator automatically always will refresh the page or redirect you to the page that is referenced in the form.

Categories