I have div that I can console log but cannot take value - javascript

I have one div that I pass on hidden input that I want to use inside this two functions. When I call the function
display_quality() it displays the number 1 in the console as expected.
But when in the function default_display_quality() i console.log the value of require_quality it gives me the error "Uncaught TypeError require_quality is null"
but if i console.log the variable of require_quality it shows the complete div .
What am I missing?
Here is the code:
<script>
function default_display_quality(){
let require_quality = document.getElementById("require_quality");
console.log(require_quality);
console.log(require_quality.value);
}
function display_quality(){
let require_quality = document.getElementById("require_quality");
console.log(require_quality.value);
}
let require_quality = 1;
if(require_quality == 1){
default_display_quality();
}
let show_quality= document.getElementById("show_quality");
show_quality.innerHTML= '<input type="hidden" id="require_quality" value="'+require_quality+'">'+
'<input type="checkbox" value="'+require_quality+'" onchange=" display_quality()">';
</script>
<!-- HTML-->
<div id="show_quality"></div>

Related

Why do I have to keep refreshing the page for the output of the code to change and actually follow what I intended it to do?

Apparently I posted a question couple of minutes ago saying that my code was not working because the output was always the same and didnt change even when I put different inputs, but I deleted it because I found out that the problem was that I had to refresh the whole page and answer again to get the intended output. I have to keep doing this everytime I wanted that or else the output would stay the same. Could someone help me figure out why that happens and how to fix it?
The Code:
var q1Agree = document.getElementById("q1-agree");
var q1Neutral = document.getElementById("q1-nuetral");
var q1Disagree = document.getElementById("q1-disagree");
var q2Agree = document.getElementById("q2-agree");
var q2Neutral = document.getElementById("q2-nuetral");
var q2Disagree = document.getElementById("q2-disagree");
var result = document.getElementById("result");
var pnum = 0;
function personalitycondition() {
if (q1Agree.checked) {
pnum += 2;
} else if (q1Neutral.checked) {
pnum += 1;
} else if (q1Disagree.checked) {
pnum += 0;
}
if (q2Agree.checked) {
pnum += 2;
} else if (q2Neutral.checked) {
pnum += 1;
} else if (q2Disagree.checked) {
pnum += 0;
}
if (pnum > 4) {
result.innerHTML = "You are a confident and energetic person.";
} else if (pnum >= 2) {
result.innerHTML = "You are a balanced and level-headed person.";
} else {
result.innerHTML = "You are a reserved and thoughtful person.";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form id="q1">
<h3>You are open about your feelings</h3>
<label for="agree">Agree</label>
<input type="radio" id="q1-agree" name="q1-personality" value="Agree"><br><br>
<label for="nuetral">Nuetral</label>
<input type="radio" id="q1-nuetral" name="q1-personality" value="Nuetral"><br><br>
<label for="disagree">Disagree</label>
<input type="radio" id="q1-disagree" name="q1-personality" value="Disagree"><br><br>
</form>
<form id="q2">
<h3>It is difficult to get you excited</h3>
<label for="agree">Agree</label>
<input type="radio" id="q2-agree" name="q2-personality" value="Agree"><br><br>
<label for="nuetral">Nuetral</label>
<input type="radio" id="q2-nuetral" name="q2-personality" value="Nuetral"><br><br>
<label for="disagree">Disagree</label>
<input type="radio" id="q2-disagree" name="q2-personality" value="Disagree"><br><br>
</form>
<button type="button" onclick="personalitycondition()">Find Your Personality</button>
<p id="result"></p>
</body>
</html>
Plus, I didnt really try anything because I dont know if the problem is related to the code or something outside
In short, the issue is in the JavaScript you've provided. You have defined the pnum variable globally. This means that after the function personalitycondition completes, the pnum function keeps its value, and the starting value of pnum the next time the function executes is not 0 anymore, but instead is what the function left behind itself.
A simple solution would be to put the pnum variable inside the function, so that the variable is reset every time we execute the personalitycondition function. Another solution would be to set pnum to 0 in the start of the function.

I can’t get the value from `document.getElementById`

The console says “Unable to get property 'value' of undefined or null reference”.
I tried using getElementsByName but it still doesn’t work, even the alert won’t show up.
<!doctype html>
<html>
<head>
<title>TUGAS PBW</title>
<script type="text/javascript">
function hitung() {
var hasil;
var balik;
var diskon;
var x = parseInt(document.getElementById("jumlah")[0].value);
var y = parseInt(document.getElementById("harga")[1].value);
var z = parseInt(document.getElementById("bayar")[2].value);
hasil = x * y;
if (hasil => 750000) {
diskon = hasil * 10 / 100;
hasil - diskon;
balik = z - hasil;
} else {
balik = z - hasil;
}
alert("\nTotal Kembalian =" + hasil);
}
</script>
</head>
<body>
<h1>toko buku</h1>
jumlah barang : <input type="text" id="jumlah"><br> harga barang : <input type="text" id="harga"><br> Uang yang dibayarkan : <input type="text" id="bayar"> <br>
<input type="button" id="btnHitung" value="Test" onclick="hitung();"><br><br>
</body>
</html>
getElementById returns an element, not an array of elements. Consider the semantics of even just the name of the method... it "gets" an "element" by the element's "ID" (unique identifier).
Remove the array index syntax:
var x = parseInt(document.getElementById("jumlah").value);
var y = parseInt(document.getElementById("harga").value);
var z = parseInt(document.getElementById("bayar").value);
Edit: This is also a typo:
if ( hasil => 750000)
The operator you seem to be looking for is >=:
if (hasil >= 750000)
There could be other typos in your code as well? The first place you should always look is your browser's development console. Error messages will be shown there. Additionally, your browser's debugger can help you find where a problem is.

Having trouble displaying an array value within console.log event using .push function in Jquery

The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">

Getting the following error Cannot read property 'value' of undefined at HTMLInputElement.onclick

Trying to create a simple calculator and this is the code I have input.
<input type="button" value=" 1 " onClick="calculator.answer.value += '1'" />
The problem is that I am getting the above error. Not sure what could be the problem.
Below is the error again.
Cannot read property 'value' of undefined
at HTMLInputElement.onclick
If you really have an object with property called answer that itself is an object with property called value (that is what your code looks like), then you need to wrap your calculator.answer.value += '1' in function and execute that function on click.
const calculator = {
answer: {
value: 0
}
};
function addOne() {
calculator.answer.value += 1;
console.log(calculator.answer.value);
}
<input type="button" value=" 1 " onClick="addOne()" />
Although you should move that onClick code to js file and replace it with addEventListener method so that you don't clutter your HTML with JavaScript.
const calculator = {
answer: {
value: 0
}
};
const btn = document.querySelector('input');
btn.addEventListener('click', addOne);
function addOne() {
calculator.answer.value += 1;
console.log(calculator.answer.value);
}
<input type="button" value=" 1 " />

HTML/javascript TypeError when using document.getElementById even though ID's are declared

A button on my webpage stops working every few days and then starts working again without any intervention/modifying source code. This "Next" button calls a javascript function to iterate forward through an array of text already retrieved via php, but sometimes it stops working. I have not touched this code for more than a month, and during this time I have seen it working most of the time - but not always. Today it's not working.
Here is the button declaration:
<input type="button" value="Next Question" class="button" onclick="submitform('Next')" style=" padding: 0.25em 1em 0.25em 1em;" id="nextQButton"/>
The button calls function submitForm with parameter "Next."
function submitform(x)
{
document.getElementById("alertShow").innerHTML = ""
if(x=='Back')
{
....
}
else if(x=='Next')
{
alert("next Q!");
if(jj+1<numQQ){
runningSum += qnumans_array[jj];
}
++jj;
++j;
kk=0;
if (jj == limit)
{
if((viewQ==null)&&(viewA==null))
{
window.location="judge.php?counter="+j;
}
else if(viewQ)
{
window.location="judge.php?&counter="+j+"&viewQ="+viewQ;
}
else if(viewA)
{
window.location="judge.php?&counter="+j+"&viewA="+viewA;
}
}
alert("middle of next q bit1");
if( jj>=numQQ && jj!=limit)
{
--jj;
--j;
alert("middle of next q bit if statement");
document.getElementById("alertShow").innerHTML = "end of available questions for this category";
}
alert("middle of next q bit2");
alert("jj is"+jj);
alert("qid array at jj is"+qid_array[jj]);
document.getElementById('qidInput').value = qid_array[jj]; ///*****this is where it stops outputting script alerts. all alerts before this output as they should.
***********************************************
alert("middle of next q bit3");
document.getElementById('jjInput').value = j;
alert("middle of next q bit4");
document.getElementById("questionShow").innerHTML = quser_array[jj] + ": "+ question_array[jj];
alert("middle of next q bit5");
if(qnumans_array[jj]>0)
{
document.getElementById("answerShow").innerHTML = auser_array[kk + runningSum] + ": " + answer_array[kk + runningSum];
}
else
{
document.getElementById("answerShow").innerHTML = "No answers posted to this question.";
}
alert("got to end of next q bit");
}
....
}
The line after which the alerts fail relates to this input field in an html form in the same php files:
<input type = 'hidden' id = 'qidInput' name = 'qid' >
Chrome debugging tool gives me this error
Uncaught TypeError: Cannot set property 'value' of null
on every line that calls:
document.getElementById("qidInput").value = qid_array[jj];
Even though these similar calls generate no error:
document.getElementById("jjInput").value = j;
document.getElementById("kkInput").value = kk+runningSum;
All these HTML elements are declared together and are of the same type:
<form name="messageInput" id = 'idForm' method="get" action="judge.php?"
onSubmit="return validate(this)">
<center><textarea name='text' style="height: 1em"></textarea><br>
<input type = 'hidden' id = 'qidInput' name = 'qid' >
<input type = 'hidden' id = 'jjInput' name = 'counter' >
<input type = 'hidden' id = 'kkInput' name = 'kk' >
<ul class="actions">
<li><input type="submit" value="Post Message" class="button"/></li>
</ul>
</center>
</form>
If I comment out every line that contains qidInput, the error message switches to giving the same error, now for every line that contains "jjInput." So it seems to be something about the ordering - whichever HTML element is called by id first is nil.
This happens on the same computer and browser on different days. The conditions on the webpage are the same, too.
Any debugging advice would be appreciated. Thank you.
Fixes that didn't work:
-swapping single and double quotes
-adding a "dummy" element and setting it first (so it's probably not ordering)

Categories