HTML + JS: Clear File Input on button click - javascript

I want to tell my backend, I deleted the assigned file it already loaded:
<input id="pic" name="pic" type="file" onclick="this.value=null;" onchange="uploadFile(this);">
<button id="pic-delete" type="button" onclick="removeFile(this);"><i someicon></i></button>
where the onclick function looks like:
removeFile = function() {
var ipt = document.getElementById("pic");
ipt.value = null; // <--- problem here
console.log("worked...")
}
my problem now is: I can differentiate the request in the browser Network tab whether I do nothing or hit the delete button. Both times the input field does not show up.
I wanted to add ipt.value="DELETE" so I can catch that in the backend, but this leads to an error:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
From what I can tell the error always occurs if I put anything else but ipt.value = null or ipt.value = "" in this line.
A fiddle with the full code to show the error: https://jsfiddle.net/rvc8sbjy/3/

There are a few errors. The way you were trying to extract the ID is wrong. A much easier approach is to just use .replace
var inputFieldID = v.id.replace("-delete", "");
Second - you can't set the value to an non-empty string. To reset it just set it to an empty one:
ipt.value = "";
Working example:
https://jsfiddle.net/5yqohjzv/

Related

JS/PHP Issue passing clipboard data between window.open and form

I inherited this project and am trying to correct a few bugs. This particular issue deals with the user double clicking a box in a form(built in conveyor_maint.php), then picking a value in a window that pops up (getPartNumber.php) and then having that value pass back down the form. It successfully pushes the value into the clipboard, but I cannot figure out how to get the value to go back to the form. I would like it to update the form each time the user picks a value in the popup window, but could have it only update upon closure of the popup window too.
Here are the details:
The table is in conveyor_maint.php
<th> Override Head Tail </th>
<td><input type="text" name="cd_headtail_ovrd" value="$cd_headtail_ovrd" size="20"
ondblclick="getPartNumber('cd_headtail_ovrd','desc_htail_ovrd','TAIL');"
title="DOUBLE CLICK to display a list of tails you may select from. This will override the calculated head tail when choosing BOM data. YOu may leave this field blank.">
<input type="display" name="desc_htail_ovrd"
value="$desc_htail_ovrd" size="30" readonly></td></tr>
When the block is double clicked, it runs the javascript function getpartNumber, from the included file javascript.php
<script language="javascript">
function getPartNumber(field1, field2, filter) {
var user = '$user_login'
var url = 'getPartNumber.php?user_login=' + user + '&filter=' + filter + '&field1=' + field1 + '&field2=' + field2
window.open(url,'Get_Part_Number','height=700,width=900,scrollbars=yes')
getClipboardContents(field1, field2);
}
async function getClipboardContents(field1, field2) {
try {
const text = await navigator.clipboard.readText();
console.log('Pasted content: ', text);
var partarray = text.split("!")
var partno = partarray[0]
var partdesc = partarray[1]
if (text != "") {
window.document.forms[0].elements[field1].value = partno
window.document.forms[0].elements[field2].value = partdesc
}
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
}
}
</script>
The javascript launches the window.open command to open the pop-up GetPartNumber.php
GetPartNumber.php builds a table which the user selects the value to be pushed back to the original form.
It relies on a state_change to push the value into the clipboard:
function state_Change() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
myhtml = xmlhttp.responseText;
var dataarray = myhtml.split("~");
var retdata = dataarray[1];
navigator.clipboard.writeText(retdata);
} else {
alert("Problem retrieving XML data:" + xmlhttp.statusText)
}
}
}
This works, as I click the different choices in the popup, they can be pasted into a text file correctly.
Now, this used to work with the following code, but upgrades to the server and related software broke it.
Each time a choice is made in the pop-up, it runs SelectPart()
function SelectPart(partno, user_login) {
window.document.curform.partno.value = partno;
var url = 'getPartData.php?partno=' + partno + '&user_login=' + user_login;
loadXMLDoc(url)
}
Subsequently, getPartData.php runs and echoes the same data I pushed to the clipboard.
I am trying to get rid of the selectPart() and the subsequent code, unless it turns out to be easier to fix.
The fundamental issue I have is that when the javascript.php runs, it opens the window for the selection and the javascript then completes, reading the clipboard and pushing it to the form (while the popups is still open and the user is making their choice). Subsequent selections, change the clipboard, but they don’t get read until I rerun the popup. I need a way to run the async function which reads the clipboard, either with each selection in the popup, or upon closure of the popup window.
I have tried a variety of things including moving the code to other places, global variables (yuck), and other methods to solve it, so I am hoping for a solution to the original problem.
After a bit of digging, I got rid of the clipboard copy and paste entirely.
Using some standard Javascript between a parent and a child window, I updated the code in the child to reference the parent table directly and dynamically pulling the field names and content from an array:
opener.document.curform[results[2]].value = results[0]
opener.document.curform[results[3]].value = results[1]
for some more information, check out this link: https://www.plus2net.com/javascript_tutorial/window-child3.php

Adobe Javascript Signature Lock

I am trying to use Adobe Javascript to change the properties of a fillable form text box when a signature is added to a signature block.
A PDF file is created by exporting from Excel into PDF.
An Action is then used to Detect Form Fields which produces 2 text boxes and 2 signature blocks automatically.
The Action then runs this:
var f =this.getField("Signature").required = true ;
to make the first signature block a required form.
Everything is successful up to this point.
The action then attempts to run this:
var f =this.getField("Signature");
var oLock = f.getLock();
oLock.action = "include";
oLock.fields = new Array("Receivers CommentsRow1");
f.setLock(oLock);
Which throws up the error
TypeError: oLock is null
4:Batch:Exec
Running directly from the console gives the same error.
Any help is appreciated, thanks.
According to the documentation http://help.adobe.com/en_US/acrobat/acrobat_dc_sdk/2015/HTMLHelp/Acro12_MasterBook/JS_API_AcroJS/Field_methods.htm?rhtocid=_6_1_8_31_2_12#TOC_getLockbc-13
oLock.action = "include";
"include" should be initial caps "Include".

execute onChange when a certain condition/event is detected jQuery

alright.. i have an input box that captures paste event and checks if the pasted text/string is a youtube url. if yes, it will forward data to some PHP to process..
the result json data is being displayed here $('.printdata').append(response);
concerns:
what i didn't have in my code, is to recognize if the whole text or
the youtube link is removed/cut/deleted. it should also remove the
displayed data.
accept the first youtube URL, if multiple youtube URL is found, send the first link to PHP, then ignore the others, just display it as text.
my workaround
what im thinking (tho not sure) is to put some onchange() event
somewhere to recognize $("$input") element is being changed.
accept only a single paste event and ignore if paste() is repeated. -not sure if this is the right approach.
http://jsfiddle.net/8Pvr4/4/
to test what im trying to explain, input any youtube url in the textfield, and it should display something.
then remove the url, the data remains. OR add another URL consecutively. the resulting data will stack.
$(document).ready(function() {
//some regex
$("#input").bind('paste', function(e) {
var val = undefined;
//get pasted data
if(window.clipboardData && window.clipboardData.getData) {
val = window.clipboardData.getData('Text');
} else if (e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData){
val = e.originalEvent.clipboardData.getData('text/plain');
}
//check for youtube URL
if (youtube.test(val)) {
var yurl = val.match(youtube)[0];
$.post("youtubejson.php?url="+ yurl, {
}, function(response){
$('.printdata').append(response);
});
}
});
I'm not sure i understand your question properly, but i guess your result is stacking and not getting replaced, you can use .html(response) instead of .append(response) to stop stacking.

getElementsByTagName returns null value (but works weirdly fine in debugging mode)

This code is taking in an xml file and parse it and output as a table. Here's a piece of code(Firefox oriented):
function viewXML(inputForm) {
var URL=inputForm.URL.value; //input XML URL
// create document and load URL
var xmlDoc = document.implementation.createDocument("","doc",null);
xmlDoc.load(URL);
xmlDoc.onload = generateHTML(xmlDoc);
hWin = window.open("","sth", "height=800,width=600");
hWin.document.write(html_text);
hWin.document.close();
}
viewXML is an onClick function of a button. Now a piece of code in generateHTML():
function generateHTML(xmlDoc) {
...
caption=xmlDoc.getElementsByTagName("title").item(0).firstChild.nodeValue; //<1>
html_text += "<caption align='left'><h1>" + caption + "</h1></caption>";
...
}
A piece of XML file:
<catalog>
<title>Airbus_Aircraft_Families</title>
<aircraft>
<Airbus>A380</Airbus>
<Aircraft>A380</Aircraft>
<seats>555</seats>
<Range>15000km</Range>
<Wingspan>78.8m</Wingspan>
<Height>24.1m</Height>
</aircraft>
</catalog>
Problem:
This code works fine when I was running it in debug mode step-by-step-ly in Firebug. BUT if there's no breakpoints set up, when the program hits line <1>, there will show an error saying that:
xmlDoc.getElementsByTagName("title").item(0) is null , which is apparently not true.
And interestingly, when I tried adding a line
alert(xmlDoc.getElementsByTagName("title").length)
before the <1> line, it will pop up a window shows 0, but after I click "OK", the CORRECT title(from XML) will show up in the new window! As that in step-by-step mode.
Things I tried:
1, changing xmlDoc.getElementsByTagName("title").item(0) to xmlDoc.getElementsByTagName("title")[0]
Didn't work, debugger told me "xmlDoc.getElementsByTagName("title")[0] is undefined"
2, Removed all the whitespaces within or between tags in XML file, didn't help.
The issue is probably due to your document being loaded asynchronously. You can check document.async property here. I think if you set this property to false, your code will work.
// create document and load URL
var xmlDoc = document.implementation.createDocument("","doc",null);
xmlDoc.async = false;
xmlDoc.onload = generateHTML(xmlDoc);
xmlDoc.load(URL);
Note that I moved the line attaching an event handler to load event before the call to load function.

bad request when trying to print a page using javascript

I am trying to print a page using javascript, and i am getting a "Bad Request" when a new window popsup if i clicked the 'print' button.
Here is my javascript code that opens a window by capturing the current location and assigning the media css to print.
function printerFriendlyNew() {
genPopUp = window.open("","printer","toolbar=no,location=no,scrollbars=yes,directories=no,status=yes,menubar=yes,resizable=yes,width=760,height=600");
genPopUp.location.href = document.location.href + "&css=print";
if (genPopUp.opener == null) genPopUp.opener = window;
genPopUp.opener.name = "opener";
}
Any idea why i get the 'bad request' error ?
Got this resolved... crazy me, am just blindly appending "&css=print" since I have URLs which have querystring, and it works fine for those, and bugs out for those which don't. I added this to my existing javascript and this resolved the issue.
var contain = document.location.href;
if (contain.indexOf('?') == -1)
genPopUp.location.href = contain + "?css=print";
else
genPopUp.location.href = contain + "&css=print";

Categories