Cannot read property 'value' of null at addname - javascript

I am trying to create four inputs and display all of them after clicking the button. However it returns null. What's wrong with my code?
function addname() {
for (count = 0; count < 5; count++) {
var x = " ";
var inputID = "clientname" + (count + 1);
x = document.getElementById(inputID).value
}
var f = "";
for (var count = 0; count < 5; count++) {
f += x[count];
}
document.write(f)
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()"></button>

Immediate fix: There are 4 inputs, not 5, and stop x from being abused:
function addname() {
var names = [];
for (count = 0; count < 4; count++) {
var inputId = " clientname" + (count + 1);
var name = document.getElementById( inputId ).value;
names.push( name );
}
var f = "";
for (var count = 0; count < 5; count++) {
f += names[count];
}
document.getElementById( 'output' ).textContent = f; // Never use `document.write`!
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()">Concatenate names</button>
<span id="output"></span>
Revision 2: Simplified: Using querySelectorAll with a substring attribute match, and join to concatenate strings:
function concatenateNames() {
const inputs = document.querySelectorAll( 'input[type=text][id^="clientname"]' );
const names = []; // `const` means the variable cannot be reassigned, not that it's immutable.
for( let i = 0; i < inputs.length; i++ )
{
names.push( inputs[i].value );
}
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 3: Simplified further, using Array.from so we can use map with NodeListOf<T>, and adding filter to exclude empty values:
function concatenateNames() {
const inputs = Array.from( document.querySelectorAll( 'input[type=text][id^="clientname"]' ) );
const names = inputs.map( inputEl => inputEl.value ).filter( n => n.length > 0 );
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 4: Simplified further, inlining intermediate variables only used once:
function concatenateNames() {
document.getElementById( 'output' ).textContent =
Array.from(
document.querySelectorAll( 'input[type=text][id^="clientname"]' )
)
.map( inputEl => inputEl.value )
.filter( n => n.length > 0 )
.join( " " );
}
Revision 5: Using nextElementSibling and an inline onclick handler in a single line and shortening identifiers:
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="this.nextElementSibling.textContent = Array.from( document.querySelectorAll('input[type=text][id^=clientname]') ).map(i => i.value).filter(n => n.length > 0).join(' ')">Concatenate names</button>
<span id="output"></span>
Never do this in production code.
JSFiddle demo: https://jsfiddle.net/3md65awo/

Javascript stops running at the error upon count = 4 trying to get element by id "clientname5"
Either add another text input or change loop to "count = 0; count < 4; count++"

Try this code. I used jquery for this.
function addname() {
for (var count = 1; count < 5; count++) {
var x;
x = $("#clientname" +count).val()
console.log(x)
$("#test").append(x)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="inp" id="clientname1" />
<input type="text" name="inp" id="clientname2" />
<input type="text" name="inp" id="clientname3" />
<input type="text" name="inp" id="clientname4" />
<label id = "test"></label>
<input type="button" onclick="addname()" value="click" />

Related

adding new value to variable

I have a question I have simple JavaScript that do some basic stuff to a number from input. I have a question how can I make variable that will always track the new input value for example if I enter 123 and click on some of the following buttons I get the result, but if I now enter new number for example 54321 and click again on some of the buttons I start from the previous value. How can I make my variable change every time a new value is entered or changed ? Here is my code:
var number = document.getElementById("number");
var numberValue = number.value;
console.log(numberValue);
function plus() {
number.value = ++numberValue;
}
function minus() {
number.value = --numberValue;
}
function flip() {
var temp = numberValue;
var cifra, prevrten = 0;
while (temp > 0) {
cifra = temp % 10;
prevrten = (prevrten * 10) + cifra;
temp = temp / 10 | 0;
}
number.value = prevrten;
}
window.onload = function() {
number.value = "";
}
<div>
<input type="text" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
I suggest you use a type="number" and case the value to number - her I use the unary plus to do so
You will need to read the value in all functions
let numberValue = 0;
function store() {}
function check() {}
function plus() {
numberValue = +number.value;
number.value = ++numberValue;
}
function minus() {
numberValue = +number.value;
number.value = --numberValue;
}
function flip() {
let numberValue = +number.value;
var cifra, prevrten = 0;
while (numberValue > 0) {
cifra = numberValue % 10;
prevrten = (prevrten * 10) + cifra;
numberValue = numberValue / 10 | 0;
}
number.value = prevrten;
}
window.addEventListener("load", function() {
let number = document.getElementById("number");
number.value = 0;
})
<div>
<input type="number" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
Try using onChange="".
<input type="text" id="number" id="output" onload="restart();" onChange="updateVal();">
function updateVal() {
numberValue = number.value;
}
I would suggest, for something like this, it would be much easier to use React JS or another framework with state.

trying to link checkbox list with multiple functions using HTML & JAVASCRIPT

my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.
if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.
I have checked both function calculateAVG() & calculateMAX() and they produce correct output
function proccesFloat(flt) {
var splitFloat = flt.split(",");
for (x in splitFloat) {
splitFloat[x] = parseFloat(splitFloat[x]);
}
return splitFloat;
}
function calculateAVG(setNum) {
let total = 0;
var numInput = document.getElementById("setNum").value;
var result = 0;
var avg = proccesFloat(numInput);
for (let i = 0; i < avg.length; i++) {
total += avg[i];
}
result = total / avg.length;
document.getElementById('outputAVG').innerHTML = result;
}
function calculateMAX(setNum) {
var numInput = document.getElementById("setNum").value;
var numarry = proccesFloat(numInput);
var max = 0;
for (let i = 0; i < numarry.length; i++) {
if (numarry[i] > max) {
max = numarry[i];
}
}
document.getElementById('outputMAX').innerHTML = max;
}
function calculate() {
var checkBox = document.getElementsByTagName("check");
if (checkBox[0].checked) {
calculateAVG(document.getElementById("setNum"));
}
if (checkBox[0].checked) {
calculateMAX(document.getElementById("setNum"));
} {
alert('please choose formula')
return false;
}
}
<header>
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button onclick="calculate()" id="btn1">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<form method="post">
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
<input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
<br>
</fieldset>
</form>
</header>
Count the checked and then look at the IDs.
I also suggest you wrap in a form and use the submit event
I made a few more changes to simplify the code
Let the functions do one thing and use the event to bring them together
const proccesFloat = flt => flt.split(",").map(fl => +fl); // cast to float
const calculateAVG = setNum => {
const arr = proccesFloat(setNum);
const total = arr.reduce((a, b) => a + b)
return total / arr.length;
}
const calculateMAX = setNum => Math.max(...proccesFloat(setNum));
document.getElementById("calcForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const chks = document.querySelectorAll("[name=check]:checked")
if (chks.length === 0) {
alert('please choose formula')
return
}
if (document.getElementById("avg").checked) {
document.getElementById('outputAVG').innerHTML = calculateAVG(document.getElementById("setNum").value);
}
if (document.getElementById("max").checked) {
document.getElementById('outputMAX').innerHTML = calculateMAX(document.getElementById("setNum").value);
}
})
<header>
<form id="calcForm">
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button type="submit">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check">AVG<br>
<input type="checkbox" id="max" name="check">MAX<br>
<br>
</fieldset>
</form>
</header>

Get value from multiple input and search Array match (With AND e OR)

In the function onclilck, I have to get the value from each input and search with that value, a match in my array and then report in DIV "result". The problem is that I have to do it with a logical AND search, so using ALL the values ​​together if present. I can not do it, can someone help me? I have to use only javascript or jQuery- NO PHP. Thank you.`
$("#search").click(function(){
var pharmacies = [];
pharmacies[0] = ["Vaccaro", "Bagheria", "90011"];
pharmacies[1] = ["Greco", "Bagheria", "90011"];
pharmacies[2] = ["Timoneri", "Bagheria", "90011"];
var names = [];
var elem = document.getElementsByClassName("campi");
for (var i = 0; i < elem.length; ++i) {
if (elem[i].value !== "") {
names.push(elem[i].value);
}
}
});
HTML:
<input class="campi" id="nome" type="text" name="name">
<input class="campi" id="indirizzo" type="text" name="address">
<input class="campi" id="città" type="text" name="city">
<input class="campi" id="cap" type="text" name="zip">
<button id="search" type="submit">Cerca</button>
<div id="result"></div>
you can do this:
Copy the pharmacies array to a temp array.
Get all <input> element.
Search among <input> elements for given value.
Delete array element, if given value not found.
Remove undefined values from Temp array.
Print the temp array.
Result:
var pharmacies = [
[ 'Vaccaro', '', 'Bagheria', '90011' ],
[ 'Greco', '', 'Bagheria', '90011' ],
[ 'Timoneri', '', 'Bagheria', '90011' ]
];
function search() {
var tempArr = pharmacies.slice( 0 ),
elem = document.getElementsByClassName( 'campi' );
for ( let i = 0; i < elem.length; ++i ) {
var value = elem[ i ].value
if ( value ) {
for ( var j = 0; j < tempArr.length; ++j ) {
if ( tempArr[ j ] != undefined ) {
if ( tempArr[ j ].indexOf( value ) == -1 ) delete tempArr[ j ]
}
}
}
}
tempArr = tempArr.filter( Boolean );
printResult( tempArr )
}
function printResult( arr ) {
if ( arr.length ) {
var result = '<table><tr><th>#</th><th>Nome</th><th>Indirizzo</th><th>Città</th><th>Cap</th></tr>';
for ( var x in arr ) {
result += '<tr><td>' + (+x + 1) + '</td>'
for ( var y in arr[ x ] ) {
result += '<td>' + arr[ x ][ y ] + '</td>'
}
result += '</tr>'
}
result += '</table>'
} else {
result = 'No data found'
}
document.getElementById( 'result' ).innerHTML = result
}
input {
margin: 5px
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%
}
td, th {
border: 1px solid #ccc;
text-align: left;
padding: 8px
}
tr:nth-child(even) {
background-color: #ddd
}
<input class="campi" id="nome" type="text" name="name" placeholder="nome">
<input class="campi" id="indirizzo" type="text" name="address" placeholder="indirizzo">
<input class="campi" id="città" type="text" name="city" value="Bagheria" placeholder="città">
<input class="campi" id="cap" type="text" name="zip" placeholder="cap"><br>
<button id="search" type="submit" onclick="search()">Cerca</button><br><br>
<div id="result"></div>

Button isn't working at all

I am making a program that has an array of numbers and then the user inputs some values in and clicks on verify. the value he enters has to be in order with the array of numbers and if it isn't the user gets an alert message sorry.
The value inside the first input bar decides from which number of the array should the comparison should start. For example, if the array holds numbers like {2,4,6,8,10} and the user enters 6 in the first input bar and then he enters 8 and 10 in the next two bars, he should get the result "678"
If he doesn't get the first number right lets say he enters 3, and since 3 isn't in the array, then it doesn't matter what he enters in the other input bars, he would get the result "Sorry".
Similarly, if the user types 4 in the first input bar but then then in the second bar he types 8, he should still get the result "Sorry" since the order of the array is {4,6,8} not {4,8}.
I made a program but whenever I click on the verify button, nothing happens.
Here is my codes. and here is also the result I am getting:
https://jsfiddle.net/53j19rpt/
<html>
<head>
</head>
<script type="text/javascript">
var arr = [];
var t;
var num = 2;
var x = [];
for (var x = 0; x < 4; x++) {
document.getElementById("one" + x);
}
function go() {
for (var t = 0; t < 4; k++) {
x[t] = num * (t + 1);
}
for (var k = 0; k < 4; k++) {
if (document.getElementById("one0").value >= x[k])
if (document.getElementById("one" + k).value == x[k])
document.write(document.getElementById("one" + k).value);
else
document.write("Sorry");
}
}
</script>
<body>
<input id="one0" type="text">
<input id="one1" type="text">
<input id="one2" type="text">
<input id="one3" type="text">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
</body>
</html>
Version 1 - all 4 have to be correct in order
var x = [],num=2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = num * (i + 1);
}
console.log(x);
function go() {
var found=0;
for (var i = 0; i < 4; i++) {
if (document.getElementById("one" + i).value == x[i]) {
found++;
}
}
document.getElementById("result").innerHTML = found==x.length?x:"Sorry";
}
<input id="one0" type="text" value="" />
<input id="one1" type="text" value="" />
<input id="one2" type="text" value="" />
<input id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" />
<span id="result"></span>
Version 2 Error if anything entered is wrong
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = "";
for (var i = 0; i < field.length; i++) {
res += field[i].value; // string concatenation
}
document.getElementById("result").innerHTML = (res == x.join("")) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
Version 3 - any 1, 2, 3 or 4 entries are deemed correct if they are subpart of array, e.g. 46 is ok and so is 68 but not 26
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = [];
for (var i = 0; i < field.length; i++) {
if (x.indexOf(field[i].value) !=-1) res.push(field[i].value);
}
document.getElementById("result").innerHTML = (x.join(".").indexOf(res.join("."))!=-1) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
If I understand your question well this should work:
<html>
<head>
</head>
<body>
<input id="one0" type="text" value="">
<input id="one1" type="text" value="">
<input id="one2" type="text" value="">
<input id="one3" type="text" value="">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
<script type="text/javascript">
function go() {
var arrinputs = [];
var arr = [2, 4, 10, 12];
for (var x = 0; x < 4; x++) {
var tmp = parseInt(document.getElementById("one" + x).value)
if (!isNaN(tmp))
arrinputs.push(tmp);
}
var a = "-" + arrinputs.join('-') + "-";
var b = "-" + arr.join('-') + "-";
if (b.indexOf(a) != -1) {
alert("Ok!");
} else {
alert("Sorry!");
}
}
</script>
</body>
</html>
Test 1 (check array 2, 4, 6, 8)
Returns: Corrent
Test 2 (check array 2, 4, 6, 8)
Returns: Corrent
Test 3 (check array 2, 4, 6, 8)
Returns: Sorry
Test 4 (check array 2, 4, 10, 12)
Returns: Corrent
Test 5 (check array 2, 4, 10, 12)
Returns: Sorry
Test 6 (check array 2, 4, 10, 12)
Returns: Sorry

addition without using "+"

Would like to be able to add with a "/" or a "," sign as well as the traditional "+" sign. Obviously the "/" sign is used for division, but I would like to change its purpose.
JavaScript
function CalculateIMSUB(form) {
var Atext = form.input_A.value;
var Btext = form.input_B.value;
var val = form.val.value;
var A = eval(Atext);
var B = eval(Btext);
if (isNaN(A)) A = 0;
if (isNaN(B)) B = 0;
var answer = A - B;
form.Answer.value = answer;
form.input_A.value = form.input_A.value.replace(/\+/g, ",");
form.input_B.value = form.input_B.value.replace(/\+/g, ",");
}
function calculateAll() {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
CalculateIMSUB(forms[i]);
}
}
HTML
<form>
<INPUT TYPE=TEXT NAME="input_A" SIZE=15 />
<INPUT TYPE=TEXT NAME="input_B" SIZE=10 />
<INPUT TYPE="button" VALUE="+" name="SubtractButton" onclick="CalculateIMSUB(this.form)"
/>
<INPUT TYPE=TEXT NAME="Answer" SIZE=12 />
<input type="hidden" name="val" value="1221" />
</form>
Here's my example
Try implementing something like this. No eval, just arrays.
function add( value ) {
return value.split(/[+,\/]/).reduce(function( a,b ) {
return +a + +b;
});
}
console.log( add('1+1+1') ); //=> 3
console.log( add('2,2,2') ); //=> 6
console.log( add('3/3/3') ); //=> 9

Categories