Storing values from HTML Collection in array? - javascript

I'm new to all this and I really need help. I've been on this for hours now.
I have these checkboxes. I'm using a cfoutput to generate them and giving them each the value of SID from the query.
<cfoutput query="getvalues">
<div><input type="checkbox" name="chk" id=#getvalues.SID# value=#getvalues.SID# class="chkbxs">
</cfoutput>
<input type="button" name="PrintSelected" value="Print Selected" onclick="printTextArea()">
The only thing I want to do is get the values of these checkboxes and store them in an array. getElementsByClassName returns an html collection. I've been told I need to loop over the html collection and then store the values in a new array which is what I attempted below but this isn't working.
<script type="text/javascript">
function printTextArea() {
var myList = document.getElementsByClassName("chkbxs");
var newList = [];
for (var i = 0; i < myList.length; i++) {
newList.push(myList[i].value);
}
for (var j = 0; j < newList.length j++)
{
alert (newList[j]);
}
}
</script>
Any help would be appreciated.

Why are you setting the array items to console.log(myList[i].value);?
console.log() just returns undefined.
Just change the line to following:
newList[i] = myList[i].value;

Related

how to store dynamically created checked checkbox in array?

I am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>

Why can't get input value checkbox in array?

In the code described below, the value of the input should be taken from everyone in the array and a new div with the input value in innerHtml should be created. I don't know why get an error that length.value not defined?
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsone">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divstwo">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsthree">
<button onclick="myFunction()">Click me</button>
<div id="container"></div>
function myFunction() {
let array = [];
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');
for (var i = 0; i < checkboxnewdivs.length; i++) {
var iddivs = array.push(checkboxnewdivs[i].value);
var div_new = document.createElement("DIV");
div_new.innerHTML = "ID div:"+iddivs ;
document.getElementById("container").appendChild(div_new);
}
}
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked').value;
Should be
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');
The first one is trying to get a value property from a node collection, which will obviously be undefined.
You also had some typos (double 's') and don't define array anywhere. Define that where you defined checkboxnewdivs.
Working demo: https://jsfiddle.net/mitya33/m9L2dvz5/1/

Loop data fetched from val()

I am trying to get some data from a hidden element and loop through it and have it in an array.
The element looks like this:
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any""}]'>
Now when I grab this with jquery:
$(document).ready(function () {
var data = $(".test").val();
console.log(data);
//test loop
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
But it loops through every character instead of each {} in [].
What am I missing?
JS Bin for reference: https://jsbin.com/madaquyepa/edit?html,js,console,output
When you retrieve the input element's value, it is a string (a JSON actually). So, you will need to pass it through JSON.parse() first.
Note: there is an extraneous " near the very end of the string, which will cause an error if you try to parse it. Remember to fix it first.
$(document).ready(function() {
var data = JSON.parse($(".test").val());
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>
For an ES6 version that doesn't even use jQuery:
const data = JSON.parse(document.querySelector('.test').value);
console.log(data);
for (let datum of data) {
console.log(datum);
}
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>

How to pass an array created in javascript to another jsp and then use that array in a java function on that jsp?

Here is a script i have and I want to be able to pass the array "playernames" into a java function on another .jsp. I'm wonder how to pass that array to another page and then retrieve it for my java function.
<script>
function getPlayerNames() {
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
}
</script>
Edit:
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<input type="hidden" id="players" />
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").values=playernames;
document.getElementById("players").submit();
window.location.replace("lineups.jsp");
}</script>
Other jsp
<%String[] players = request.getParameterValues("players");%>
You'll need to have the hidden field inside the form tags with the id and action attributes set as below.
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<form id="playerNames" action="Url"> // In action give the Url of the jsp page you want to send the values to lineups.jsp in your case I guess.
<input type="hidden" id="players" name="players" />
</form>
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").value=playernames;
document.getElementById("playerNames").submit();
}</script>
1) Stringify the array and then assign to hidden field.
Refer: Javascript Hidden Input Array
2) Submit the hidden field in a form to server.
<input type="hidden" id="hiddenArrayField"/>
document.getElementById("hiddenArrayField").value=yourStringifyArrayValue;
3) On server you would get this as a part of request i.e. on next jsp you can retrieve this value as a request parameter.
<%= request.getParameter("hiddenArrayField")%>

Replacing a sub-string in JavaScript innerHTML

I have an HTML page which contains table rows like
<tr id="tp1">
<input type="checkbox" id="tc_">
</tr>
<tr id="tp2">
<input type="checkbox" id="tc_">
</tr>
The page contains input elements other than checkboxes as well
I have to change the values of all checkbox's id from tc_ to tc_1 ,tc_2 and so on.
I have thought of doing it as below
function startup(){
for(var i=0;i<3;i++)
{
var elem=document.getElementById("tp"+i);
var str=elem.innerHTML;
str.replace(/tc_,'tc_'+i); // how do I correctly use the arguments here?
elem.innerHTML=str;
//alert (""+str);
}
}
Thanks.
It isn't valid to have non-unique IDs in the first place. Any chance you can fix how the checkboxes are rendered so you don't have to do this?
That being said, I wouldn't do this by manipulating the HTML attributes. I would instead do this by manipulating the DOM properties of those input checkboxes:
// keep track of the current "new" checkbox ID suffix
var checkBoxIndex = 0;
for (var i = 0; i < 3; i++) {
// find the table row
var elem = document.getElementById("tp" + i);
// get the input elements within that row
var inputs = elem.getElementsByTagName("input");
// for each of the input elements...
for (var j = 0, k = inputs.length; j < k; j++) {
// if it's not a checkbox, skip it
if (inputs[j].type.toLowerCase() !== 'checkbox') {
continue;
}
// Alas, give the checkbox a new, unique ID
inputs[j].id = "tc_" + (checkBoxIndex++);
}
}
Also, hopefully you get an answer for your other question. This is a terrible workaround and I would hate to see it in production code.
The trick here is to select all the input elements of your rows using the appropriate CSS selector, then modify their ids:
function startup() {
for (var i = 0; i < 3;i++) {
var elem = document.getElementById("tp" + i);
var l = elem.querySelectorAll('td > input'); // Select "input"s in "td"s
Array.prototype.forEach.call(l, function (e, j) { // Apply to each element obtained
e.id = 'tc_' + j; // Modify the id
});
}
}
There's several good answers above but if you still want to change the id from tc_ to tc_ + i then you can do it like this.
<body>
<button id="tc_">1</button>
<button id="tc_">2</button>
<button id="tc_">3</button>
<script type="text/javascript">
for(var i=0;i<3;i++)
{
document.getElementById("tc_").id="tc_"+i;
}
</script>
</body>
Honestly though you shouldn't be doing it like this despite the fact this code works as other users have said it isn't valid to have non-unique id's.

Categories