Am i using document.getelementsbyclassname wrong? - javascript

When I enter the value of the textbox has to be "" and the color has to be red. I have to use the same function for three textboxes. When I use document.getelementsbyclassname() my function won't work. Am I doing something wrong?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<link rel="stylesheet" href="styleDOMoef01.css" type="text/css"/>
<title>DOMoef01</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function roodVerdwijn(){
document.getElementsByClassName('text1').value="";
document.getElementsByClassName('text1').style.color = "Red";
document.getElementsByClassName('text1').style.background = "White";
}
function gedaan(){
document.getElementByClassName('text1').style.color = "Black";
document.getElementByClassName('text1').style.background = "Gray";
}
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">persoonlijke gegevens</td>
</tr>
<tr>
<td>voornaam</td>
<td><input type="text" value="voornaam" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" value="achternaam" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td>adres</td>
<td><input type="text" value="adres" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td><input type="button" value="verzenden" onclick="window.alert('Bedankt om het formulier te verzenden')"></td>
<td><input type="button" value="alles wissen"></td>
</tr>
</table>
</body>
</html>
I've tried to fix it with this code but it still won't work:
function roodVerdwijn(){
var elements = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements.value="";
elements.style.color = "Red";
elements.style.background = "White";
}
}
function gedaan(){
var elements2 = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements2.style.color = "Black";
elements2.style.background = "Gray";
}
}
it kinda helped, but when I focus on one textbox, the value of all 3 textboxes are "". I want to focus on only one textbox. This is what i've changed:
function roodVerdwijn(){
var elements = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements[i].value="";
elements[i].style.color = "Red";
elements[i].style.background = "White";
}
}
function gedaan(){
var elements2 = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements2[i].style.color = "Black";
elements2[i].style.background = "Gray";
}
}

Get elements by class name returns an array of element. You have to loop each element or if you are sure that there's only one element for the class you have look for, use [0].
document.getElementsByClassName('text1')[0].value ...

I fixed it :
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<link rel="stylesheet" href="styleDOMoef01.css" type="text/css"/>
<title>DOMoef01</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function roodVerdwijn(id){
var elements = document.getElementById(id);
elements.value="";
elements.style.color = "Red";
elements.style.background = "White";
}
function gedaan(id){
var elements2 = document.getElementById(id);
elements2.style.color = "Black";
elements2.style.background = "Gray";
}
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">persoonlijke gegevens</td>
</tr>
<tr>
<td>voornaam</td>
<td><input type="text" value="voornaam" id="1" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" value="achternaam" id="2" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td>adres</td>
<td><input type="text" value="adres" id="3" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td><input type="button" value="verzenden" onclick="window.alert('Bedankt om het formulier te verzenden')"></td>
<td><input type="button" value="alles wissen"></td>
</tr>
</table>
</body>
</html>

Related

remove Atrribute "hidden" from a table using DOM shows removeAttribute is not a function [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 months ago.
i'm having problems using the dom "removeattribute" when i click on a button i need that the table shows up in the HTML i'm using the next HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="form-group">
<label for="">Título</label>
<input type="text" class="form-control" name="" id="titleInput" aria-describedby="helpId"
placeholder="Título del juego">
</div>
<button id="btnIncrementar" onclick="incrementar()">Incrementar</button>
<button id="btnDecrementar">decrementar</button>
<button id="pofavo">alertas</button>
<p id="pcontador">0</p>
<p id="clickcontador">0</p>
<table class="table mt-3" hidden>
<thead>
<tr>
<th>Valores </th>
<th>Tema1</th>
<th>Tema2</th>
<th>Tema3</th>
<th>Tema4</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">100</td>
<td>Pregunta:Tema1-100</td>
<td>Pregunta:Tema2-100</td>
<td>Pregunta:Tema3-100</td>
<td>Pregunta:Tema4-100</td>
</tr>
<tr>
<td scope="row">200</td>
<td>Pregunta:Tema1-200</td>
<td>Pregunta:Tema2-200</td>
<td>Pregunta:Tema3-200</td>
<td>Pregunta:Tema4-200</td>
</tr>
<tr>
<td scope="row">300</td>
<td>Pregunta:Tema1-300</td>
<td>Pregunta:Tema2-300</td>
<td>Pregunta:Tema3-300</td>
<td>Pregunta:Tema4-300</td>
</tr>
<tr>
<td scope="row">400</td>
<td>Pregunta:Tema1-400</td>
<td>Pregunta:Tema2-400</td>
<td>Pregunta:Tema3-400</td>
<td>Pregunta:Tema4-400</td>
</tr>
</tbody>
</table>
<script src="./handler.js"></script>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("titleInput").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
with the following handler.js
"use strict";
btnDecrementar.onclick= decrementar;
btnIncrementar.addEventListener('click',contaclicks);
btnDecrementar.addEventListener('click',contaclicks);
let maintable = document.getElementsByTagName("table");
function incrementar(){
let valor = Number(pcontador.innerText);
valor=valor+1;
pcontador.innerText = valor;
}
function decrementar(){
let valor = Number(pcontador.innerText)
valor=valor-1;
pcontador.innerText = valor;
maintable.removeAttribute('hidden');
maintable=maintable;
}
function contaclicks(){
let valor = Number(clickcontador.innerText)
valor=valor+1;
clickcontador.innerText = valor;
}
titleInput.addEventListener('keyup',bten);;
function bten(){
var x = document.getElementById("titleInput");
x.value = x.value.toUpperCase();
}
i tried using getelementsbyclass and it returned se same failure "handler.js:18 Uncaught TypeError: maintable.removeAttribute is not a function"
You are using:
let maintable = document.getElementsByTagName("table");
It returns a Node List, so you should use:
let maintable = document.getElementsByTagName("table")[0];

Returning values from an HTML Table to JSON format using HTMLtoJSON

I am using the jQuery package HTMLtoJSON to convert values from an HTML table to json format. The problem I am encountering is that I am unable to grab the actual input value using any of the documented options. the json returns what should be between the "<\td>" which in this case is a key value pair example "measured depth":"" and I am looking for something like "Measured Depth":"339"
Javascript
<script language='Javascript'>
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('Table').deleteRow(i);
}
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
$('#convert-table').click(function()
{
var table = $('#Table').tableToJSON(
{
onlyColumns:[0,1,2],
textDataOverride:'text-override'
});
console.log(table);
alert(JSON.stringify(table));
});
</script>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://storage.googleapis.com/jquerytabletohtml/jquery.tabletojson.js"></script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>
<input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<h1>This is a test for Directional Surveys</h1>
<div id="tablediv">
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
</div>
<button id="convert-table">Convert!</button>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body>
</html>
You need to implement extractor function:
var table = $('#Table').tableToJSON({
onlyColumns: [0,1,2],
textDataOverride: 'text-override',
extractor: function(cellIndex, $cell) {
return $cell.find('input').val();
}
});

Why is my function not grabbing the values from a blank input box and executing the function correct?

In my program, I wrote several functions so that when you typed any number of ticket holders and complementary passes from 1 to 550, and after that, when you clicked on the button "Calculate Available Seats", it would display : "The number of available seats is " and then 555 minus the number of ticket holders and complementary passes. However, with my current code, when I finish typing into the two blank boxes with two random numbers, and then I click on the button "Calculate Available Seats", it always returns "The number of available seats is 555". I want the program to first subtract the two values of ticket holders and passes from 555(the maximum number of seats on that plane) and display that value, not just 555.
var TicketHolders = parseInt(document.getElementById("txtTickets").value) || 0;
var ComplementaryPasses = parseInt(document.getElementById("txtPasses").value) || 0;
function number_of_available_seats(TicketHolders, ComplementaryPasses) {
var answer = 555 - (TicketHolders + ComplementaryPasses);
return("The number of available seats is " + answer);
}
var button = document.getElementById("btnSubmit");
function showresults(TicketHolders, ComplementaryPasses) {
document.getElementById("results").innerHTML = number_of_available_seats(TicketHolders, ComplementaryPasses);
}
function clickonbutton(){
showresults(TicketHolders, ComplementaryPasses);
}
button.onclick = function() {
clickonbutton();
};
<!-- airbus.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Airbus Seat Calculator</title>
<style>
DIV.movable { position:absolute;}
</style>
</head>
<body>
<h2>Airbus Seat Calculator</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtTickets">Ticket Holders<span class="inputs"></span></label></td>
<td><input type="text" id="txtTickets" name="tickets"></td>
</tr>
<tr>
<td><label for="txtPasses">Complementary Passes<span class="inputs"></span></label></td>
<td><input type="text" id="txtPasses" name="passes"></td>
</tr>
<tr>
<td> </td>
<td>
<input type="button" value="Calculate Available Seats" id="btnSubmit"></td>
</tr>
</table>
</form>
<div id="results">
</div>
<h2>Your Copyright Info Goes Here</h2>
<script src="airbus.js">
</script>
</body>
</html>
You have:
var TicketHolders = parseInt(document.getElementById("txtTickets").value) || 0;
var ComplementaryPasses = parseInt(document.getElementById("txtPasses").value) || 0;
at the top of your script. It's only called once, so it's only calculated once (On the page load). Simply moving it down into the clickonbutton function, you will get the values when the button is clicked:
function number_of_available_seats(TicketHolders, ComplementaryPasses) {
var answer = 555 - (TicketHolders + ComplementaryPasses);
return("The number of available seats is " + answer);
}
var button = document.getElementById("btnSubmit");
function showresults(TicketHolders, ComplementaryPasses) {
document.getElementById("results").innerHTML = number_of_available_seats(TicketHolders, ComplementaryPasses);
}
function clickonbutton(){
var TicketHolders = parseInt(document.getElementById("txtTickets").value) || 0;
var ComplementaryPasses = parseInt(document.getElementById("txtPasses").value) || 0;
showresults(TicketHolders, ComplementaryPasses);
}
button.onclick = function() {
clickonbutton();
};
<!-- airbus.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Airbus Seat Calculator</title>
<style>
DIV.movable { position:absolute;}
</style>
</head>
<body>
<h2>Airbus Seat Calculator</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtTickets">Ticket Holders<span class="inputs"></span></label></td>
<td><input type="text" id="txtTickets" name="tickets"></td>
</tr>
<tr>
<td><label for="txtPasses">Complementary Passes<span class="inputs"></span></label></td>
<td><input type="text" id="txtPasses" name="passes"></td>
</tr>
<tr>
<td> </td>
<td>
<input type="button" value="Calculate Available Seats" id="btnSubmit"></td>
</tr>
</table>
</form>
<div id="results">
</div>
<h2>Your Copyright Info Goes Here</h2>
</script>
</body>
</html>

Javascript calculation not working for second text field

I found some code on JSBin (http://jsbin.com/lejoxesari/1/edit?html,js,output) which works like a treat, until I try and adapt it to do more! Now I seem to have an error where it won't calculate the second field.
My edited code can be seen below;
<!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com
Copyright (c) 2015 by anonymous (http://jsbin.com/fivesocaku/1/edit)
Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<table width="80%" border="0">
<tr>
<th>Qty</th>
<th>1.2m</th>
<th></th>
<th>1.8</th>
<th></th>
</tr>
<tr>
<td><input id="qty" type="text" oninput="calculate()" /></td>
<td><input id="R12" type="text" oninput="calculate()" /></td>
<td><input id="b12" type="hidden" value="5" oninput="calculate()" /></td>
<td><input id="R18" type="text" oninput="calculate()" /></td>
<td><input id="B18" type="hidden" value="2" oninput="calculate()" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<script id="jsbin-javascript">
function calculate() {
var myBox1 = document.getElementById('qty').value;
var myBox2 = document.getElementById('b12').value;
var result = document.getElementById('R12');
var myResult = myBox1 * myBox2;
result.value = myResult;
var myBox4 = document.getElementById('b18').value;
var result18 = document.getElementById('R18');
var myResult18 = myBox1 * myBox4;
result.value = myResult;
}
</script>
</body>
</html>
I don't seem to be getting any errors reported, but was wondering if someone could take a look and let me know where my error is.
Thanks!
var myBox4 = document.getElementById('b18').value;
b18 must be UPPERCASE
var myBox4 = document.getElementById('B18').value;
you try to get the element by id b18 instead of B18.
Also, you are assigning the value again to result (overriding it), instead to result18.
If I could offer my 2 cents, use more meaningful names for variables, and have some pattern for it (same casing, with/withour numbers etc)
var myBox4 = document.getElementById('b18').value;
You are getting an element id which doesn't exist
var result18 = document.getElementById('R18');
var myResult18 = myBox1 * myBox4;
result.value = myResult;
The last assignment should be result18.value = myResult you are assignig to the same textbox twice.

deleting the table after rows are deleted

I m trying to delete the table after all the rows deleted but somehow i cant check if table has children after deleting all the rows.
I dont understand why looking for the child elements length doesnt work here ? any suggestions ?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>table manipulation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<script src="..//jquery-2.1.3.min.js"></script>
<script src="table.js" type="text/javascript"></script>
</head>
<body>
<table id = "table1">
<tr id = "1">
<td id = "information1"> i m the first row !</td>
<td><button id = "button1" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "2">
<td id = "information2"> i m the second row !</td>
<td><button id = "button2" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "3">
<td id = "information3" > i m the third row !</td>
<td><button id = "button3" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
<tr id = "4">
<td id = "information4" > i m the fourth row !</td>
<td><button id = "button4" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
</table>
<div id = "newtable"> </div>
</body>
</html>
var id ;
var table = $('<table></table>').addClass('foo');
function destroy(){
var theParent = document.querySelector("#table1");
var parent = $("#" + id).parent();
$("#" + id).fadeOut( "slow", function() {
$(parent).closest('tr').remove();
alert(theParent.innerHTML);
});
var row = $('<tr</tr>').addClass('bar').text(parent.siblings().html());
table.append(row);
$("#newtable").append(table);
parent.siblings().remove();
theParent.addEventListener("click", doSomething, false);
}
function doSomething(e) {
if($("#table1").children().length < 1 ){
theParent.remove();
}
}
function reply_click(clicked_id)
{
id = clicked_id;
destroy();
}
function doSomething(e) {
if($("#table1 tr").length <= 1 ){
theParent.remove();
}
}
This will help you
You can try this instead:
if($("#table1").find('tr').length < 1 ){
theParent.remove();
}
Browsers will usually add <tbody> and<thead> tags into a table even if they aren't in your HTML, so the rows aren't the only children. The code above just looks for rows.

Categories