How do I get the values of classes in jQuery? [duplicate] - javascript

This question already has answers here:
jQuery access input hidden value
(9 answers)
Closed 1 year ago.
console.log($('.package_ids').val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="package_ids[]" name="package_ids[]" value="6" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="775" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="7207" />
I'm getting the right results when submitting this as a form. But when I get the value using jQuery I'm getting undefined.
I'm hoping to get something like an array [6, 775, 7207].

package_ids[] cannot be a class name. To get the expected array, you can use .map as follows:
const arr = $('.package_ids').map((i,elem) => +$(elem).val()).get();
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="package_ids" name="package_ids[]" value="6"/>
<input type="hidden" class="package_ids" name="package_ids[]" value="775"/>
<input type="hidden" class="package_ids" name="package_ids[]" value="7207"/>

You could select the items with their name property, e.g.:
let values = [];
$('[name="package_ids[]"]').each(function (i, v) {
values.push($(v).val());
});
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="package_ids[]" name="package_ids[]" value="6" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="775" />
<input type="hidden" class="package_ids[]" name="package_ids[]" value="7207" />

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>

Get the values for all the input hidden in the html with jQuery

I want to get a list with the values for all of the input hidden that I have in my HTML. All of these inputs hidden ids will end with the string LevelName. This is an example of the inputs (they don't have to appear one after another):
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
I have tried this:
console.log($( this ).find("input:hidden[id$='LevelName']"));
And on the console I get:
[object Object]{0: HTMLInputElement {...}, 1: HTMLInputElement {...}, 2: HTMLInputElement {...}, context: HTMLDocument {...}, jquery: "2.1.1", length: 3, prevObject: Object {...}, selector: "input:hidde..."}
I have also tried:
console.log($( this ).find("input:hidden[id$='LevelName']").val());
But I get:
nivel_1
I think I'm on the right way but I don't know how to get all the values from the result of find.
How can I get all the values in one string separared by commas?
var allvalues = $("input:hidden[id$='LevelName']").map(function() {
return $(this).val()
}).get()
console.log(allvalues)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
Loop all the inputs.
use .map() to get the input values and put it in array
Your problem is that you are not looping throught the collection of inputs, you are just returning the value of the first one.
You need to use $("input[id$='LevelName'][type='hidden']") to get all the hidden inputs and then use .each()method to loop over them to take their values:
Demo:
$("input[id$='LevelName'][type='hidden']").each(function() {
console.log($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
You can simply loop through all elements and then get the value.
$("input:hidden[id$='LevelName']").each(function() {
console.log($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
You need to loop the element .so Try with each()
$("input:hidden[id$='LevelName']").each(function(){
console.log($( this ).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
The issue is because when you call val() on a jQuery object holding a collection of elements it will only return the value of the first one in the set.
If you want to build a list of the values you can create an array of them using map(), like this:
var values = $("input:hidden[id$='LevelName']").map(function() {
return this.value;
}).get();
console.log(values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />
Loop the input fields.
$("input").each(function() {
console.log($(this).attr('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="VariableDataList_0__LevelName" name="VariableDataList[0].LevelName" type="hidden" value="nivel_1" />
<input id="VariableDataList_1__LevelName" name="VariableDataList[1].LevelName" type="hidden" value="nivel_2" />
<input id="VariableDataList_2__LevelName" name="VariableDataList[2].LevelName" type="hidden" value="nivel_3" />

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);
});

Categories

Resources