Read ViewBag in javascript generating errors - javascript

I tried many ways to get the value of a ViewBag in Javascript, but all showed errors. I have a view and a js file.
<input type="text" id="myInput" data-myValue="#ViewBag.PrimerNombre" />
//Undefined
var myVal = $("#myInput").data("myValue");
alert(myVal);
<input type="hidden" id="customInput" data-value="#ViewBag.PrimerNombre" />
//Cannot read property value of null
var customVal = $("#customInput").data("value");
alert(customVal);
//Cannot read property value of null
<script type="text/javascript">
var myJsVariable = '#ViewBag.PrimerNombre'
</script>
//Show warning is not defined
$(document).ready(function() {
showWarning('#ViewBag.Message');
});
//Unrecognized expression ##(ViewBag.PrimerNombre)
var x = $('#' + '#(ViewBag.PrimerNombre)').val();
//Cannot read property value of null
var myValue = document.getElementById("#(ViewBag.PrimerNombre)").value;
I tried all, one by one, there is one part ot the view that matchs a part in the javascript file, i put the errors above, if you know a way that really works please tell me.

I´ve found that the code that was after in my js, some code i copied and that i needed to adapt was the one causing the error

Related

Global variable not working as an input value

I am a JavaScript beginner, I am stuck with a problem regarding variables.
I wrote this code :
var acNo = document.getElementById("ac").value;
function doSomething(){
alert(acNo);
}
The output is: undefined
But when I did this :
var acNo = 3
The output is 3
Html code :
(This is a very big project so that's why I cant share much code, but I am sharing the HTML code related to this script)
<td>A/c</td>
<td> <input type="number" name="" id="ac"></td>
<td> <input type="number" name="" id="acHour"></td>
Can you please tell me how can I fix it while keeping the variable global only.
Try defining acNo after the document has fully loaded, or within the function.
Solution 1:
let acNo;
window.onload = () => {
acNo = document.getElementById("ac").value;
}
function doSomething() {
alert(acNo);
}
Solution 2:
funtion doSomething() {
alert(document.getElementById("ac").value)
}
A way you can go to check that is by opening the dev tools of your browser and running your document.getElementById in the console.
You will be able to see everything about the element and what properties it has. For example, you might want to check innerHTML instead of value depending on your element type.
I think the value is only set in the beginning and not when you run doSomething later. If you want to have the value globally, have a global variable and keep updating it when you call doSomething.
var acNo = document.getElementById("ac").value;
function doSomething(){
acNo = document.getElementById("ac").value;
alert(acNo);
}

JavaScript value not getting fetched undefined is coming

Why this code lines are not working
let a = document.getElementsByTagName("input")[0].value;
let b = document.getElementsByTagName("input")[1];
b.value = a;
A simple code to get value from one text and paste it into another text.
The issue code be that your code is running before the DOM is fully loaded. In that case you should get the following error:
Uncaught TypeError: Cannot read property 'value' of undefined
To solve the above issue either you can palce your code at the bottom of the body tag or wrap the code with DOMContentLoaded.
Demo:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
let a=document.getElementsByTagName("input")[0].value;
let b=document.getElementsByTagName("input")[1];
b.value=a;
});
</script>
<input value="123"/>
<input />
JavaScript can't get input element.
Why did you decided to get inputs by theirs tagname? Use id's or classes for getting it.
Second is, check it for availability at all.
for example:
const [firstInput, secondInput] = document.getElementsByTagName("input");
if (firstInput && secondInput) {
secondInput.value = firstInput.value || 'default value';
}
Something like that.

Property says it can't be read, even though it can read the property

Before I start, I just want to say I have very little experience with javascript, so maybe I'm missing something very obvious, but anyways.
I have an array of objects called Accommodations. I have the following code:
alert(this.quoteService.activeBasket.components.length);
This alert shows a length of 3, but I get a ton of errors saying:
An unexpected error has occurred. TypeError: Cannot read property 'length' of undefined
I'm just not sure how it's possible that it can read the .length property, but it's throwing errors that it can't...
Originally, the component object wasn't imported into this file, but even after importing it, I still have the same error...
Any help is greatly appreciated.
Edit:
Here is a little more context:
Basically I have an html file that has a radio button, this button should be greyed out, based on the method found in the ng-disabled tag:
<li class="c-3-12">
<div class="radio-btn" tl-field>
<input type="radio" class="radio" ng-model="vm.requiredBookingState"
ng-value="1" ng-disabled="!vm.validateOutfitLength()">
<label i18n>Confirmed</label>
</div>
</li>
Here is that method:
validateOutfitLength()
{
var rv = true;
let accoms: Accommodation[] = this.quoteService.activeBasket.accommodations;
accoms.forEach(accom => {
if (accom.outfitLength < 350) {
rv = false;
}
});
return rv;
}
The error for this code is different than above! The error for this is:
An unexpected error has occurred. TypeError: Cannot read property 'forEach' of undefined
This is a very large project that I'm working on, and I'm unaware if it's intentional that this method is being called many times... I assume it is intentional though.
Try this
alert(this.quoteService['activeBasket']['components'].length === undefined ? '' : this.quoteService['activeBasket']['components'].length);
This has been solved! I do want to give some credit to Chellappan, as I wouldn't have been able to find the solution without his answer.
Basically, there must be multiple calls to the validateOutfitLength method and within some of those calls, the quoteService.activeBasket.accommodations/components were undefined. The fix was simple, it was just basically checking whether the object was undefined before doing anything with the value.
let accoms = this.quoteService.activeBasket.accommodations;
if (typeof(accoms) != 'undefined') {
// do something with accoms
}

Javascript reference error to function

I want to call a Javascript function every time a checkbox changes its value. I do the same for inputs of the select type and there it works just fine. Both inputs are in one table.
This is one element that calls the first function:
<td>
<select name="minuteEnd" id="minuteEnd" onChange="calculateWorkTime()">'.$dropDown_minuteEnd.'
</select>
</td>
And the part which calls the second function
<td>
<input type="checkbox" name="deleteShift" id="deleteShift" onChange="updateSubmitButton()" /><br />
<input type="checkbox" name="deleteShiftConfirm" id="deleteShiftConfirm" onChange="updateSubmitButton()" />.
</td>
Then I define both functions in separate script tags, but I also tried to define them in one, that did not solve the problem. Because I do not always need both of them I call a PHP-function for each to be written.
These PHP functions are
drawScriptCalculateWorkTime();
drawScriptUpdateSubmitbutton();
the actual Javascript code is this:
function drawScriptCalculateWorkTime()
{
echo'
<script>
function calculateWorkTime()
{
//I work (My name can be found)
}
</script>
';
}
function drawScriptUpdateSubmitbutton()
{
echo'
<script>
function updateSubmitButton()
{
//I do not work. I get the error: ReferenceError: updateSubmitButton is not defined
//This is my code
var delete = document.getElementById("deleteShift").checked;
var deleteConfirm = document.getElementById("deleteShiftConfirm").checked;
if(delete && deleteConfirm)
{
document.getElementById("submitButton").disabled = false;
}
}
</script>
';
}
My Browser-console always tells me
ReferenceError: updateSubmitButton is not defined,
but I checked the name about 20 times. Further, it always tells me on window load this:
SyntaxError: missing variable name
This refers to the first line of Code of the second javascript.
I already checked google and even found a quite similar question here ( Javascript Uncaught Reference error Function is not defined ) but that solution did not work for me.
If I did not provide all information needed I will provide them right away.
John
In javascript, delete is a reserved word and cannot be used for a variable name.

TypeError:Cannot read property 'getElementById' frameset

I have a simple code that refreshes the main page each time there is a new version, but it only works in Internet Explorer. In other browsers I get the following error:
Uncaught TypeError: Cannot read property 'getElementById' of undefined line 24
Here is my code:
<html>
<script type="text/javascript">
var num=0;
var currVersion;
var started=false;
function startLoad() {
var url= "version_telemark.html?"+ (++num);
window.version.navigate(url);
}
function endLoad() {
if (started) {
var newVersion = version.document.getElementById("version").value;
if (newVersion != currVersion) {
currVersion=newVersion;
var url = "telemark.html?"+ (++num);
window.pane.navigate(url);
}
}
}
function start() {
currVersion = version.document.getElementById("version").value;
started=true;
setInterval("startLoad()", 200);
}
</script>
<frameset onload="start()" cols="40%,100%">
<frame id="version" src="version_telemark.html"/>
<frame id="pane" src="telemark.html" />
</frameset>
</html>
and in my other file I only have that I wish to edit I have:
<input id="version" name="version" type="textbox" value="700">
and my other file that has the design just has tables but we wont need to add anything there.
Two things:
Your code is relying on the automatic global that browsers create for elements that have ids on them, by using version as a global variable without declaring or initializing it. Perhaps for some reason, the automatic global isn't working on browsers other than IE. I don't like to rely on them anyway, it's too easy to shadow them, so I suggest getting the element on purpose by adding this near the top of your script:
var version = document.getElementById("version");
But your comment on the question suggests that it's not this, but #2 below:
You may need vesrion.contentDocument rather than version.document in your currVersion = version.document.getElementById("version").value; and similar lines; perhaps JavaScript's curiously-powerful || operator:
var versionDoc = version.document || version.contentDocument;
// ...and then
currVersion = versionDoc.getElementById("version").value;
// ...and so on
Side note: Just to keep yourself and whoever has to maintain the code after you sane, I'd also suggest different id values for the version frame and the version input inside it.

Categories