I have html like
<div id="MAC_Allocation_Heading">
<span style="position:relative;left:2%;">
MAC Allocation
</span>
<span style="position:relative;left:9%;">
<label>Quantity</label>
<input type="text" style="width:40%" name="txtMACNeededAllocations"/>
</span>
</div>
Now in my .js file I have a global array as
var user_entry = [$("#MAC_Allocation_Heading input[type=text]:first")]
and inside FormValidate() I have the following code
function FormValidate() {
console.log(user_entry[0].val());
}
I run the application and entered value in text box. But I am getting console output as 'undefined'.
If I put the array "user_entry" inside the function then am able to get the textbox value.
What is the reason?
I Would love to keep this array globally as it will be used by other functions also
Try this:
var user_entry = [];
function FormValidate()
{
alert(user_entry[0].val());
}
$(document).ready(function()
{
user_entry = [$("#MAC_Allocation_Heading input[type=text]:first")]
})
By this you can achieve "I Would love to keep this array globally as it will be used by other functions also".
I got the issue as per comments above
I initialized the array inside $( document ).ready(function() { ... });
and this solved my issue
The problem is I included the .js file before tag so that before DOM is loaded completely I try to get a reference to the object which is obviously empty
Related
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);
}
I have a js file which is part of a larger website using react.
I have a class and inside the render & return I have a div which displays a popup form, inside that I wanted to add javascript as I've done previously, but the first line of script is giving the error [ts] Expression Expected.
Code example:
<div className='popup_inner'>
{
//the script, fails first line on var with [ts] Expression Expected
var necc = $('example')[0];
//more code
}
</div>
Later in the code I do the same thing which works fine
<div className='example2'>
<button onClick = {script variable}> Save </button>
I've done many google searches, and used <script> instead of {} but it didn't make any difference. Anyone got any ideas?
This is definitely a ReactJs issue. So, you cannot make any declarations in a react return statement.
a React call looks like this:
const ReactElement = () => {
var dataInside = 'Something Something'
return <div>{dataInside}</div>
}
See how the variable is declared above the return statement.
You are trying to return while declaring variables where dataInside is located. What you are doing returns nothing, move it up before the return statement. If you really want to mix jQuery with React you could do something like this
const ReactElement = () => {
var necc = $('example');
return <div dangerouslySetInnerHTML={{__html: necc.html()}}>
}
As #HarishSoni mentioned, you probably didn't import $ from jQuery.
If you only need to assign a variable inside this div, I would recommend replacing your jQuery variable assignment here with a pure JavaScript variable assignment instead like this:
<div className='popup_inner'>
{
var necc = document.querySelector('example'); // you dont need to add [0] since querySelector returns the first element by default
}
</div>
Update: #Moosecouture's answer is the correct way to do this. The variable assignment should be done within the render but outside the return like this:
class SomeReactClassName extends React.Component {
render(){
var necc = document.querySelector('example');
return (
<div className='popup_inner'>
<p>The variable above is {necc}</p>
</div>
)
}
}
I have the following function (onButtonClick) when the button is clicked only the first function works. All the included functions work if I only have one of them in the button function.
I have also tried the on button click function this way as well. Still does not work.
setProjectData() && getProjectData() && window.location.href='support_page.html';
Any ideas on what I may be missing?
<span class="profile_container_right">
<a onclick='onButtonClick()'; return true;"; ><img src="images/bSUPPORT.png"/></a>
</span>
<script>
/* on button click */
function onButtonClick(){
setProjectData();
getProjectData();
window.location.href='support_page.html';
}
function setProjectData() {
// --- set local storage project descriptions ---
vProjectName=‘The Project Name’;
localStorage.setItem('xProjectName', vProjectName);
return true;
}
function getProjectData() {
// --- get local storage project descriptions ---
vProjectName = localStorage.getItem('xProjectName');
alert('you entered the GET project data function ='+vProjectName);
return true;
}
</script>
First issue is the use of quotes in the onclick binding:
onclick='onButtonClick()'; return true;";
The correct syntax for onclick is onclick="yourFunctionCall();" for example:
onclick="onButtonClick(); return true;"
Second issue is your use of quotes in the setProjectData function:
vProjectName=‘The Project Name’;
Change to single quotes or double quotes:
vProjectName="The Project Name";
With these syntax issues fixed your code should execute as expected.
Side note use var to declare variables within a function to make them adhere to the scope of the function. Declaring a js variable without the var exposes the variable globally.
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.
I have this code in my js file
var selectedTagElement = _.template('$("#selected_tag_item_template").html()', item = { tag: label, value: value });
$('#wrapper_id').append(selectedTagElement);
and this in my html file
<script type="text/template" id="selected_tag_item_template">
<div class="tag_item selected js-selected_tag_item"
data-tag-value="<%= item.value %>"
data-tag-label="<%= item.tag %>"><%= item.tag %>
</div>
</script>
Everything is working fine in all browser but IE9 and IE10. If it try
console.log(selectedTagElement)
all i get is
LOG: function(n){return o.call(this,n,m)}
and if i try to print the item variables in my html file, like this
<%= item %>
i get this
function item() { [native code] }
What's going wrong? Thanks
The output you're getting from:
console.log(selectedTagElement)
indicates that selectedTagElement is a function. You used to be able to compile and fill in a template in one step but that stopped working in Underscore 1.7.
You need to start building your selectedTagElement in two steps:
Compile the template to a function using _.template.
Run that function with the desired data to get your HTML.
So you want to be saying this:
var t = _.template($('#selected_tag_item_template').html());
var selectedTagElement = t({ item: { tag: label, value: value } });
That should work everywhere and matches the standard usage.
Your code works by accident where it works at all. I'm going to assume that '$("#js_template").html()' is just a typo because it doesn't make sense otherwise. Let us break up your code into something equivalent:
item = { tag: label, value: value };
var selectedTagElement = _.template('$("#js_template").html()', item);
$('#wrapper_id').append(selectedTagElement);
The first line creates a global item variable that holds the data you want to give to the template.
The second line will compile the template into a function and ignore the second item argument completely since it doesn't match any of _.template's options.
The third line hands a function to [append]2. Normally you give append a string of HTML or a DOM node but you can also give it a function; when you give append a function, it runs the function and uses its return value as an HTML string. In non-IE browsers, the template function will get the item through your accidental global variable:
item = { tag: label, value: value }
but IE is using an item function (which is implemented with native code in the browser) from somewhere instead of using your item variable.