adding events to dynamically created elements using JS or Jquery - javascript

I am creating a div block dynamically. In the div, i am having text fields and one file field and one hyperlink. on clicking the hyperlink, the div tag will be removed from its parent. coming to the file field, i want to add onchange event to the file, which is not working for me. Please check my code and correct me if i am wrong?
this is my code:
<div id="incdiv" class="incdiv" name="incdiv">
<div id="increpeatdiv">
<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>
</div>
add one more Incident
</div>
<script>
function repeat(){
var p=document.getElementById('incdiv')
var element = document.createElement('div');
element.id='increpeatdiv'+p.children.length;
element.innerHTML='<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>'+
'Delete Incident;';
p.appendChild(element);
}
function delete(a){
var p=document.getElementById(a)
var h=document.getElementById('incdiv');
h.removeChild(p);
}
function filelogValidation(input){
var fileInput = document.getElementById(input);
var filePath = fileInput.value;
var allowedExtensions =
/(\.txt)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('Invalid file type. Please Upload .txt format');
fileInput.value = '';
return false;
}
else return true;}
}
I am guessing the problem to be of id "ifile". But I dont know how to solve it. Can somebody help me?

Check this
<div id="incdiv" class="incdiv" name="incdiv">
<div id="increpeatdiv">
<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>
</div>
add one more Incident
</div>
<script>
var i = 1; //index for doing identity to ifiles like ifile_1, ifile_2 ...
function repeat(){
var p=document.getElementById('incdiv')
var element = document.createElement('div');
element.id='increpeatdiv_'+i;
element.innerHTML="<input type=\"file\" class=\"\" id=\"ifile_"+i+"\" name=\"ifile\" onchange=\"return filelogValidation(this.id)\"/>"+
"Delete Incident;";
p.appendChild(element);
i++;
}
function delete_(a){
var p=document.getElementById(a)
var h=document.getElementById('incdiv');
h.removeChild(p);
}
function filelogValidation(input){
var fileInput = document.getElementById(input);
var filePath = fileInput.value;
var allowedExtensions = /(\.txt)$/i;
if (!filePath.match(allowedExtensions)) {
alert('Invalid file type. Please Upload .txt format');
fileInput.value = '';
return false;
}
else return true;
}
</script>

Related

How can I change the label name when file is selected?

HTML is given below-
<input type="file" class="custom-file-input" accept="image/*" onchange="loadFile(event)" id="customFile">
<label class="custom-file-label" id="change" for="customFile">Choose File</label><br><br>
<img width="150px" id="output" src="#"/>
Script is given below-
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
My code is able to show the image selected but I also Want to Change The Label text to selected image name
The logic to change the label text can be written on the change event. Check the following event snippet,
document.getElementById('customFile').onchange = function() {
// code to change the label text
var fullName = getFileName(document.getElementById('customFile').value);
document.getElementById("change").innerHTML= fullName;
};
var getFileName = function(fullPath) {
if (!fullPath) return null;
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
return filename.substring(1);
}
return null;
}
For more input on getting the file name check https://stackoverflow.com/a/857662/17542117
Var name = document.getElementById("customFile").value;
Use
document.getElementById("Change").innerHTML = name
Please correct the spelling.

Unable to get an event interrupter for preventing form submission to work corrctly in a basic JavaScript and PHP tutorial

I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:
<div>
<form id="frmSupport" name="frmSupport" method="post" action="support_process.php">
<fieldset id="fastSupport">
<legend><strong>Fast Support</strong></legend>
<p>If you've already booked the Singing Rails Girls coach,</br> and have not gotten a confirmation number,</br> drop us a line and we'll respond within 24 hours.</p> </p>
<p>
<label for="email">Email:</label>
<input type="text" value="your email" name="name" id="email" tabindex="10" />
<p>
<span id="errorMsg"></span>
</p>
<input type="submit" value="Submit">
</p>
<p><b>Ed's "Blah Blah Blah" Tour Status</b></p>
<label for="tourStatus" class="inline">
<input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here
</label>
<label for="tourConf" class="inline" >
<input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date
</label>
</br>
</fieldset>
</form>
</div>
Comments Section
Comments:
<script src="myscript.js">
</script>
And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
//prevent a form from sumbitting if no email.
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>
<h1>Thank you, we will contact you shortly!</h1>
<a href="index.html" target="_blank" >Back</a>
<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_GET); */
error_log(message);
?>
Here's a problem:
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
document.getElementById(errorMsg).innerHTML = "OOPS!";
In the second, you're accessing the element by its id properly:
document.getElementById("errorMsg").innerHTML = "";
You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.

In an AMT HTML Questio. for batch, how to generate all inputs

So I've been trying to generate the contents mturk_form using the DOM model for a Amazon Mechanical Turk HTML question. I ran into an interesting error when I generated ALL inputs using the script: I get the error Dhtml template must contain a question.
This error can be hacked around by putting an unnamed hidden input in the top of the page, like the example below. Remove the <input type="hidden" /> and the error comes back. Does anyone have a better way?
<p><input type="hidden" /> <script>
window.onload = create_form;
function validate()
{
var checkbox = document.getElementById("testbox");
if (checkbox.checked)
{
return true;
}
else
{
alert("failed validation");
return false;
}
}
function create_form()
{
var turkform = document.forms[0];
var testbox = document.createElement('input');
testbox.type="checkbox";
testbox.name="testbox";
testbox.id="testbox";
testbox.innerHTML="check to be valid";
turkform.appendChild(testbox);
turkform.appendChild(document.createTextNode('check to be valid'));
var submitbutton = document.getElementById("submitButton");
submitbutton .onclick=validate;
turkform.appendChild(submitbutton);
}
</script></p>

How to determining if a file has been selected in JavaScript?

I'm using JavaScript to validate an uploading form, one of the conditions is to check if any file has been selected. I thought this would be simple, but I can't get it to work. Is this code invalid? The var file works with other conditions so it's not that
var file = document.getElementById('file');
if(file.value =="") {
alert("no file selected")
return false;
}
<input name="uploaded" type="file" id="file" />
You can use the following example:
var fileInput = document.getElementById('file');
fileInput.onchange = function () {
var input = this.files[0];
if (input) {
//process input.
} else {
alert("Please select a file.");
}
};
Hope this helps.

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

Categories

Resources