Get all input values to javascript with the same id - javascript

I just want to get all different values using javascript with the same id.
Here is my input code:
<input type="text" id="full" name="full" value="2018-12-06">
<input type="text" id="full" name="full" value="2018-12-14">
<input type="text" id="full" name="full" value="2018-12-18">
When I alert the id of the inputs it show's the 2018-12-06 only. I want to disable the jquery datepicker but the 2018-12-06 is the only one read.
Here is my calendar.
and my javascript code:
var x = (document.getElementById('full').value);
var array = ["2018-12-25", "2019-01-01", x]
I want to disable all value with same id like the mention above,

IDs must be unique. You should add a class to each element and then use getElementsByClassName.
Because the method returns a nodelist to get each input value you need to iterate over it. For both these examples I've used map, but you might find a for/loop or forEach easier to use.
const full = document.getElementsByClassName('full');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">
An alternative might be to use querySelectorAll. This uses CSS selectors so you can pinpoint elements by their attributes instead:
const full = document.querySelectorAll('[name="full"]');
const arr = [...full].map(input => input.value);
console.log(arr);
<input type="text" name="full" value="2018-12-06">
<input type="text" name="full" value="2018-12-14">
<input type="text" name="full" value="2018-12-18">

ID is used as an individual identifier. So it is illegal to use same Id for multiple elements. To get values of multiple elements use class instead of id.
You can use getElementsByClassName() function to read values of all elements with same class name
Alternative to getElementsByClassName() using jQuery
var l = $('.full').length;
//Initialize default array
var result = [];
for (i = 0; i < l; i++) {
//Push each element to the array
result.push($('.full').eq(i).val());
}
//print the array or use it for your further logic
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="full" value="2018-12-06">
<input type="text" class="full" value="2018-12-14">
<input type="text" class="full" value="2018-12-18">

You can't create an element with the same Id, If you want to get all different values from another element using javascript you can use ClassName
<input type="text" class="full" name="full" value="2018-12-06">
<input type="text" class="full" name="full" value="2018-12-14">
<input type="text" class="full" name="full" value="2018-12-18">
var x = document.getElementsByClassName('full');

Related

Get an object from a DomElement Node without frameworks

I have an element in my page:
<form>
<div data-id="x">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
<div data-id="y">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
...other 100 inputs...
</form>
I'm looking for a javascript script like that:
var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();
And the object must looks like
{"field1":"Foo","field2":5}
I can't use the FormData strategy because I need a very small set of data from a very big form, but it is like a "partial FormData".
I'm asking if exists a standard method to convert the content of an HTMLElement in an object like for the FormData.
PS: i can use also the data-attribute if necessary
Actually there is no standard quicky method to do this task.
The solution is iterate over inputs and selects:
<script>
let myObj = {};
let element = document.querySelector('[data-id="x"]');
element.querySelectorAll('input').forEach(el=> {
// check the type
// the property is : el.name
// the value must be : el.value for text/number/email...
// the value for the type="checkbox" is according to checked attribute
});
element.querySelectorAll('select').forEach(sel=> {
// if multiple choise => create an array of selected options
// if single => check the selected option's value
});
</script>
This is the code i've used (simplified)

Set form names with javascript loop

I have a form with which a user can dynamically add text inputs. This generates a form with multiple text inputs that have the same name. If this form is submitted they overwrite each other. To solve this I need change the names so that they are appended with an incremented prefix when the form is submitted. Can anyone help?
Example of form (once three inputs have been added):
<form action="" method="post">
<td class="recipe-table__cell">
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
</td>
<input type="submit" value="Submit">
</form>
Desired Post output on submission:
Array ( [1-answer] => test [2-answer] => ok [3-answer] => nice)
rather than Array ( [answer] => test )
First, select all of the elements that you want to add the attribute for. This can be done with .querySelectorAll().
Second, loop over those elements.
Third, use .setAttribute() to change the name attribute to append the index from the loop.
Note that you'll also want to increment the ID attribute, as you can't have duplicate IDs on the same page. You'll also want to swap your <td> elements for <div> elements to both allow .querySelectAll() to work correctly, and ensure valid markup.
This can be seen in the following example:
var inputs = document.querySelectorAll("form div input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("id", "answer" + i);
inputs[i].setAttribute("name", "the_answer" + i);
console.log(inputs[i]); // Added purely to show the change
}
<form action="" method="post">
<div class="recipe-table__cell">
<input id="answer" name="the_answer" type="text" value="">
<input id="answer" name="the_answer" type="text" value="">
<input id="answer" name="the_answer" type="text" value="">
</div>
<input type="submit" value="Submit">
</form>
Hope this helps! :)

How can I store multiple sets of input values in JS?

Consider the following pairs of inputs
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
The number of pairs of inputs on a page is dynamic, not fixed.
I wish to loop through all pairs and store values as pairs to be output later into a table for example.
I've been trying to do it with jQuery's each() but I can't figure it out fully.
var detail = [];
//var detail = {};
$('input').each(function(index) {
detail[index] = $(this).val();
//detail.index = $(this).val();
});
console.log(detail);
This outputs
["iphone", "10", "macbook", "5"]
And it's not what I need.
I'm used to PHP, so what is the correct approach in JS/jQuery to store the pairs of inputs as a multidimensional associative array/object?
You can iterate over the elements with class item_name and create an array of objects that each have a name and qty property.
You can create this array more easily using jQuery's .map():
var details = $('.item_name').map(function() {
return {
name: $(this).val(),
qty: $(this).next('.item_qty').val()
};
}).get();
console.log(details);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
The equivalent of an associative array in javascript is an object (both act as a dictionary)
The problem you have is that your html describes a key and a value as inputs in a flat list, so when you enumerate them with your JQuery .each() you get them back all in one list.
[key, value, key, value]
what you most likely want is an object like:
var obj = {
key: value,
key: value
}
Then you can get at say the 'macbook' property like so
obj.macbook or obj['macbook']
You can achieve this by either looping through the list two at a time and adding them to the object, or by restructing your html to have both the key and value inputs inside another element e.g.
<div class="item">
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
</div>
<div class="item">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
</div>
Then you can do something like this:
var items = {}
$('.item').each(function(){
var key = $(this).find('.item_name').val()
var value = $(this).find('.item_qty').val()
items[key] = value;
})
var val = $("input.item_name").map(function(){
obj = {}
obj[$(this).val()] = $(this).next("input.item_qty").val();
return obj;
}).get()
console.log(val)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
Use .map()
You can use recursion, Array.prototype.slice() to slice two <input> elements at each function call, populate an object with key, value pairs until <input> elemnents .length is reached
var [obj, n] = [{}, 2];
var inputs = $("input[type=text]");
var res = (function re(i) {
if (i + n <= inputs.length) {
var [key, prop] = Array.from(inputs).slice(i, i + n).map(({value}) => value)
obj[key] = prop;
i += n;
return re(i)
} else {
return obj
}
})(0);
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="item_name" value="iphone">
<input type="text" class="item_qty" value="10">
<input type="text" class="item_name" value="macbook">
<input type="text" class="item_qty" value="5">
You can try a quick and "dirty" solution:
Ref: for each input type get value with javascript
You were on the right track with .getElementById, but you want instead, .getElementsByName.
var els = document.getElementsByName("filter[]");
for (var i = 0; i < els.length; i++)
alert(els[i].value);
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
Or, follow this: jQuery .each() with input elements
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
Edit : .map implementation
var arrText= $('input[type=text]').map(function(){
return this.value;
}).get();

Read HTML array using javascript or jQuery

I have array element in HTML
<input type="checkbox" value="Value1" name="model[settings][]">
<input type="checkbox" value="Value2" name="model[settings][]">
<input type="checkbox" value="Value3" name="model[settings][]">
I am reading all the HTML input, iterating it and building a hash in the javascript. But this will read the array element and only pick the last model[settings][] element.
var inputs = jQuery(" :input", "#elementID");
Is there a way in jQuery or JavaScript to read and build an array variable in javascript which then can be passed to controller ?
Thank You
If I understand you correctly, you are trying to iterate through all your input elements to get their value and store that as a JS object, correct?
If that's the case, I would add a unique ID to all my inputs, and then create an object with the structure { id : value }:
function getInputObject(sel) {
sel = $(sel);
var out = {};
sel.each(function() {
out[$(this).attr("id")] = $(this).val();
});
return out;
}
$(document).ready(function() {
console.log( getInputObject("input") );
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" value="value input 1" type="text" />
<input id="input2" value="value input 2" type="text" />
<input id="input3" value="value input 3" type="text" />

javascript (math) adding up an array

I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++){
if (inputs[i].type = "text"){
total += parseInt(inputs[i].value, 10);
}
}
alert(total);
<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />
JS:
var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);
<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />
This will work:
var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)
Note Do not have other tags with id="price1" or id="price2"
What you have written will not work, for several reasons. Firstly, as the name suggests, getElementById gets an element based on the value of the id attribute. You haven't given your input elements an id attribute, so that's not going to work.
Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:
var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);
This will work with the following HTML:
<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />
Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.

Categories