Get all file/img input fields from a form with Javascript - 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

Related

how to get the files from multiple input file control?

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.

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/

Javascript get form array values

I have a form that is set up so that there is an add button so my user can submit multiple people at once to the site.
At first the form has an input to fill out the persons name one example below
<input type="text" name="name[]" value="Name" />
If they hit the add button another one is appended so that I'm left with the following
<input type="text" name="name[]" value="Name" />
<input type="text" name="name[]" value="Name" />
Then when they hit submit I'm trying to get the values of each name in Javascript and loop through them I've tried this but it's not working
var inputs = document.getElementById('formIDhere').getElementsByTagName('name');
alert(inputs.length);
I never get the alert and if I just set up a loop like this
for(int i=0; i<inputs.length; i++)
Nothing happens, any help on looping through the values of name[] in javascript would be greatly appreciated
I guess you could try:
var inputs = document.querySelectorAll("#formIDHere input[name='name[]']");
alert(inputs.length);
for (i = 0; i < inputs.length; i++) {
// your code here
}
Simple approach:
var names=document.getElementsByName('name[]');
for(key=0; key < names.length; key++) {
alert(names[key].value);
//your code goes here
}
[...document.querySelector("#FORMID").elements['name[]']].map(el=>el.value);
// Returns ["name","name",...]
I think you can use document.getElementById('formIDhere').elements.name.
It will give you an array with all the values.
your mistake is using getElementsByTagName, which is asking for a tag called <name>, and of course you don't have it, try setting a class to the input for example and fetch it using jquery $('className') which will surely get the result correct, or using dom you can still use
document.getElementById('form').elements.name but still this way might not be cross browser safe unless tested carefully
getElementsByTagName returns the array of elements whoose tag name is specified in argument.
In html there is no element whoose tag name is name.
name is an attribute given to html elements.
To get elements based on name you can use
var ele=document.getElementsByName('whatevername');
ele will contain the array of elements whose name is specified. Then you can use your loop to iterate through each element.
this is what form elements is for
var inputs = document.getElementById('formIDhere').elements["name[]"];
alert(inputs.length);
for (i = 0; i < inputs.length; i++) {
// your code here
}
Using JQuery you could try:
var arr = $('#frmId').serializeArray();
serialize method offers several options that you could check in: https://api.jquery.com/serializearray/

How can I apply a function to several images in jQuery?

I need a little help with (probably) something really simple.
I want to use a script which converts images from color to grayscale.
I got it working partially — the first image turns gray, but the second won’t.
I know this is because an id cannot be used multiple times:
var imgObj = document.getElementById('grayimage');
I tried this:
var imgObj = $(’.grayimage’)[0];
But it didn’t work. Changing it to getElementByClass also does not work. (Before people ask, I did change the id to class in the <img> tag.)
I really could use some help here. Thanks in advance!
$('.grayimage').each(function(idx,imgObj){
<do your code here>
});
$('.grayimage') gives you a list of all elements with grayimage as a class. If you add '[0]' you're accessing the first element, so any changes you make will apply to only the first image that it finds with this class.
You should loop through all elements:
var images = $('.grayimage');
for(i = 0; i < images.length; i++) {
var image = images[i];
// Do stuff
}

YUI Button apply by class name

Is it possible to apply / create a YUI Button by using an element's class name and not by id. I have to generate a list of buttons then transform it to a YUI button.
[Update]
By the way, I'm trying to apply the button in an anchor tag. So it will be a link button.
[Update:Code]
Ok so here's the code. I have a loop that generates this anchor tag.
<a class="system-button" href="/system/edit/12">Edit</a>
wrumsby's answer perfectly makes sense. But I don't know why it doesn't work. I tried debugging it and the elements are successfully fetched. But it seems that no YUI Buttons are created.
I even tried generating unique ids for the elements but still no luck.
Any ideas?
Looks like I've solved it myself. But I'm not sure if this is the best solution. I generated unique ids then create the buttons.
var i = 0;
$(".system-button").each(function(i,b){
var button = new YAHOO.widget.Button($(b).attr('id','system-button'+i).attr('id'));
i++;
});
And oh yes, I use JQuery here. That framework is so awesome.
You should be able to use the srcelement configuration attribute like so:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
Button = YAHOO.widget.Button;
Event.onDOMReady(
function() {
var elements = Dom.getElementsByClassName('...');
for (var i = 0; i < elements.length; i++) {
var button = new Button({
srcelement: elements[i],
...
});
...
}
}
);
})();

Categories