Javascript get form array values - javascript

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/

Related

Javascript can't apply an existing function to onkeyup

I have a bunch of HTML number inputs, and I have grabbed them by
x=document.querySelectorAll('input[type="number"]');
I then try and iterate through this with a for-loop, and apply an onkeyup function. The function is this:
t=function(elem){
elem.onkeyup=function(e) {
if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
elem.value='';
}
};
};
Basically, what it does is clear the value of the input if there is a letter typed in. I know I can apply it via HTML:
<input type='number' onkeyup='t(this)'/>
But how can I do it with Javascript? I tried iterating through it with:
x=document.querySelectorAll('input[type="number"]');
for(i=0; i<x.length; i++){
x[i].onkeyup=t(this);
}
but it doesn't work. What am I doing wrong? How can I do this? Please regular JavaScript answers only, no jQuery or other frameworks/libraries.
change
x[i].onkeyup=t(this);
to
x[i].onkeyup=t(x[i]);
because this isn't what you want it to be
Apologies, all. I found my answer. Agreeing with Jaromanda X, I needed to change
x[i].onkeyup=t(this);
to
x[i].onkeyup=t(x[i]);
This (pun intended ;)was part of the problem, but the main problem was that the valid property name is
keyup=function();
and not
onkeyup=function(){}'

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

Empty validation not working in a particulor empty textbox

I've few similar textboxes. When i run the validation script given below, One of them isn't affected the first time, even though it's empty. I'd like to know why.
Following is the HTML:
<input type='text' class='txt' value="" />
<input type='text' class='txt' value="" />
<input type='text' class='txt' value="" />
<input type='button' onclick='validate()' value='validate' />
JS:
function validate() {
var txts = document.getElementsByClassName('txt');
for (var i = 0; i < txts.length; i++) {
if(txts[i].value === "")
txts[i].className = 'txtError';
}
}
and CSS:
.txt {
border:1 px solid green;
}
.txtError {
border:1 px solid blue;
background:red;
}
This might be a dumb mistakes but i stared at it many times and my eyes isn't catching anything at the moment. I also tried it in different browsers.
Here's a JSfiddle demonstrating the problem.
Side note: i'm not looking for another validation script, i just want to know why the second textbox escapes the validation.
Because getElementsByClassName returns a live collection. Meaning it is updated underneath you as you change the DOM. So when you remove the txt class from the first box (replacing it with txtError you suddenly have an enumerable of size 2 instead of 3.
To fix it you can convert the live collection to a regular array using the array slicing trick
var txts = Array.prototype.slice.call(document.getElementsByClassName('txt'), 0);
However there are better ways to achieve pretty much everything that you're doing here. SO isn't really the place to discuss this but once you get it working go ahead and post it on the codereview stackexchange for feedback.
This seems like a strange issue and I cannot fully explain the issue. But when debugging and stepping though the code, every time you update the classname of one of the elements, your collection of txts decrements. Therefore, this is the only way I can think of to fix it. Basically the same thing you have, but instead I start with the last element of the txts array, instead of the first.
function validate() {
var txts = document.getElementsByClassName('txt');
for (var i = txts.length - 1; i >= 0; i--) {
if (txts[i].value === "") txts[i].className = 'txtError';
}
}
I think the problem arose because you were changing the class entirely instead of just adding a class; at least, it fixed the problem for me.
Here's a jsfiddle I created from yours that works fine by changing the behaviour to something more like jQuery's .addClass() method - I set .className = 'txt txtError' instead of just changing it to txtError.

onkeyup, get value from textbox, update another textbox, not working

Here is the javascript:
function changeText(containerId) {
var datatext = document.getElementById('masterText').value;
var collection = document.getElementById(containerId).getElementsByTagName('INPUT');
for (var x = 0; x < collection.length; x++) {
if (collection[x].type.toUpperCase() == 'TEXTBOX')
collection[x].value = datatext;
}
}
and this is the html
<input id="masterText" type="textbox" onkeyup="changeText('divGrid')"><br />
<div id="divGrid">
<input type="textbox"><br />
<input type="textbox"><br />
<input type="textbox"><br />
<input type="textbox"><br />
</div>
Suppose that all the textbox's value will change, but it is not. Do you know what is the error?
As I said in the comments, textbox is not a valid type for <input> elements. Although unknown types default to text, it might have somehow messed up the js (maybe the type property doesn't work right with unknown types), and changing it to just text seems to work fine, as you can see in this jsbin: http://jsbin.com/xakoxeyi/1/
My best guess at why this is happening is that using element.type doesn't work right with unknown types, so it doesn't have the value textbox, even though that's what html says. The best way to fix this is to change everything to text instead (as I said above), but another great way is to, instead of using collection[x].type, to use collection[x].getAttribute('type'), as using getAttribute always gives you what's in the HTML attribute
Just to expand on what Markasoftware said:
Had you chosen to get the attribute type, using getAttribute, your code would have worked.
function changeText(containerId) {
var datatext = document.getElementById('masterText').value;
var collection = document.getElementById(containerId).getElementsByTagName('INPUT');
for (var x = 0; x < collection.length; x++) {
if (collection[x].getAttribute('type').toUpperCase() == 'TEXTBOX') {
collection[x].value = datatext;
}
}
}
JSFiddle: http://jsfiddle.net/MSTUe/
So, my guess is that behind the scenes, an unknown type gets set as a text input, however you can still query an input with textbox, if needed. Probably for those awesomely new (but poorly supported) HTML5 inputs (like color, datetime-local, week, etc.) that a browser may not support.

How to change the value of id or name?

Example:
<table id ='table'>
<tr>
<td>1</td>
<td><select id='old' name='old'></select></td>
<td><select id='old2' name='old2'></select></td>
<td><div id='old3' name='old3'></div></td>
</tr>
</table>
How to change the value of id or name from select id ='old' to select id ='new' (for example) after deleting rows in javascript?
I have been trying all the methods like trying getElementById('old') = 'new' but not work, used replaceChild also not work (or maybe I put the wrong code, no idea).
Do you have other alternatives? (No JQuery, please).
Thanks.
You can use the setAttribute method to accomplish this
document.getElementById("old").setAttribute("id","new");
document.getElementById("new").setAttribute("name","new");
var sel = document.getElementById("old"); //Reference the element
sel.id = "new"; //set the id
try this :
document.getElementById("old").name = 'NewName';
alert(document.getElementById("old").name);
document.getElementById("old").id = 'Newid';
alert(document.getElementById("Newid").id);
its work for me.
I feel there is something inelegant going on here; if you told us more we'd be able to say the "right way" to do it. If you nevertheless have a very good reason to do what you're doing, merely call this snippet of code you have made all your changes. It will update all the elements in your rows to have the correct numbering.
var formElements = document.getElementById('table').getElementsByClassName('toUpdate');
for (var i=0; i<formElements.length; i++) {
var e = formElements[i];
e.id = 'new'+i;
}
There are quite a few variations on this if you didn't want to add a class="toUpdate ..." to each one. For example you were using regular form elements, you could iterate over the <form>'s elements. Or you could iterate through all the elements and pattern-match on the names or ids. Or if you are algorithmically generating this with javascript you could add each element to an array at the same time you add it to the DOM, for later use (like this update).

Categories