I need to run a function when someone has finished selecting a file using the file input service. By "file input service", I mean:
<input type="file" name = "foo" id="foo">
I have tried to do this in various ways, first by creating a form to do so and using other techniques, but nothing seems to work. There are several ways to detect if the thing has something, like by using:
document.getElementById("foo").files[0]
This only returns a value if you run it, but I cannot constantly compile a while statement to do this.
Pure Javascript
You can use pure javascript like below. This code basically uses document.getElementById() to get the input element, and .addEventListener() and change to do something when the input field is changed.
document.getElementById("foo").addEventListener("change", function() {
console.log("Changed");
});
<input type="file" name="foo" id="foo">
jQuery
Use jQuery .change(). Basically, this code will console.log "Changed" when the input changes (you add a file).
$("#foo").change(function() {
console.log("Changed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="foo" id="foo">
Related
I have a pretty simple query here. I have a view page with an div and a form element. This is how they look.
<div id="candy" value="valueOfCandy" ></div>
<input type="text" value="javascript:document.getElementById('candy').getAttribute('value')"/>
I need to access the value of candy inside input's attribute (it can be any attribute).
I tried the code as I have shown above but that didnt work. I researched on StackOverflow too but couldnt find anything satisfactory. Please help out.
Edit: Thank you everyone. I found the answer to that, which I am gonna mark. Also, deleting this question so that it doesnt confuse someone else.
If I assume you want to do this at page load, do it like this
Note 1, custom attributes should have a data- prefix and use .dataset to access its value.
Note 2, for older browsers like IE10 and below, you need getAttribute (as in 2nd sample below).
Stack snippet 1
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
<script>
document.getElementById('candy2').value =
document.getElementById('candy').dataset.value
</script>
Stack snippet 2
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
<script>
document.getElementById('candy2').value =
document.getElementById('candy').getAttribute('data-value')
</script>
Do it in JavaScript outside of code but after the objects exist.
Here's an example of how to achieve this:
var candy = document.getElementById('candy').getAttribute('data-value');
document.getElementById('input').value = candy;
<div id="candy" data-value="valueOfCandy" ></div>
<input id="input" type="text"/>
As mentioned in the comments, please make sure your JavaScript code is loaded after your markup. There are various ways to do this, including waiting for the dom to load.
See $(document).ready equivalent without jQuery and How does the location of a script tag in a page affect a JavaScript function that is defined in it? for more information.
Try this
document.getElementById('input').value = document.getElementById('candy').dataset.value
<div id="candy" data-value="valueOfCandy" ></div>
<input id="input" type="text" value=""/>
This is not how you should be doing this.
JavaScript should be separated out of the HTML completely to avoid a whole host of issues. Including JavaScript in the HTML as you are attempting is a 20+ year old technique that was used before we had standards.
Next, a div element can't have a value attribute. value is only for form fields. But, you can create a data-* attribute, which allows for you to create custom attributes. You can then extract that value using the .dataset property.
See below:
// This code would be placed inside of <script> and </script> tags and the whole
// thing would be placed just before the closing body tag (</body>).
document.getElementById("result").value = document.getElementById('candy').dataset.value;
<div id="candy" data-value="valueOfCandy"></div>
<input type="text" id="result">
Put that code either within a script tag or in a separated js file.
Further, always bind the event DOMContentLoaded when you need to manipulate DOM elements.
DOMContentLoaded
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
This way, your logic is totally consistent.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById('candy2').value =
document.getElementById('candy').getAttribute('value')
});
<div id="candy" value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
A recommendation is to use data-attributes because the value attribute is related to form fields:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById('candy2').value =
document.getElementById('candy').dataset.value;
});
<div id="candy" data-value="valueOfCandy"></div>
<input id="candy2" type="text" value="" />
I know I can create several types of options, questions, checkboxes, and buttons using in HTML. How can I save the response a user enters and assign it to a variable? Here's the code I'm using right now:
HTML:
<input type="text" value="Hotel Name" id="questionOne"><h1 display="block">WHAT IS THE NAME OF THE HOTEL</h1><br>
<input type="button" value="HELLO" onclick="testFunction()">
JS:
function testFunction() {
prompt(document.getElementById("questionOne").value;);
}
Shouldn't it activate the function when the HELLO button is clicked, and then it identifies the response through the ID "questionOne" and creates a prompt with the variablev value? I don't understand why it's not working.
I'm new to JS and HTML so please don't go crazy if it's a simple answer. Thank you.
I think your problem is to do with where things are defined. Rather than using onclick, add an event listener in your js. e.g.
document.getElementById ("bar").addEventListener ("click", foo);
function foo() {
prompt(document.getElementById("questionOne").value);
}
and just change the button to have an id and get rid of the onclick:
<input type="button" id="bar" value="HELLO">
Well you can just add event Listener to your input.
Like
document.getElementById('questionOne').addEventListener('input',function(){
var somevariable = prompt(this.value,'');
});
That will save the answer of prompt to 'somevariable'.
I am trying to populate an input, of type text, with the the file name that has been selected. From what I have read sometimes you have to set the value to "" or null onClick then onchange set the place holder.
I have tried many different variations, but it just doesn't seem to fire. What am I overlooking?
My very basic example....
<script type="text/javascript">
getElementById("upFile").onClick = function(){
this.value = "";
}
getElementById("upFile").onchange = function(){
getElementById("uploadName").value = this.value;
}
</script>
<input type="text" name="uploadName" id="uploadName" placeholder="Attachment Title">
<input type="file" id="upFile" name="upFile" enctype="multipart/form-data"><br>
What I have read
Changing the placeholder text based on the users choice
Change placeholder text
Upload files using input type="file" field with .change() event not always firing in IE and Chrome
HTML input file selection event not firing upon selecting the same file
None of which seem to be my issue...
Here you go. You can get rid of the onclick event listener, and watch for changes instead. The file upload element creates an array of files and you can access it like so:
<input type="text" name="uploadName" id="uploadName" placeholder="Attachment Title">
<input type="file" id="upFile" name="upFile" enctype="multipart/form-data">
<script>
document.getElementById("upFile").onchange = function(){
// single file selection, get the first file in the array
document.getElementById("uploadName").value = this.files[0].name;
}
</script>
FYI:
This is what happens if the script tag is before the element. It runs the script once read and says it can't find the element referenced with document.getElementById("upFile")
Uncaught TypeError: Cannot set property 'onchange' of null
at :2:48
You are missing document.getElementById and onClick should be onclick
So I have javascript code to prepend "tag:" or "vendor:" before every search term, but I wanted to hide that from the user, so I created a hidden input field to send the code but it's not properly prepending the "tag:" and "vendor:" before every word. and instead inputs the entire string, then the search terms.
<form method="get" action="/search" id="search-home">
<button type="submit" value="search"></button>
<input type="hidden" name="type" value="product" />
<input type="hidden" name="q" class="searchtext" />
<input type="text" name="red" placeholder="Search"/>
</form>
<script>
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
</script>
Here's what the Url looks like with the code
http://zzz.co/search?type=product&q=tag%3A+OR+vendor%3A&red=tote#fullscreen=true&search=home
Here's what it's supposed to look like.
http://zzz.co/search?type=product&q=tag%3Atote+OR+vendor%3Atote#fullscreen=true&search=home
You're getting an empty value and inserting it here:
$(document).on('submit','#search-home',function(){
var searchtext = $('.searchtext').val(); // <- HERE
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
What you should be doing is getting the user given query, which is the input you named "red".
$(document).on('submit','#search-home',function(){
var searchtext = $('input[name="red"]').val();
$('.searchtext').val("tag:"+searchtext+"* OR vendor:"+searchtext+"*");
});
With the above fix, your URL will look similar to:
http://zzz.co/search?type=product&q=q=tag%3Atote+OR+vendor%3Atote&red=tote.
I do not know where you're getting your hashbang(#) from, but I would assume it will append at the end as before.
If you want to get rid of the red=tote part, you have a few options. Emptying the value via $('input[name="red"]').val(''); will make it appear in your url as red=. If you want it gone entirely, you should use $('input[name="red"].remove();.
I would also advise having your "on" hook attached to the form, not the entire document. This is just a good practice to avoid using unnecessary resources as this hook will bubble every time a form is submitted, regardless of the selector. Instead, consider:
$('form#search-home').on('submit', 'button[type="submit"]', function() { ... };
That way it will only bubble when a submit event happens on that specific form, greatly reducing the possible instances those resources are used.
I have the worlds most simple javascript function:
fnSubmit()
{
window.print();
document.formname.submit();
}
Which is called by:
<button type="button" id="submit" onclick="fnSubmit()">Submit</button>
All is well and good, the print dialog shows up, however after printing or canceling the print I get the following error:
"document.formname.submit is not a function"
My form is defined as follows: (obviously I am not using formname in the actual code but you get the idea)
<form name="formname" id="formname" method="post" action="<?=$_SERVER['SCRIPT_NAME']?>">
Obviously I am not trying to do anything special here and I have used similar approaches in the past, what in the world am I missing here?
In short: change the id of your submit button to something different than "submit". Also, don't set the name to this value either.
Now, some deeper insight. The general case is that document.formname.submit is a method that, when called, will submit the form. However, in your example, document.formname.submit is not a method anymore, but the DOM node representing the button.
This happens because elements of a form are available as attributes of its DOM node, via their name and id attributes. This wording is a bit confusing, so here comes an example:
<form name="example" id="example" action="/">
<input type="text" name="exampleField" />
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
On this example, document.forms.example.exampleField is a DOM node representing the field with name "exampleField". You can use JS to access its properties such as its value: document.forms.example.exampleField.value.
However, on this example there is an element of the form called "submit", and this is the submit button, which can be accessed with document.forms.example.submit. This overwrites the previous value, which was the function that allows you to submit the form.
EDIT:
If renaming the field isn't good for you, there is another solution. Shortly before writing this, I left the question on the site and got a response in the form of a neat JavaScript hack:
function hack() {
var form = document.createElement("form");
var myForm = document.example;
form.submit.apply(myForm);
}
See How to reliably submit an HTML form with JavaScript? for complete details
Given that your form has both an id and a name defined, you could use either one of these:
With the form tag's id:
document.getElementById('formname').submit();
With the form tag's name attribute:
document.forms['formname'].submit();
Try this:
fnSubmit()
{
window.print();
document.getElementById("formname").submit();
}
The most likely culprit is IE confusing JavaScript variables, ids, and names. Search in your source for something sharing the name of your form.
Place a input button inside your form.
Give tabindex="-1" on it.
Make It invisible using style="display:none;".
Like This
<input type="submit" tabindex="-1" style="display:none;" />