How can I create new variables within a loop? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a form and I want to retrieve the values by their id's. Instead of writing var itemnamehere = document.getElementById('theid'); multiple times, I want to be able to loop through the inputs in the form and create variables within a for loop.
This is what I have so far
var gsItems = document.getElementsByClassName('gsinput').getAttribute('id');
for(var i = 0; i < gsItems.length; i++){
//create new variable here
}

Because getElementsByCLassName returns an nodelist you can't use getAttribute on it because that method is reserved for single elements only. BUT you also don't need the id either if I understand your question. You can simply iterate over the nodelist you get with getElementsByCLassName and do whatever you need to with the inputs, like grab their values.
Here's how you might approach it with ES6:
const gsItems = document.getElementsByClassName('gsinput');
[...gsItems].forEach(item => {
console.log(item.value);
});
<input class="gsinput" value="1" />
<input class="gsinput" value="2" />
<input class="gsinput" value="3" />
<input class="gsinput" value="4" />
<input class="gsinput" value="5" />
If you wanted to use ids you might want to create a map of ids against values. You could do something like this with reduce:
const gsItems = document.getElementsByClassName('gsinput');
const obj = [...gsItems].reduce((obj, item) => {
obj[item.id] = item.value;
return obj;
}, {});
console.log(obj);
<input class="gsinput" id="steve" value="1" />
<input class="gsinput" id="daisy" value="2" />
<input class="gsinput" id="tina" value="3" />
<input class="gsinput" id="dennis" value="4" />
<input class="gsinput" id="bob" value="5" />
And here's the ES5 method:
const gsItems = document.getElementsByClassName('gsinput');
Array.prototype.forEach.call(gsItems, function (item) {
console.log(item.value);
});
<input class="gsinput" value="1" />
<input class="gsinput" value="2" />
<input class="gsinput" value="3" />
<input class="gsinput" value="4" />
<input class="gsinput" value="5" />

Id is not perfect approach to get multiple form input values when using a loop.
function getSubmitValue(params) {
var formObject = document.theForm;
var itemnamehere = [];
if (formObject.length) {
for (var i = 0; i < formObject.length; i++) {
if (formObject[i].value !== "") {
itemnamehere.push(formObject[i].value);
}
}
} else {
alert("Please check your form input value")
}
}
<form id="myForm" name="theForm">
<input type="text" name="user" id="user" value="Arsalan" />
<input type="text" name="occopation" id="occopation" value="doctor" />
<input type="number" name="age" id="age" value="27" />
<input type="text" name="email" id="email" value="johndoe#test.com" />
<textarea name="message" id="message">Enter Your Message Her</textarea>
<button type="submit" onClick="getSubmitValue()">Place Order</button>
</form>

Related

javascript jquery find multiple hidden input without specific attribute

Can javascript or jquery create an array of values from multiple hidden inputs with randomly created ids (in other words, no specific attribute to search for)? The code below only results in the alert of the first hidden input, 'abc'...
Thanks
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
<script>
//create hidden fields array
var hiddenFields = [];
//for each table row
$('html').each(function()
{
//get hidden field
if (hiddenField != $(this).find("input[type='hidden']").val()){
var hiddenField = $(this).find("input[type='hidden']").val();
}
//if not empty push to array
if(hiddenField!='undefined'&& hiddenField !=null )
hiddenFields.push(hiddenField);
});
alert(hiddenFields);
</script>
Maybe try this:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
JS
var tags = document.getElementsByTagName("input");
for(var i = 0; i < tags.length; i++){
if(tags[i].getAttribute("hidden") == null){
console.log(tags[i].value);
}
}
Codepen - https://codepen.io/anon/pen/jxRVMb?editors=1010
You're only calling .val once after you .find, so it only returns the value of the first element in the jQuery collection. ($('html').each will only iterate once, because there's only one html tag in the document)
You can try something like this instead, no jQuery needed:
const hiddenFields = [...document.querySelectorAll('input[type="hidden"]')]
.map(input => input.value);
console.log(hiddenFields);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
You should also try to fix the HTML so that there are no duplicated IDs; that's invalid.
If you wanted to use jQuery iteration:
const hiddenFields = $.map($('input[type="hidden"]'), input => $(input).val());
console.log(hiddenFields);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
Can use a combination of filter() and map()
var results = $("input[type='hidden']").filter(function() {
return this.value // only return elements that have value
}).map(function() {
return this.value // pass the value to array
}).get()
console.log(results)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />
Grab all hidden inputs and then you can fetch value by iterating on it using forEach loop
const hiddenInputs = document.querySelectorAll('input[type="hidden"]');
const hiddenInputValues = [];
hiddenInputs.forEach((ele) => {
hiddenInputValues.push(ele.value);
});
console.log(hiddenInputValues);
<input type="hidden" id="some_random_id" value="abc" />
<input type="hidden" id="some_random_id" value="def" />
<input type="hidden" id="some_random_id" value="ghi" />

How to send multidimensional array from php to javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to get this "data" multidimensional array value in my javascript function. How can I get it?
Here is my code: https://jsfiddle.net/tanzilamohita/7nhv5h8h/
function getJSarray(){
var data = new Array;
data = document.getElementsByName("data[]");
alert(data.length);
//alert(hidden_courses[2].value);
}
Simply by using starts-with selector $('[name^="data["]') in jquery
function getJSarray() {
var data = new Array;
data = $('[name^="data["]');
alert(data.length);
console.log('Alternatively use querySelectorAll '+document.querySelectorAll("input[name^='data[']").length);
return false;
//alert(hidden_courses[2].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" onsubmit="return getJSarray()">
A1<input type="radio" name="data[0][]" value="1" /><br /> A2
<input type="radio" name="data[0][]" value="2" /><br /> B1
<input type="radio" name="data[1][]" value="3" /><br /> B2
<input type="radio" name="data[1][]" value="4" /><br />
<br /><br />
<input type="submit" name="save" value="Save" />
</form>
Alternatively, use querySelectorAll() like, document.querySelectorAll("input[name^='data[']");
To get the checked elements use :checked-selector like
function getJSarray() {
var data = new Array;
data = $('[name^="data["]:checked');
alert(data.length);
return false;
//alert(hidden_courses[2].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" onsubmit="return getJSarray()">
A1<input type="radio" name="data[0][]" value="1" /><br /> A2
<input type="radio" name="data[0][]" value="2" /><br /> B1
<input type="radio" name="data[1][]" value="3" /><br /> B2
<input type="radio" name="data[1][]" value="4" /><br />
<br /><br />
<input type="submit" name="save" value="Save" />
</form>

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Sum input fields by using javascript [duplicate]

This question already has answers here:
compute sum dynamically with javascript
(5 answers)
How get total sum from input box values using Javascript?
(9 answers)
Closed 9 years ago.
How could I sum the fields automaticly (by each function) to sum some input fields like this:
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
Thank you very much if anyone has a suggestion?
Use jQuery;
<script src="{path to jquery}/resources/js/vendor/jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
var total = 0;
$.each($('input'), function(){
total += parseInt($(this).val(), 10); //use radix 10 to ensure correct parseInt val
});
console.log(total);
});
</script>
On jsfiddle
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
var inputs = document.getElementsByTagName("input");
function sumIt() {
var sum = Array.prototype.reduce.call(inputs, function (a, b) {
return a + parseFloat(b.value);
}, 0);
console.log(sum);
}
Array.prototype.forEach.call(inputs, function (input) {
input.addEventListener("keyup", sumIt, false);
});

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

Categories

Resources