Detecting open button in an upload dialog - javascript

Is there a way to detect if the open button in an upload dialog is clicked using javascript or query?
UPDATE :
I will show you my sample code:
<input type = "file" name = "imgUpload" id = "trngImgUpload" style = "display : none;" multiple>
<button class="btnTools" onclick = "trngOpenVidUploadDialog()" ><img src ="#Url.Content("~/Images/video_icon.jpg")" class ="img3"/></button>
<script>
function trngOpenVidUploadDialog() {
//$('#modalMatchingTypePairType').modal('hide');
//console.log(123);
$('#trngImgUpload').trigger("click");
};
$('input[type=file]').change(function () {
if (this.files) {
alert('changed');
var path = sendVidFile($('#trngImgUpload')[0].files[0], 1);
$('#page' + currId).append('<div class = "vidDR" id = "tTool' + (toolIdCounter) + '"><div class = "del"></div><embed autostart="false" class = "vid" src="' + path + '"></embed></div>');
$('.vidDR').resizable({
containment: '#page' + currId
}).draggable({
containment: '#page' + currId
});
$(".vidDR").click(function () {
alert(1);
});
$('#trngImgUpload').val("");
$('#tTool' + toolIdCounter).contextmenu(function () {
$(this).remove();
});
toolIdCounter++;
}
});
</script>
I already tried using change event but nothing happens. I don't know whats wrong in my code.

You cannot capture the action on the 'Open' button, however you can capture the action upon changes on the file input. E.g. when the user has selected a new file using the file input.
Example as follows:
// input on change event listener
$('#file-upload').on('change', function() {
alert('File Attached: ' + $('#file-upload').val());
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- file upload input -->
<input type="file" id="file-upload">
Hope this helps.

No! That is not possible.
But if you want to have an eye on your input type=file then you might like to use change() event on the input.
Check the snippet:
$('input[type=file]').change(function() {
if (this.files) {
$('pre').html('Files selected. (open clicked.)');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="imgUpload" id="trngImgUpload" style="display : none;" multiple>
<button class="btnTools" onclick="trngOpenVidUploadDialog()">
<img src="https://cdn3.iconfinder.com/data/icons/ilb/Perspective%20Button%20-%20Windows.png" class="img3" />
</button>
<script>
function trngOpenVidUploadDialog() {
//$('#modalMatchingTypePairType').modal('hide');
//console.log(123);
$('#trngImgUpload').trigger("click");
};
$('input[type=file]').change(function() {
if (this.files) {
alert('changed');
}
});
</script>

Related

Neither .preventDefault() or .stopPropagation() will stop my page from reloading when I click my submit button

I've got a search box and a search button. I can hit the search button and the results pop up, no problem, works fine. I wanted to add the ability to search by pressing enter as well, so I added in some code to listen for the keypress and click my button when the keypress is released. This, however, results in the form being submitted and reloads the page with no data. I tried adding in preventDefault() and stopPropagation() to the event listener, but no matter what, the form gets submitted when I hit enter. It shows the correct information for a split second, but then immediately reloads the page.
Here's the HTML:
<script defer src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" integrity="sha384-slN8GvtUJGnv6ca26v8EzVaR9DC58QEwsIk9q1QXdCU8Yu8ck/tL/5szYlBbqmS+" crossorigin="anonymous"></script>
<div class="container-fluid">
<div class="row search-box" id="firstRow">
<div class='col-10 search-head-two'>
<form class="form">
<input type="text" class="search-input" id="term">
</form>
</div>
<div class='col-2 search-head-one'>
<button id="search"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
Here's the Javascript:
var content = [];
document.getElementById("term")
.addEventListener("keyup", function(event) {
event.stopPropagation();
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("search").click();
}
});
document.getElementById("search").onclick = function() {getData()};
function getData() {
var domain = "https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=" + encodeURI(document.getElementById('term').value) + "&limit=10";
fetch(domain).then(function(resp) {
return resp.json()
}).then(function(data) {
for (var i = 1; i < data.length; i++) {
content.push(data[i]);
}
var content1 = content[0];
var content2 = content[1];
var content3 = content[2];
for (var x = 0; x < content[0].length; x++) {
addRow(content1, content2, content3, x);
}
console.log(content[0]);
console.log(content[1]);
console.log(content[2]);
});
}
function addRow(content1, content2, content3, x) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<div class="col-3" id="title">\
<p>' + content1[x] + '</p>\
</div>\
<div class="col-9" id="content">\
<p>' + content2[x] + '</br></br><a target="_blank" href="' + content3[x] + '">' + content3[x] + '</a></p>\
</div>';
document.getElementById('firstRow').appendChild(div);
}
Also important to note is that I'm using Bootstrap 4, Jquery and Jquery UI as external scripts. I'm running this in CodePen.io.
I moved the event.preventDefault() into the if clause, and changed the eventListener from keyup to keydown since the form was getting submitted on keydown not keyup. Now it works like a charm.
document.getElementById("term")
.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("search").click();
}
});
Check this.
Some usefull MDN infos on preventDefault()
Also, you cant have any return from Ajax requests.

Get text value from a button s created dynamically jquery

So i am dynamically adding buttons to a table based on array values returned from my generateFolderTree function, problem is i can't seem to get the text value of a clicked button or even get any events when i click the created buttons. How can i get the name of a clicked button? Code below....Thanks
Jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$("#selectFolder").click(runMyFunction);
});
function runMyFunction(){
google.script.run
.withSuccessHandler(successCallback)
.withFailureHandler(showError)
.generateFolderTree();
$("#hiddenAttrib").hide();
}
function showError(error) {
console.log(error);
window.alert('An error has occurred, please try again.');
}
function successCallback(returnedArray)
{
console.log("returnedArray" + returnedArray);
var folders = returnedArray;
console.log("folders" + folders);
var i = 0;
//row;
for( i=0; i<folders.length;i++)
{
console.log("i = " + i);
var row = $('<p><tr><button class = "selectedFolder">' + folders[i] + '</button></tr></p>');
$("#source").append(row.html());
}
}
$(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
});
</script>
Show.html
<!-- USe a templated HTML printing scriphlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile("Stylesheet").getContent(); ?>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<div>
<div class = "block" id = "dialog-elements">
<button class = "selectFolder" id = "selectFolder" >Select a Folder</button>
</div>
<!-- This block is going to be hidden until the user selects a folder -->
<div class = "block" id = "hiddenAttrib">
<p><label for = "SelectedFolder"> Selected Folder: </label></p>
<p><label id = "foldername"> Folder Name: </label></p>
<p><label id = "folderid"> Folder ID: </label></p>
</div>
<div class = "folderTable" id = "folderTable">
<p><label class = "showStatus" id = "dialog-status">Selected Folder: </label></p>
<table style = "width:100%" id = "source">
</table>
</div>
</div>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('ShowJavaScript').getContent(); ?>
$('document').on('click', '.selectedFolder', function () {
alert($(this).text())
});
Put this piece of code of yours in $(document).ready
$(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
});
use
$(ELEMENT/CLASS/ID).on('click', function(){});
instead of
$(ELEMENT/CLASS/ID).click
click() function doesnt consider elements added to DOM dynamically before we used to use live() for attaching events for dynamically created element but since live() is depreciated we should use on()
on() acts as live()

prevent double click on button in javascript

<script type="text/javascript">
$(document).ready(function () {
$("#submit").on("click", function () {
$(this).attr('disabled', true);
var taskid = num;
var loadnew = 1;
var guessnum = $("input[name=guessnum]:checked").val();
if (guessnum != 1 && guessnum != 2) {
alert("You could not submit an empty answer");
loadnew = 0;
location.href = "/minions/peerprediction1.php";
}
else if (loadnew == 1) {
finishedTask += 1;
}
var starttime = $("#timestart").val();
var timecost = starttime;
$.ajax({
type: "post",
url: "GameMysql.php",
data: "taskid=" + taskid + "&guessnum=" + guessnum + "&effort=" + effort + "&finishedTask=" + finishedTask + "&time=" + timecost,
success: function (data) {
}
});
});
});
</script>
<form>
<a class="button" id="submit"><span>&#10003</span>Submit report</a>
</form>
I want to make sure the form with same answers do not submit twice, and disable the button, but it does not truly work. For I click it twice the finished task number increased by 2
I already see the answer here Prevent double submission of forms in jQuery
and tried, but still could not make it work
Use the button element, it will provide the functionality you are after. It can be styled to look like an anchor. Less issues trying to get it working as intended across all browsers.
$("#submit").on("click",function(){
$(this).attr('disabled', true);
console.log('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" id="submit"> <span>&#10003</span> Submit report</button>
You should use a button instead of an anchor, anchors dont support the disabled attribute
<button id="submit">Submit Report</button>

Custom upload for a generated form

I have a generated form which I can't add HTML directly to it.
This form has 2 upload boxes which needs to have a custom styling. I have managed to style the upload box, but upon testing the function which I need to be triggerd, doesn't trigger.
To clarify, here is my code and what I tried:
The html (that is autom being generated):
<div class="controls">
<input class="span3" type="file" name="img1" id="img1" />
</div>
This is the jQuery
$(document).on('change', 'input[type=file]', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready(function() {
var fileinput = $('input[type=file]', this);
var file_parent = fileinput.parent(); // get the parent
var fileinputhtml = file_parent.html(); // the HTML of the parent (which is input)
file_parent.replaceWith('<span class="btn btn-file"><span class="btn-class btn-primary">Browse</span>'+fileinputhtml+'<span class="form-control"></span></span>');
// The upload function has been triggerd
fileinput.on('fileselect', function(event, numFiles, label) {
console.log(label); // When the .replaceWith() is active, it doesn't show this log.
var input = $(this).parent().find('.fileupload-filename');
console.log(input.val(label));
if( input.length ) {
input.val( label );
}
});
});
Maybe it has an easy solution but I really can't seem to get this to work.
You help would be highly appericiated

Clone form input and clear value

I'm trying to create an upload form. It's working well so far and i'm trying to sort out a couple of bugs that I dislike.
The line that I seem to be having trouble with is
$(element).find(">:first-child").attr("value", "");
When cloning the form, it clones the div and replaces the value with nothing leaving a blank form, this works well, if I were to delete that line I would get the previous form's value, so it would be nice for a blank form to show.
The issue i'm having is when you delete a form all the forms values delete, What I want is when you delete a form, leave the value alone for the other forms.
Here's a fiddle http://jsfiddle.net/d77pd/1/ or see code below
HTML
<button class="clone">Add an Image</button>
<div id="upload_image_sets">
<div id="clonedInput1" class="clonedInput">
<input type="text" id="upload_image_link_1" class="image" size="36" name="hero_options[upload_image_link_1]" value="' . $hero_options['upload_image_link_1'] . '" />
<input id="show_upload_image_link_button_1" class="button upload_images" type="button" value="Upload Image" />
<button class="remove">Remove</button>
</div>
</div>
JavaScript
function updateClonedInput(index, element) {
$(element).appendTo("#upload_image_sets").attr("id", "clonedInput" + index);
$(element).find(">:first-child").attr("id", "cs_product_menu_img_src_" + index);
$(element).find(">:first-child").attr("name", "hero_options[upload_image_link_" + index + "]");
$(element).find(">:first-child").attr("value", "");
$(element).find(">:first-child").next().attr("id", "cs_product_menu_img_src_" + index + "_button");
displayRemove();
}
function displayRemove() {
if ($('.clonedInput').length === 1) {
$('.remove').hide();
} else {
$('.remove').show();
}
}
displayRemove();
$(document).on("click", ".clone", function (e) {
e.preventDefault();
var cloneIndex = $(".clonedInput").length + 1;
var new_Input = $(this).closest('.clonedInput').length ? $(this).closest('.clonedInput').clone() : $(".clonedInput:last").clone();
updateClonedInput(cloneIndex, new_Input);
});
$(document).on("click", ".remove", function (e) {
e.preventDefault();
$(this).parents(".clonedInput").remove();
$(".clonedInput").each(function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement);
})
});
Clone the form a few times, if you delete any form apart form the 1st one with the content, you'll notice the first form's content deletes, I want this left alone.
First approach:
call $(element).find(">:first-child").attr("value", ""); after calling updateClonedInput(cloneIndex, new_Input); from add function.
Working Demo First approach:
Second Approach:
I have modified some code. pass one more bool argument in function updateClonedInput.which will be set true when added and set false when dom is removed.This will prevent the value getting replaced on remove function:
function updateClonedInput(index, element,param) {
$(element).appendTo("#upload_image_sets").attr("id", "clonedInput" + index);
$(element).find(">:first-child").attr("id", "cs_product_menu_img_src_" + index);
$(element).find(">:first-child").attr("name", "hero_options[upload_image_link_" + index + "]");
if(param)
$(element).find(">:first-child").attr("value", "");
$(element).find(">:first-child").next().attr("id", "cs_product_menu_img_src_" + index + "_button");
displayRemove();
}
function displayRemove() {
if($('.clonedInput').length === 1) {
$('.remove').hide();
} else {
$('.remove').show();
}
}
displayRemove();
$(document).on("click", ".clone", function(e){
e.preventDefault();
var cloneIndex = $(".clonedInput").length + 1;
var new_Input = $(this).closest('.clonedInput').length ? $(this).closest('.clonedInput').clone() : $(".clonedInput:last").clone();
updateClonedInput(cloneIndex, new_Input,true);
});
$(document).on("click", ".remove", function(e){
e.preventDefault();
$(this).parents(".clonedInput").remove();
$(".clonedInput").each( function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement,false);
})
});
Working Demo Second Approach
An alternate solution that creates a blank clone from the first element once, then uses this every time a new row is required. It also uses CSS to hide/show the Remove button based on the fact that you only need Remove buttons on all rows unless it's the only child.
Disclaimer: I have removed the id manipulation as I am unsure if you really need it. I can update if necessary.
Demo
HTML
<button class="clone">Add an Image</button>
<div id="upload_image_sets">
<div class="clonedInput">
<input type="text" class="image" size="36" name="hero_options[upload_image_link_1]" value="an initial value" />
<input class="button upload_images" type="button" value="Upload Image" />
<button class="remove">Remove</button>
</div>
</div>
CSS
.clonedInput .remove {
display:inline-block;
}
.clonedInput:only-child .remove {
display:none;
}
JavaScript
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
var $blankClone = $('.clonedInput').clone();
resetForm($blankClone);
$(document).on('click', '.clone', function(e) {
e.preventDefault();
$blankClone.clone().appendTo('#upload_image_sets');
});
$('#upload_image_sets').on('click', '.remove', function(e) {
e.preventDefault();
$(this).closest('.clonedInput').remove();
});
resetForm() borrowed from Resetting a multi-stage form with jQuery

Categories

Resources