html input fileupload returning null - javascript

I am trying to make a demo involving an html input file uploader and ajax, but I can't even get my script to getElementById.
I keep receiving an TypeError: form is null.
Here is my html and script:
<form id="file-form" action="handler.php" enctype="multipart/form-data" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
<script type="text/javascript">
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
</script>
Note that 'fileSelect' and 'uploadButton' are receiving their elements and are not null.
For some reason form is not able to getElement.
I've seen several similar questions, but it seems like I am doing the right thing. Let me know if you have any suggestions.
Thanks in advance.
EDIT: I should add that this demo is in an ASP .ascx User Control Form. kami-sama's Code Snippet worked perfectly fine, but it will not do the same in my solution.
I log the 'form' variable after getElementById and it returns null and does not proceed past the form.onsubmit = function(event) line.

You should declare that your form will be handling uploaded files by adding the enctype="multipart/form-data"
w3
w3schools

I just added closing bracket to your code and it's working just fine in StackOverflow code snippet and in Firefox with html file.
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
<form id="file-form" action="handler.php" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>

Related

How do I submit data from a text field in HTML to a JavaScript variable?

I cannot figure out how to pass an HTML input to a JS variable.
<form id="form" target="_self">
<input type="text" id="task" placeholder="What's on the agenda?" onsubmit="getForm()">
</form>
My HTML form with the function being called as follows:
function getForm() {
var form = document.getElementById("task").value;
console.log(form);
}
However, when I press enter after typing into the input text, it just refreshes the page and changes the URL from index.html to index.html?task=foo and doesn't log anything in the console.
Try this:
<form id="form" onsubmit="getForm()" target="_self">
<input id="task" placeholder="What's on the agenda?" type="text">
</form>
and
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
…but keep in mind that you need at least a button or an input to submit the form.
There are two issues with the OP's code.
The getForm function will not execute because onsubmit is wired up against the input element instead of the form element. HTMLInputElement doesn't emit submit events.
The default action of a form is to submit the form to the server, so even if the getForm function were correctly wired up it would execute quickly and then the page would refresh. Likely you want to prevent that default action.
Generally speaking, it's good practice to wire up event listeners in your JavaScript code. Here's a snippet that demonstrates working code akin to what the OP is attempting.
'use strict';
const taskFrm = document.getElementById('taskFrm');
const taskTxt = document.getElementById('taskTxt');
taskFrm.addEventListener('submit', e => {
e.preventDefault();
console.log(taskTxt.value);
});
<form id="taskFrm">
<input id="taskTxt" placeholder="What's on the agenda?">
</form>
For the sake of completeness, if you want to wire up the onsubmit function in the HTML, here's how:
function getForm(e) {
var form = document.getElementById("task").value;
console.log(form);
e.preventDefault(); // Or return false.
}
<form id="form" target="_self" onsubmit="getForm(event)">
<input type="text" id="task" placeholder="What's on the agenda?">
</form>

adding an input value and submitting the form on load

I have the following form:
<form action="http://example.co.uk/order" method="post" id="voucher" class="AVAST_PAM_nonloginform">
<fieldset>
<h4>Vouchers</h4>
<input type="text" class="discount_name form-control" id="discount_name" name="discount_name" value="">
<input type="hidden" name="submitDiscount">
<button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</fieldset>
</form>
and am using the following script:
<script>
window.onload = function(){
document.getElementById(\"discount_name\").value = \"50681\";
}
</script>
to populate the input. I then use:
<script>
window.onload = function(){
document.forms['voucher'].submit();
}
</script>
to activate the submit.
However, use the second script, it stops the "50681" from being inputted into the text box (instead submits a blank input).
Originally I had the code as :
<script>
window.onload = function(){
document.getElementById(\"discount_name\").value = \"50681\";
document.forms['voucher'].submit();
}
</script>
(I split it up thinking it may be a timing issue).
Any ideas?
p.s. the reason for the backslash's is due to it currently being run under php until I can get it working
The issue seems to be with (\"discount_name\").value = \"50681\"; & document.forms['voucher'].submit();
In either of the case you can avoid \ & for form you need to target by the index number. Assuming there is only one form present , so passing 0 in index
window.onload = function(){
document.getElementById("discount_name").value = "50681";
document.forms[0].submit();
}
Note: In the demo I have changed the action url to https else it will prohibit to make call from jsfiddle. In your case you can still keep http in code
DEMO USING ID

Why the change in input type=file is not identified with `form.serialzie()`

I am checking whether the values in form has been changed before submitting for updation. All other controls inside form, if changed, are identified but
not input type=file control. Below is the sample I was trying and if you try submitting form with or without uploading file, the response is its not changed. Why this behavior with only input type=file? Why the change in input type=file is not identified?
var form_serialize = "";
$(function() {
form_serialize = $("#frmProfile").serialize();
})
$('.submit').on('click', function(e) {
e.preventDefault();
var isChanged = $("#frmProfile").serialize() == form_serialize ? false : true;
if (isChanged)
$('body').append('changed');
else
$('body').append('Not changed');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmProfile">
<input type="file" />
<input type="submit" class="submit" value="Submit" />
</form>
As per the documentation of serialize()
Data from file select elements is not serialized.
Instead you can use jQuery ajaxForm plugin which support.
Or you can use FormData object , Refer these questions : Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP? , Sending multipart/formdata with jQuery.ajax

pass JavaScript variable to HTML input box and (to use in PHP file)

I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->

Pass js variable to form action url

I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.

Categories