Unable to create a variable in javascript - javascript

I am creating an app that will tell you the price of a product when the barcode is scanned. Basically, when a barcode is scanned, it goes into the text field, and then based on which barcode it is, the textarea will have a price put into it via javascript. I've gotten this to work, but I can't seem to create a certain variable to save me from looking through tons of code later on.
Here is my javascript:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea').innerHTML;
if (userInput === "783466209834") {
price = "16.99";
} else {
price = "Not a valid barcode";
}
}
And here is my HTML:
<input type="text" name="text" class="textinput" id="barcode">
<input type="button" onclick="showPrice()" value="Submit">
<textarea name="" cols="" rows="" readonly="readonly" id="textarea"></textarea>
Right now, my code isn't working, but if I remove
var price = document.getElementById('textarea').innerHTML;
and replace "price" in the if statement respectively, then it works. I'm not sure why I can't create this price variable.

Because you're storing the value of the innerHTML as the variable, not storing a reference to it.
Change it to var textarea = document.getElementById('textarea'); and then textarea.innerHTML = "16.99" and so on.

If you want to work with the value of the textarea, you need to access document.getElementById('textarea').value, not innerHTML.
And, yes, as others have pointed out, you want to set the variable to reference to the element, not the value. Then you can retrieve or set the value of the element.

You are getting the innerHTML of the textarea and storing it in the variable price. Instead, you need to only store the element in the variable and then call price.innerHTML to place your result in the DOM. Like such:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}
}
EDIT: As talemyn correctly points out, you should use .value rather than .innerHTML for altering the contents of textareas. While it might look like it does the same thing, there are slight disadvantages that come with the use of .innerHTML.

You should not assign a value to price and then overwrite it... That's what your code is doing. I believe you think you are creating a storage location in the innerHTML?
Instead, just create the variable:
var price;
Run your code as you did; and then put the result into the page with
document.getElementById("text area").innerHTML = price;

You're setting the 'price' variable twice with two separate things. You're not actually changing the DOM. Instead use:
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}

Related

Error with Javascript TypeError code, variable undefined

I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.

Set HTML Form Input To JS Variable

I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.

get input value using javascript and based on its value use javascript to insert a value elsewhere

I have this loading at the bottom of the page
if((document.getElementById('pcc').value)==="1") {
var $postcontrr = "hello";
document.write($postcontrr);
}
else {document.write ('this is messed up');}
in my form I have a field with id=pcc so the way I'm reading it is, if the value of field with id of pcc is 1 the the varialbe $postcontrr is going to be Hello and then the document.write should print Hello. But I get nothing. Not even the else statement prints. Any pointers would be appreciated.
Get the expected result. No error here.
Please check it out in
if ((document.getElementById('pcc').value) === "1") {
var $postcontrr = "hello";
document.write($postcontrr);
} else {
document.write('this is messed up');
}
<html>
<input id="pcc" value="1" type="text" />
</html>
I would make you javascript into a function so you can call it onkeyup of the input. I would also change the inner html of an element instead of using document.write otherwise you will just be appending the text to the document each time the input changes.
<script>
function checkValue() {
var $postcontrr;
if (document.getElementById('pcc').value === "1") {
$postcontrr = "hello";
} else {
$postcontrr = "this is messed up";
}
document.getElementById('result').innerHTML = $postcontrr;
}
</script>
<input type="text" id="pcc" onkeyup="checkValue();">
<div id="result"></div>

Does node created within a sub-function stay valid even after the function exited?

I have project for my php class where I have to enter First name, last name, email, and phone number and output returns the exact values. (but I will only put the 'first name' code for editing).
I have a function in of html that gets called from 'onsubmit' inside
<script>
function validate3(){
alert ("1validate3 called");
var elemFnameSpan = document.createElement("span");
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
elemFnameBrParent.insertBefore(elemFnameSpan,elemFnameBr);
elemFnameSpan.id = "idFnameErr";
elemFnameSpan.style.color="red";
elemFnameSpan.innerHTML="";
var elemFname=document.getElementById("idFname");
var elemFnameValue = elemFname.value;
var errorFlag=false;
if (elemFnameValue == null || elemFnameValue ==""){
elemFnameSpan.innerHTML ="required field";
return false;
}
else{
elemFnameSpan.innerHTML="";
}
if(errorFlag==true){
return false;
}
return true;
}
</script>
<form onsubmit="return validate3()" action = "ContactInfo.php">
First Name<span style="color:red">*</span>
<input type="text" name = "Fname" size = "10" id="idFname" onchange="eraseFnameErr()"/>
<br id="idFnameBr" >
<input type="submit" name="submit" value="Submit" /><br>
The function creates a node 'elemFnameSpan' before of id 'idFnameBr'. If the textinput for first name is empty, elemFnameSpan.innerHTML outputs "required field", and false on 'onsubmit' . My problem is that the output doesn't refresh everytime the submit button is called, so 'required field' outputs get extended next to each other.
I am having difficulty resolving this situation and tried to remove the previous child node everytime the new function is called, but that didn't work either for me yet.
Once you append any DOM node, it never removed unless you do it explicitly.
I can suggest two ways to achieve your goal.
First, you can save the node in a global variable.
var elemFnameSpan;
function validate3(){
alert ("1validate3 called");
if (!elemFnameSpan) {
elemFnameSpan = document.createElement("span");
}
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
Or, set id to elemFnameSpan and find it every time the form is submitted.
function validate3(){
alert ("1validate3 called");
var elemFnameSpan = document.getElementById('whatever_you_want');
if (!elemFnameSpan) {
elemFnameSpan = document.createElement("span");
elemFnameSpan.setAttribute('id', 'whatever_you_want');
}
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
You need to check if you have already created the span element, if you have grab it by using getElementById, if you havent then create it.
//This is an "if" shortcut, if getElementById returns null
//the code in right side will execute and the return value
//will be put in eleFnameSpan
var eleFnameSpan = document.getElementById("idFnameErr") || document.createElement("span");
var elemFnameBr = document.getElementById("idFnameBr");
//Check parentNode on elemFnameBr if it is null/undefined then it hasnt
//been added to the dom yet
if(!elemFnameBr.parentNode){
//No need to store the parentNode (unless needing it else were in code)
elemFnameBr.parentNode.insertBefore(elemFnameSpan,elemFnameBr);
elemFnameSpan.id = "idFnameErr";
elemFnameSpan.style.color="red";
elemFnameSpan.innerHTML="";
}
The rest of the code can stay the same
What is happening is you are just creating a new span on each click, and since on each click you add a new span and edit that one instead of the original one you keep getting new message stacked next to each other.

In Javascript, Value not comming instead the variable name is displayed

function ProvideValue(){
Values = document.getElementById('HiddenValue').value;
FirstCut = Values.split("###"); // This will return the array ID#-#VALUE#-#TYPE
var CtrlId;
for (i = 0; i < FirstCut.length - 1; i++) {
Strings = FirstCut[i];
SecondCut = Strings.split("#-#");
if(SecondCut[2].match("TEXT")) {
CtrlId = "" + SecondCut[0];
document.getElementById(CtrlId).value = SecondCut[1];
}
}
}
This is my code instead of the Id, which i can print it.But CtrlId is not replaced by the actual value. Am getting error document.getElementById(CtrlId).value is NULL. I tried to hard code the ID then its working fine but i cannot hard code the controlsID because there are 1000s of control and everytime the ID changes.
Your code seems fine (apart from implied globals1), you must have some other problem in your HTML document... I'm also not sure why you're leaving out the last value from the first cut since you're interating to length - 2, because i is less than length - 1 (not less than or equal) which means that it goes all the way to value length - 2 and then breaks the loop.
Here's a JSFiddle I created that uses your code and displays some additional console messages and actually applies values to inputs as provided by the hidden input.
1Important
I applied var to your variables so they're not implied globals which should be avoided at all times because they're nothing but evil friend of hidden bugs.
The code I used
HTML is super simple but I do have both elements with IDs that are being addressed in the compound value of the hidden field:
<input type="hidden" id="hidden" value="me#-#Rob#-#text###you#-#Mike#-#text" />
<input id="me" value="name" />
<input id="you" value="name" />​
Script is simple as well (runs on DOM ready for JSFiddle simplicity reasons):
var vals = document.getElementById('hidden').value;
var firstCut = vals.split("###");
for(var i = 0; i < firstCut.length; i++) {
var ctrl = firstCut[i].split("#-#");
if (ctrl[2].match("text")) {
var id = ctrl[0];
document.getElementById(id).value = ctrl[1];
}
}​

Categories