javascript jquery find multiple hidden input without specific attribute - javascript

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" />

Related

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

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" />

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

Convert li input values data to JSON

Hello I need to save multi values and update database using ajax.. I'm working on Yii framework..
in the first I need to send data using ajax as json but I have wrong on results.
Live code:
http://jsfiddle.net/kxJwp/2/
My javascript code is:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$('li inputs').each(function() {
values[$(this).attr('name')] = $(this).val();
});
$('li').each(function(i) {
showtimes[i]=values;
});
alert(JSON.stringify(showtimes));
});
Javascript output:
It's output last one li values x number of li
inputs:
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>
You are seeing only one row because you have only one object, whereas you need an array of objects, so declare an array first, and then keep adding the objects to it. Something like this:
$("#save").live('click', function(){
var showtimes = []; // Create empty javascript array
var objec={};
$("li").find("input").each(function(index) { // Iterate over inputs
objec=new Object; // to create a new object for every matched element
objec[$(this).attr('name')]=$(this).val()+'avla';
showtimes[index]=objec; // Add object to array
});
var json = JSON.stringify(showtimes);
alert(json);
});
Code explanation:
Use the inbuilt index of each(), by passing the index to the function like: function(index){...}.
Edit: objec=new Object; is needed to avoid getting repeated values, because each time the same object was getting added to the array, but with new, a new object is created each time and that is added to the array.
Update: A better way to select the lis would be using a selector such as : $("li:has(input)") and then cycle through the children:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$("li:has(input)").each(function(i){
values = new Object;
$(this).children().each(function(){
values[$(this).attr('name')]=$(this).val();
});
showtimes.push(values);
});
alert(JSON.stringify(showtimes));
});
Edit: The output(arrays formed) in both the above samples is different.
Output for code sample 1:
json=[{"show_id":"1avla"},{"movie_id":"2avla"},{"cinema_id":"3avla"},{"status":"4avla"},{"times":"5avla"},{"show_id":"6avla"},{"movie_id":"7avla"},{"cinema_id":"8avla"},{"status":"9avla"},{"times":"0avla"}]
Output for code sample 2:
json=[{"show_id":"1","movie_id":"2","cinema_id":"3","status":"4","times":"5"},{"show_id":"6","movie_id":"7","cinema_id":"8","status":"9","times":"0"}]
Your original js code shows
$("tr").find("input.att").each(function() {
however your view code shows you are using an <li> instead of <tr>
So shouldn't it be $("ul") or $("li")
You can use another alternate method. The changes you should made is place the the lis and input's under a form ad submit the form via ajax. Also you should change the names of the input according to this ie add square brackets so that you can retrieve it as arrays in PHP. No jSON needed
So
<form id="myform" action="action.php">
.....
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
....
</form>
and the javascript for ajax
$("#save").live('click', function(){
var form = $('#myform');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
});
then in your controller you will get the submitted data as array
print_r($_POST['show_id']);
print_r($_POST['movie_id']);
etc etc

Making "Mark all" button

How can i make a "Mark all" link that, marks all checkboxes there is inside a td:
<td style="padding-right:4px;padding:4px;" class="alternating">
<input name="cbPick" type="checkbox" value="88156144" />
</td>
Don't know what language you write this in.. JavaScript?
It would be in Javascript.
You would be using the DOM API.
function markAll() {
var tds = document.getElementsByTagName('td');
for(var index in tds) {
var innerNode = tds[index].firstChild;
if(innerNode.tagName == 'input' && innerNode.attributes.type="checkbox")
innerNode.checked = true;
}
}
You'd then need to make sure that the onClicked handler for the mark all link references this function. This code also assumes that where the tickbox is inside the TD's, it is the first child - otherwise this code would be more complicated.
Reference info:
http://www.w3schools.com/jsref/dom_obj_checkbox.asp
Code:
function checkAll(value, arr) {
$(arr).each(function () {
if (value) {
$(this).attr('checked', 'checked');
}
else {
$(this).removeAttr('checked');
}
});
}
Usage:
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
Mark all
P.S.
Yes, it requires jQuery. OMG OMG!!
Yes, that would be javascript, something like:
<script type="text/javascript">
function selectAll(x) {
for(var i=0,l=x.form.length; i<l; i++){
if(x.form[i].type == 'checkbox' && x.form[i].name != 'selectAll'){
x.form[i].checked=x.form[i].checked?false:true
}
}
}
</script>
<form>
<input type="checkbox" name="selectAll" onclick="selectAll(this)" /> (Select all)<br />
<input type="checkbox" name="a" /> (A)<br />
<input type="checkbox" name="b" /> (B)<br />
<input type="checkbox" name="c" /> (C)<br />
<input type="checkbox" name="d" /> (D)<br />
<input type="checkbox" name="e" /> (E)
</form>
Yeah javascript is the way to go
here is a link for a way to do it
http://www.shiningstar.net/articles/articles/javascript/checkboxes.asp

Categories

Resources