Making javascript work after dynamically adding html - javascript

I have a file upload button with auto upload enabled as follows:
<form id="fileupload" action="home/uploadprofilepic" method="POST" enctype="multipart/form-data">
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="files">
</span>
</form>
$(document).ready(function()
{
$("input[name=files]").change(function() {
$(this).closest("form").submit();
});
});
However, I want to dynamically insert this as html. I need to add the autoupload javascript too. This is what I have so far :
$('#uploadPicId').popover({
title : 'Edit Profile Picture', //this is the top title bar of the popover. add some basic css
html: 'true', //needed to show html of course
content : '<form id="fileupload" action="home/uploadprofilepicmeta" method="POST" enctype="multipart/form-data">'+
'<span class="btn btn-success fileinput-button">'+
' <i class="icon-plus icon-white"></i>'+
' <span>Add files...</span>'+
' <input type="file" name="files">'+
'</span>'+
'</form>'
});
I need to add javascript to make the autoupload work. Is there any way to do this? I am pretty lost.
Thanks.

Change your above js to be like this instead:
$(document).ready(function()
{
$("body").on("change", "input[name=files]", function() {
$(this).closest("form").submit();
});
});
The key difference is your setting up the event listener on the entire body and if the event was launched from the given input, fire your function no matter if the html was added dynamically or not.

Related

How to stop next page to be loading

In my project, while a particular button is clicked I want to stop the next page appearing. Here is my JavaScript code:
function checkcond() {
check_value=document.getElementById("chkvalue");
if(check_value==null){
alert(check_value);
document.firstform.textview.focus();
return false;
}
}
and button code is:
<form id="payment_form" name="payment_form" action="<?php echo site_url("cont/accept");?>" method="post">
<input id="chkvalue" name="chkvalue" type="hidden">
<button type="submit" id="submit_button" class="btn btn-primary" onclick="checkcond()">
<b>Make a Payment</b>
<span class="fa fa-hand-o-right" aria-hidden="true"></span>
</button>
Here after checking the check_value I want to keep my current page while it is null. How should it be done? Is there any function for that?
My suggestion would be to remove inline javascript
and use like this
document.getElementById('payment_form').onsubmit = function() {
return checkcond();
};
or if you want to use inline method, change onclick method like this
<button type="submit" id="submit_button" class="btn btn-primary" onclick="return checkcond()"><b>Make a Payment</b>

Raising an Ajax event after knockout rendering is done? (explained with screenshots)

<div data-bind="style: { display: isShortlisted() === false ? 'inline-block' : 'none'}">
<form id="shortlistForm" action="#MVC.GetLocalUrl(MVC.HireOrgJobApplication.AjaxShortlist(Model.Application))" method="post" style="display:inline;">
#Html.AntiForgeryToken()
<input type="hidden" name="ApplicationKey" value="#Model.Application.ApplicationKey" />
<button type="submit" class="btn-act jui-tooltip" title="Shortlist">
<i class="fa fa-2x fa-star"></i>
</button>
</form>
</div>
<div data-bind="style: { display: isShortlisted() === true ? 'inline-block' : 'none'}">
<form id="unshortlistForm" action="#MVC.GetLocalUrl(MVC.HireOrgJobApplication.AjaxUnshortlist(Model.Application))" method="post" style="display: inline;">
#Html.AntiForgeryToken()
<input type="hidden" name="ApplicationKey" value="#Model.Application.ApplicationKey" />
<button type="submit" class="btn-act-active jui-tooltip" title="Remove from shortlist">
<i class="fa fa-2x fa-star" style="color:#f3b700;"></i>
</button>
</form>
</div>
$('form#shortlistForm').ajaxForm(function () {
viewModel.isShortlisted = true;
});
$('form#unshortlistForm').ajaxForm(function () {
viewModel.isShortlisted = false;
});
I have a code for a button that "shortlists" an applicant.
To briefly explain, my intention is to turn the "shortlistForm" button to
"unshortlistForm (which means it's already shortlisted)" button when it's clicked.
Please look at the attached screenshot:
So the start which looks like this
should turn like below when it's clicked.
when I check my network status on google chrome, it successfully "posts" to the correct link.
But the problem is, I have to REFRESH it to see the changed star.
Right now when I click the button, it gives me
just a page with 'true' written.
I want it to happen immediately without giving me that page, or having me refresh the page to see the change.
I am assuming this is happening because I cannot render Ajax-forms before knockout rendering is done. How can I make the ajax to form after the knockout is generated?
Please help !!

Bootstrap File Upload clone

I am using Krajee's Bootstrap file upload plugin for file input & I am trying to clone the file input so that users can add multiple files from different folders rather than selecting it at once. The issue I am facing is after the file input gets cloned, it behaves weirdly. I have setup a fiddle for this.
When I am trying to reset or clear the file input, it always clears the first input. Have been trying a lot of options & after spending so many hours decided to post here.
JS Fiddle: https://jsfiddle.net/asfg9mna/
Any ideas as to how to make it work fine? Issue is whenever i click on delete icon, it always deletes the first input's file & not the current one.
HTML code:
<form role="form" id="upload-form" class="form-horizontal">
<div class="addFiles text-nowrap">
<div class="appendClass form-group" style="margin-bottom: 1.5%;">
<label class="col-md-2 control-label" for="input-2">Select Files</label>
<div class="col-md-9 col-9-input uploadFile">
<input placeholder="Select Files" id="input-2" name="input2[]" type="file" class="file input-upload" data-show-upload="false" data-show-preview="false">
</div>
<button type="button" class="btn btn-box-tool addFilesBtn" data-toggle="tooltip" title="Click to add more files">
<i class="fa fa-plus"> </i>
</button>
<button type="button" class="btn btn-box-tool closeFilesBtn" data-toggle="tooltip" title="Click to remove this block">
<i class="fa fa-times"> </i>
</button>
</div>
</div>
</form>
JS Code:
//Clone Upload File Div
$(document).on('click', ".addFilesBtn", function(e) {
e.preventDefault();
$(this).tooltip('hide');
$(".appendClass:first").clone(true).appendTo(".addFiles");
$('.closeFilesBtn').show();
$('.closeFilesBtn:first').hide();
//$fileInput = $('.input-upload');
//$fileInput.replaceWith( $fileInput = $fileInput.clone( true ) );
//$('.input-upload').fileinput('clear').fileinput();
$('.uploadFile').next().trigger('reset');
});
Here is jsfiddle
Update your js code like this,
$(document).on('click', ".addFilesBtn", function(e) {
e.preventDefault();
$(this).tooltip('hide');
parent_element = $(".appendClass:first");
$(".input-upload").fileinput('destroy');
element = parent_element.clone();
element.appendTo(".addFiles");
$(".input-upload").fileinput();
$('.closeFilesBtn').show();
$('.closeFilesBtn:first').hide();
//$fileInput = $('.input-upload');
//$fileInput.replaceWith( $fileInput = $fileInput.clone( true ) );
//$('.input-upload').fileinput('clear').fileinput();
//$('.uploadFile').next().trigger('reset');
});
And please write your code to update ids of every elements which will be cloned.
EDIT
$(document).on('click', ".addFilesBtn", function(e) {
e.preventDefault();
$(this).tooltip('hide');
$(".has_clone").each(function() {
$this = $(this);
var parent_element = $(this).closest(".appendClass");
var $element = parent_element.clone();
$element.find(".file-input").remove();
var counter = parseInt($("#counter").val()) + 1;
$element.find(".col-md-9").append('<input placeholder="Select Files" id="input-' + counter + '" name="input2[]" type="file" class="file dynamic_clone input-upload " data-show-upload="false" data-show-preview="false">');
$("#counter").val(counter);
$element.appendTo(".addFiles");
$(".input-upload").fileinput({
'showPreview': true
});
});
$('.closeFilesBtn').show();
$('.closeFilesBtn:first').hide();
});
//Close addFile div - Upload files
$(document).on('click', ".closeFilesBtn", function(e) {
e.preventDefault();
$(this).closest(".appendClass").hide();
});
Thanks

File upload change function submit form?

i was trying to post files with jQuery, but didnt come anywhere, so i was thinking if i post the form instead, when you select your files, it would have been almost the same. But i got a problem right now, he aint posting the form and i cant figure out what im doing wrong :S
JS:
$(".filesUpload").on("change", function() {
$("#fileupload").submit();
});
HTML:
<li class="uploadBg">
<form method="post" action="index.php" id="fileupload" enctype="multipart/form-data">
<input type="file" name="filesUpload[]" class="filesUpload" multiple="">
<a href="#" class="btn btn-xs btn-default">
<span class="fa fa-upload"></span> Ladda upp
</a>
</form>
</li>
CSS:
.uploadBg { position:Relative;}
.uploadBg input { width: 94px;height: 24px;position:absolute;top: 10px;z-index:1;opacity: 0;cursor:pointer }
Hope any of you guys can tell me what i'm doing wrong

Do i need to load javascript again

I m adding a row in a table via jquery. Every row has some javascript associated with it.
When i add a new row using jquery, the javasccript works on previous rows, but not on newly added row.
Do i need to load the same js again ?? if yes, how?
js works on already html row, but not on row i added
<table>
<tr id="hello12">
<div class="formField" style="float:right" >
<span class="btn btn-success fileinput-button" >
<i class="glyphicon glyphicon-plus"></i>
<span>Add Attachments...</span>
<input id="fileupload" type="file" name="attachment" multiple>
</span>
</div>
</tr>
</tr>
<tr class="row">
<td>
<button type="button" id="override_button">
<b>+</b>
</button>
</td>
</tr>
</table>
$('#fileupload').fileupload({
url: '/attachments/create',
dataType: 'json',
done: function (e, data) {
alert("done");
},
});
$('#override_button').click(function(){
alert("hello")
$('#hello12').after('\ <tr id="hello12">
<div class="formField" style="float:right" >
<span class="btn btn-success fileinput-button" >
<i class="glyphicon glyphicon-plus"></i>
<span>Add Attachments...</span>
<input id="fileupload" type="file" name="attachment" multiple>
</span>
</div>
</tr>')
});
You can use on jquery function :
$("table").on("click", "#override_button", function(event){
alert("done");
});
or if you use jquery prior to 1.7 check live function
example: http://jsfiddle.net/rad_101/99q5jwrx/1/
Case 1: You are hard-bound to reload the script(which I donot feel is a necessity at all). You can save the script in an external file, and append it to the head of your html page.
<script language="text/javascript">
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'source_file.js';
head.appendChild(script);
}
// call the function, so as to run the scripts again on the page
load_js();
</script>
Case 2: (More efficiently) Use (as Dimitris Nastos pointed out)
$(document).on("click", "table .row", function(){
//write your "ASSOCIATED JS" code here.
});
This binds a click event to the document and all child elements within it. It then matches the element identifier provided as the second argument. Works on dynamic elements too.
Case 3: (Little more efficiently) In your case, table is a static element, and would the parent element of the new row. Hence, instead of traversing the whole DOM while writing $(document).on("click","element",function(){}), use
$(table).on("click", "table .row", function(){
//write your "ASSOCIATED JS" code here.
});
So Finally after lot of struggle i got the answer,
Fileupload binds the action to the html once it is loaded, so if you add a new html to the page ,
for each element you have to bind the fileupload again.( you can also use live action to add events to button, in that case you do not need to bind again)
var dofileupload = function(){
$('#fileupload').fileupload({
url: '/attachments/create',
dataType: 'json',
done: function (e, data) {
alert("done");
},
});
}
$('#override_button').click(function(){
alert("hello")
$('#hello12').after('\ <tr id="hello12">
<div class="formField" style="float:right" >
<span class="btn btn-success fileinput-button" >
<i class="glyphicon glyphicon-plus"></i>
<span>Add Attachments...</span>
<input id="fileupload" type="file" name="attachment" multiple>
</span>
</div>
</tr>')
}).each(function () {
dofileupload
}
This solves my problem

Categories