how to get the files from multiple input file control? - javascript

I have multiple file input controls which are dynamically generated through code. I tried to put sample script which is as below
<input type="file id="file1" />
<input type="file" id="file2" />
JS:
$(document).ready(function(){
$('input:file').on('change', function ()
{
for (var i = 0; i < this.files.length; i++)
{
alert(this.files[i].name);
}
});
});
I think my code is in getting the files is wrong.

I think you can do something like this:
$('input[type="file"]').on('change', function() {
$('input[type="file"]').each(function() {
alert($(this).val());
});
});
If I understood your question correctly this should do what you need. The problem with your code was that you gave the selector multiple items to listen for a change on, however each item matched with the selector, in this case two items given your example html markup, triggers the on to fire with the <input /> that had the value change.
This code should listen for a change in any file input, then on change it will again using the same selector now scan both inputs and output the value. In this code though, it will output the path to the file, so you will need to do some regex replace or something else to get to just the filename.

Related

How to hide an upload file element using javascript?

Its quite wierd .
My structure is
<form name="fm">
<input type="file" name="fl">
<input type="text" name="st">
</form>
Now document.fm.st.hidden=true; works as expected hiding the text box but document.fm.fl.hidden=true; doesnt works , it doesnt hides the file upload element ! Why & how to work around ?
It sounds like this might be a case of the script running before the page is completely loaded. If you want to be absolutely sure that the page is loaded before the script runs, you can do something like this:
document.onload = function(){ // if you want it could also be window.onload
document.fm.st.hidden = true;
document.fm.fl.hidden = true;
};
Cant you just give it an id and use
document.getElementById('yourID');
other whise maybe you can make a css class for it and use Jquery
.addClass() and .removeClass()
if you want to keep the input's space than apply visibility = "hidden" otherwise display = "none".
get Element by name
var inputElements = document.getElementsByName("fl");
This will provide you a list of the elements which have name 'fl'.
Now if you want to hide all the elements, run a loop.
For now, it'll provide only an element.
var inputElement = inputElements[0];
I would suggest using jQuery if you want to keep using javascript for long.
now hide the element
inputElement.style.display = "none";
For starters, make sure your script is after your element. The javascript you provided should work as you provided it, but if it doesn't, try the following:
<form name="fm">
<input type="file" name="fl">
<input type="text" name="st">
</form>
<script>
// hides the element (it will still take up space)
document.getElementsByName("fl").style.visibility="hidden";
// hides the element (it does not take up any space)
document.getElementsByName("fl").style.display="none";
</script>

Get all file/img input fields from a form with Javascript

Seems like such a novice question but I'm stuck. I have a form in which user can dynamically add rows of <input... and select images to be added inside a textarea. Upon submitting, I'm trying to select all rows with images.
<input type="file" class="pics" name="file[]" onchange="imgChanged(this)"><img class="addImg" onclick="addRow(this)" src="../img/addmore.png">
So there's a possibility of "n" number of images. The inputs have the class of "pics". How can I get them all before uploading using the new FormData in JS? I can't seem to get it like this...
var imgs = document.getElementsByClassName("pics").files
And then use it like this
for (var i = 0; i < imgs.length; i++) {
var file = imgs[i];
formData.append('photos[]', file, file.name);
}
Hope this is an easy solutions. Thanks for your help.
Changing it to getElementById would work. Refer the example at end here: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

JS/HTML Image changer with dynamic img src

Essentially I'm adding some JS to a site that allows the same set of buttons to load images(colour options) based on the ONLY image found within an ID. WIP to illustrate:
http://www.twistfurniture.co/collections/product-test/
So what I've done thus far:
<div id="switchgallery">
<img src="/wp-content/uploads/Chair.jpg" id="switchimage">
</div>
<p>
<input id="Button1" type="button" value="Show black" onclick="ShowBlack()"/>
<input id="Button2" type="button" value="Show red" onclick="ShowRed()"/>
</p>
JS
function ShowBlack()
{document.getElementById("switchimage").src = "/wp-content/uploads/Chair_Black.jpg";}
function ShowRed()
{document.getElementById("switchimage").src = "/wp-content/uploads/Chair_Red.jpg";}
Now this works but if I have lots of colours and lots of products it'll take ages and require coding each time a new product is adding (productname=Chair in the above example).
What I'd like to accomplish is the following.
function ShowBlack()
{document.getElementById("switchimage").src = "***Dynamically generate the SRC of the image based on the ID of switchimage and and add _Black before the file extension =(/wp-content/uploads/Chair_Black.jpg)***";}
That way I can add lots of products and so long as they have the correct ID and the buttons are on the page I will get an easy method to switch their colour (assuming I have uploaded the appropriately named files in the right directory ;D)
Like I mentioned this is a work in progress and I will continue to fiddle until either I solve this myself or you guys flip over the ICT Hero card.
I've learned a lot by reading these forums, but now need direct assistance! Many thanks in advance
What you need is to setup a function with a parameter color :
function showImage(color) {
document.getElementById("switchimage").src = "/wp-content/uploads/Chair_"+color+".jpg";
}
this color can easily be a parameter of the button that you load with a function like that
function showImage() {
{
var color = jQuery(this).attr("color");
document.getElementById("switchimage").src = "/wp-content/uploads/Chair_"+color+".jpg";
}
with button definition like
<input id="Button1" type="button" value="Show black" onclick="showImage()" color="black"/>
Since your site is a Word Press site, I would recommend using one of the many plugins available, like this.
While I will be the first to want to use my own custom code, Word Press plugins are the best way to work within Word Press. While it may seem straight forward, there are a lot of things to consider. For example, how to determine what the product is and what images are available for said product. Javascript is a client side library and won't give you the best solution for something like a product catalog unless you have full control over the site.
You have a couple options:
Use data.
You can use the data attribute to store which color to load.
<button data-color="Red">Red</button>
jsfiddle: http://jsfiddle.net/PThwj/
Use arguments
<button onlick="loadImage('black');">Black</button>
jsfiddle: http://jsfiddle.net/gt6BS/1/
The load image function looks like this:
function loadImage(color) {
document.querySelector("#image").innerHTML =
"/wp-content/uploads/Chair_" + color;
// Change source of image here by using img.src
}
To bind events dynamically (if you use option 1) do this:
var buttons = document.querySelectorAll(".chair-button");
for (var i = 0; i < buttons.length; ++i) {
buttons[i].addEventListener("click", loadImageEvent);
}
Now you can add <button>s and specify a data-color and the rest will take care of itself.
This should work:
function ShowBlack()
{
source = document.getElementById("switchimage").src;
if (source.lastIndexOf("_") != -1){
source = source.substring(0,source.lastIndexOf("_"));
}else{
source = source.substring(0,source.lastIndexOf("."));
}
source += "_Black.jpg"
console.log(source);
document.getElementById("switchimage").src = source;
}
function ShowRed()
{
source = document.getElementById("switchimage").src;
if (source.lastIndexOf("_") != -1){
source = source.substring(0,source.lastIndexOf("_"));
}
else{
source = source.substring(0,source.lastIndexOf("."));
}
source += "_Red.jpg"
document.getElementById("switchimage").src = source;
}
Here is a fiddle : http://jsfiddle.net/TQhJk/1/

Add items to drop-down box

I can't seem to find the correct syntax to get this working:
$.get('/templates/mytemplate.html', function (template) {
$(template).find('select').append($("<option />").val(0).text('Please select ...'));
$.each(dashboard.myArray, function () {
$(template).find('select').append($("<option />").val(this.Id).text(this.Text));
});
$('#new-items').append(template);
});
The template variable is just a string of html like:
"<form class="user-item">
<select class=".sc" name="context" />
<input type="hidden" name="id"/>
<input type="hidden" name="date"/>
<form>"
I've tried selecting the select item on name 'select[name=context]' and using a class selector like '.sc' as well ... none seem to work but I've got similar code working fine elsewhere. Very confused.
The problem is template is a string. in your case you are creating a new jQuery wrapper for that element every time and manipulating it but that does not actually change the contents of the string in template, it just changes another in memory object
You need to create a reference to a new jQuery wrapper for template then do the dom manipulation using that reference and at the end append it to the container element
$.get('/templates/mytemplate.html', function (template) {
var $template = $(template);
$template.find('select').append($("<option />").val(0).text('Please select ...'));
$.each(dashboard.myArray, function () {
$template.find('select').append($("<option />").val(this.Id).text(this.Text));
});
$('#new-items').append($template);
});
Demo: Problem, Solution
such code will work
var value = 'some_value',
text = 'some_text';
$('#id').append($('<option value='+value+'>'+text+'</option>'));
the reason your code it's not working is you are modifying a variable but don't assign the changes to variable
$(template).find('select').append($("<option />").val(0).text('Please select ...'));
this line never stores changes to template, it should be :
template = $(template).find('select').append($("<option />").val(0).text('Please select ...'));

create a pop-up window and display a list of radio buttons using javascript

I'm writing on a js file.
Here is what I've tried so far. (My code is a bit long but here is what I'm trying to do)
var popUpList= $ ('<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C');
var showPopUpButton=$('<button type="button">Select a Letter</button>');
// showPopUpButton is appended to the body
showPopUpButton.click(function() {
alert(popUpList);
});
When I click on showPopUpButton, the alert window shows [object Object], which I guess means that the variable popUpList is empty.
I couldn't find how to do that in javascript.
I also tried with jQuery as suggested here Create a popup with radio box using js
var popUpList= $ ('<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C ');
showPopUpButton.click(function() {
popUpList.dialog();
});
Now, the buttons are displayed but not inside a pop-up window! And they are all superposed.
Any help will be appreciated.
Thanks!
You need to wrap your <input>s in a container element, e.g.: <div>, because dialog() works on a single element.
In your code, you are asking the dialog() function to work on multiple DOM objects and thus it will fail.
Here is the code:
var popUpList = $('<div><input type="radio">A<br><input type="radio">B<br><input type="radio">C</div>');
showPopUpButton.click(function() {
popUpList.dialog();
});
See it in action here. Try it yourself. :)
Changed your inputs to HTML string, parsing as HTML and inserting inside the #dialog element.
var popUpList= '<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C',
dialogHtml = $.parseHTML(popUpList);
showPopUpButton.click(function() {
$( "#dialog" ).html(dialogHtml).dialog();
});

Categories