trying to get values from a HTML form? - javascript

I have a HTML form where i dynamically create elements and set its name , value attributes .
when i tried to access the value say document .formname.nameoftheelement.value then i get the error that value is undefined.
Then i tried to use the following function to access the values .it returns the input elements as 4 but value as null when i it already has predefined value .
function returnTheStoredValues(getTableName) {
//Array arrList = new Array(20);
var tableName = document.getElementById (getTableName);
console.log("The table name" + tableName);
if (tableName) {
var inputs = tableName.getElementsByTagName ('td');
console.log("the inputs are " + inputs.length);
if (inputs) {
console.log("inputs not equal to null")
for (var i = 0; i < inputs.length; ++i) {
console.log("the value in phones table are " + inputs[i].value);
//arrList[i] = inputs[i].value;
}
}
}
//return arrList;
}
The html code is
Phone
<table id="email_table">
<tr>
<td><h3>Email</h3></td>
<td><input value="+" type="submit" onClick="checkTheEmailButtonClicked()"></td>
</tr>
</table>
<table>
<tbody>
<tr>
<td><input type="submit" value ="Save" onclick="getData();"/></td>
<td><input type="submit" value = "Cancel"/></td>
</tr>
</tbody>
</table>
Appreciate all your help .

You seem to want the values of the input elements, so:
function returnTheStoredValues(getTableName) {
var arrList = [];
var table = document.getElementById(getTableName);
var inputs = table.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
arrList[i] = inputs[i].value;
}
return arrList;
}

Because you're getting the TD's and not the INPUT's?
var inputs = tableName.getElementsByTagName('td');
Should be
var inputs = tableName.getElementsByTagName('input');
By the way, if you use a Javascript framework, your code will be happier.

You really need to look into using jQuery for accessing elements through JavaScript.
You could then re-write your function to the following:
function returnTheStoredValues(getTableName) {
return $("#email_table input").map(function() {
return $(this).val();
}).get();
}

Related

Remove first duplicate from an array of objects in JavaScript

On input change I create an array of objects. When any value enter within the input field, it pushes objects into array but the problem is when a text field is updated, it does again push items into array. I need to update the array instead of pushing more items.
var tableData = [];
$('.aantalNumber').change(function(){
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking =$(this).closest('tr').find('.verpakking').text();
tableData.push({aantalNumber:aantalNumberVal,Productnummer:Productnummer,Productnaam:Productnaam,verpakking:verpakking });
console.log(tableData);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal1"></td>
<td class="product_number">01454</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal2"></td>
<td class="product_number">218031</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<!-- Repeated tr and so on -->
First check if value exist, if available then update else push into tableData
var tableData = [];
$('.aantalNumber').change(function() {
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking = $(this).closest('tr').find('.verpakking').text();
if (tableData.some(tableData => tableData.Productnummer === Productnummer)) {
updateTableData(Productnummer, aantalNumberVal);
} else {
tableData.push({
aantalNumber: aantalNumberVal,
Productnummer: Productnummer,
Productnaam: Productnaam,
verpakking: verpakking
});
}
console.log(tableData);
});
function updateTableData(value, aantalNumber) {
for (var i in tableData) {
if (tableData[i].Productnummer == value) {
tableData[i].aantalNumber = aantalNumber;
break; //Stop this loop, we found it!
}
}
}
Working Demo

Get data from input using template literals as id

I have a program that makes a table using json data. This technique uses template liretals, so i can add rows myself however i want. My problem is that I need to get data from an input, which has a template literal as an id, but the getElementById doesn't allow me to.
I have already tried escaping my brackets, but that doesn't work. I have looked into using a simple index, but i don't know how I could set it up in my function.
Here is the javascript code:
//load JSON file
var articles = ""
var txt = ""
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
articles = xmlhttp.responseText;
txt = JSON.parse(articles);
processArticles(txt);
processForm(txt);
}
};
xmlhttp.open("GET","../articles.json",true);
xmlhttp.send();
function processArticles(txt) {
var tableStart = `
<h2>Liste des articles</h2>
<form id="formtable">
<table>
<tr>
<th>ID</th>
<th>Article</th>
<th>Prix</th>
<th>Prix-Retour</th>
<th>Quantitée maximale</th>
<th>Projet</th>
<th>Quantitée</th>
</tr>`;
var tableEnd = `
</table>
<input type="submit">
</form>`;
function articlesTemplate(txt, index) {
return `
<tr>
<td>${txt.ID}</td>
<td>${txt.Article }</td>
<td>${txt.Prix}</td>
<td>${txt.PrixRetour}</td>
<td>${txt.QuantiteeMaximale}</td>
<td>${txt.Projet}</td>
<td><input type="number" name="quantity${txt.ID}" id="quantity${txt.ID}" min="1" max="5"></td>
</tr>
`;
}
let mctxt=txt.filter(value=>
value.Projet=="mc");
document.getElementById("tablemc").innerHTML = `
${tableStart}
${mctxt.map(articlesTemplate).join("")}
${tableEnd}
`;
;
}
The problem is in the .getElementById of my quantity in this last function.
function processForm(txt) {
var form = document.getElementById('formtable');
var quantity = document.getElementById(`"quantity$\\{txt.ID\\}"`);
form.onsubmit = function(e) {
e.preventDefault();
console.log("HI");
console.log(quantity.value);
};
}
I want to be able to collect the quantity of each object selected and also the price of that same object, so that i can make a total price at the end of the table.
I think you accidentally did bad quoting like #DontVoteMeDown already mentioned.
Lets assume
txt.ID = 2
then the template string
`<input ... id="quantity${txt.ID}" />`
will result in
<input ... id="quantity2" />
as well as the selector's template string
document.getElementById(`quantity${txt.ID}`);
will result in
document.getElementById("quantity2");
So it should work in general.
If you want to sum all input values of the resulting table, you have to select all inputs and iterate over the values.
var total = 0;
document.querySelectorAll('#formtable input').forEach(function(input) {
total += parseInt(input.value);
})

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")%>

When using DOM within a loop: Uncaught TypeError: Cannot read property 'checked' of null error

Hi im having trouble with a bit of code checking if any of the radio buttons are checked
im getting this result:
Uncaught TypeError: Cannot read property 'checked' of null
when I run it
the code that is relevant to this is:
function validateForm() {
var msg="";
var LoE="";
...some code
for (var i=0; i<3; i++) {
if ((document.getElementById('"LoE" + i').checked)){
LoE="";
break;
}
Else
{
result = false;
msg+="You need to chose your level of entry";
}
}
...some more code
}
and the radio buttons that are being checked. They are within a form by the name of ExamEntry
<tr>
<td><input type = "radio" name = "LevelOfEntry" id = "LoE0" value = "GCSE">GCSE</td>
</tr>
<tr>
<td><input type = "radio" name = "LevelOfEntry" id = "LoE1" value = "AS">AS</td>
</tr>
<tr>
<td><input type = "radio" name = "LevelOfEntry" id = "LoE2" value = "A2">A2</td>
</tr>
thanks for the help.
EDIT
removed the single quote marks as suggested in the comments and replaced with:
if ((document.getElementById("LoE" + i).checked)){
now only getting error that else is unspecified in this part of the code:
Else
{
result = false;
msg+="You need to chose your level of entry";
}
}
EDIT:
resolved. Thanks a lot everyone
Just as a note and I'm not 100% sure what you're trying to do, but you are limiting yourself in terms of specifying the amount of radio buttons and using the ID instead of the name.
Making use of Jquery makes working with radio buttons a lot easier (just saying), alternatively this is a more robust way in terms of this post:
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_radio_value();
alert("selected input is: " + id);
}
See this link: getting selected value of radio button in case of action

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