element id is not accessible javascript - javascript

i have the following code. here i am declaring all the element id's to variables as global before all the functions declared. but those variables are taken by the functions
below is the sample:
var ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
var disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
function btn_proceed_Click()
{
var ses='<%=Session("hcur").toString %>';
if(pos_valid()==true)
alert('success');
}
function pos_valid()
{
var pos_valid=false;
var ses;
var ccy;
var ccy1;
var ccy2;
var as11costbud;
ses='<%=Session("hcur").toString %>';
var bm='<%=Session("benchmark").toString %>';
var dtsheet='<%=Session("dtsheet").toString %>';
var ratedis='<%=Session("ratedis").toString %>';
if(ddlpf.selectedIndex <= 0)
{
message("Please select the Portfolio");
return;
}
pos_valid=true;
return pos_valid;
}
function message(msg)
{
disp_msg.innerHTML=msg;
var modalPopupBehaviorCtrl = $find('modalpop');
modalPopupBehaviorCtrl.set_PopupControlID("poppan");
modalPopupBehaviorCtrl.show();
}
If i declare the variable "ddlpf" inside the pos_valid() and "disp_masg" inside the message(), it works.
the code is like this:
function pos_valid()
{
var ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
//code
}
function message()
{
var disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
//code
}
but these id's are common to 5 functions. not only this two. i have 20 id's which are common to 5 big functions. thats why i have declared them outside the functions.
what change should i make?

I am guessing you are putting the script at the top of the HTML page. So the page has not finished loading yet and you are trying to access the document.getElementById even before the document.body is ready. So when you access them in your functions, the variables value will be undefined => your problem
Try it this way,
var ddlpf;
var disp_msg;
window.onload = function(){
ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
}
This way, you can put the code anywhere.

As far as i understood your question and with the code provided you are wondering
why your global variables appear not to work ddlpf and disp_msg is not working inside pos_valid and message functions
You have to make sure that the global variables are declared before any function is using them. Another option would be to pass in the variables.
In my demo on codepen you can see that it works. This html
<h2>Element id is not accessible</h2>
<select id="ddlpf">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button onclick=btn_proceed_Click()>proceed</button>
<div id="disp_msg">
</div>
and this javascript
var ddlpf=document.getElementById('ddlpf');
var disp_msg=document.getElementById('disp_msg');
function btn_proceed_Click()
{
if(pos_valid()==true)
{
var btn = document.getElementById('btn');
btn.innerHTML='success';
};
}
function pos_valid()
{
var pos_valid=false;
var ses, ccy, ccy1, ccy2, as11costbud;
var selectedIndex = ddlpf.selectedIndex
if(selectedIndex <= 0)
{
message("Please select the Portfolio. Your selection:" + selectedIndex);
return;
}
message("Your selection" + selectedIndex);
pos_valid=true;
return pos_valid;
}
function message(msg)
{
disp_msg.innerHTML=msg;
}
If you provide more information erromessages from chrome dev tools we can help better.

Related

Javascript/JQUERY local variable

I have 2 pieces of code
Javascript:
function changeImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG") {
npath = document.getElementById("main_img").src = targetElement.getAttribute("src");
}
}
and JQUERY
var bpath = npath.replace("_n", "_b");
$(document).ready(function(){
$('div.prod_seeds_mimg_div').zoom({url: bpath});
});
I want to access npath variable from Javascript block, change it and use in JQUERY. But npath variable is not defined outside of Javascript. I've tried to make it global by skipping var and declare npath on top of two blocks (var npath = "";) but these methods are not helped.
Is there some way to access npath from JS and use it further?
Thanks.
EDITED
Try to use the following code:
$(document).ready(function(){
$('.prod_seeds_mimg_div').zoom({url: $('#main_img').attr('src')});
$('div.prod_seeds_oimg_div img').on('click', function(){
changeImage($(this).attr('src'));
});
});
function changeImage(imagePath){
$('#main_img').attr('src', imagePath);
$('.prod_seeds_mimg_div').zoom({url: imagePath});
}
And remember to remove the changeImage onClick trigger from your HTML source.

Call function is not a function

$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
I got an error that is $.club_settings is not a function. How can i call $.club_settings in a if condition ?
You're defining the function after you call it. Switch around the code like so:
$(function() {
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
})(jQuery);
JavaScript only hoists declarations, not initializations.
The reference above displays how variables are hoisted but it works for functions too.
$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
club_settings();
function club_settings() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
The drawback would be is that it would be found in your $ variable which may lead to codes elsewhere breaking. But that could be another question.
Trying to resolve this by doing $.club_settings() = function club_settings() { ... will not work unless you reorder your codes as suggested by Mike

Javascript - Uncaught ReferenceError - Code seems perfect?

Here's how I'm calling my JS:
"#item.OwnerID#" is a variable from a loop containing an ID. So the element I want to change the CSS for should look like: "cwa123" or some other number for the id...
Here's my JS:
$(document).ready(function() {
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
});
I ain't got a clue, it gives me the "not defined" error...
Out of scope, remove the document ready wrapper
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
Every function creates a new scope, the global scope is window, and that's the scope used for inline javascript.
Inside $(document).ready(function() { ... }); the scope is changed (to document) so the function is out of scope for the inline handler.
An even better approach would be to use a proper event handler
$('.FCChatControl').on('click', function() {
toggleChatControl('cwa#item.OwnerID#');
});

Keeping variables between function executions (Javascript)

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.
All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.
An example follows:
$(document).ready(function()
{
$(".sidebar a").click(function(event) {
event.preventDefault()
var targetID = $(this).attr("data-target")
$("#" + targetID).attr("src", $(this).attr("href"))
var element = $(this).attr("class")
if (element == "submit") {
var submit = $(this).attr("user")
alert("1")
} else if (element == "view") {
var view = $(this).attr("user")
alert("2")
}
})
window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})
Thanks
You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.
Example
var next = (function() {
var value = 0;
function next() {
return value++;
}
}());
console.log(next());
console.log(next());
console.log(next());
Live demo
http://jsfiddle.net/bikeshedder/UZKtE/
Define the variables in an outer scope:
$(document).ready(function () {
var submit;
var view;
$(".sidebar a").click(function (event) {
event.preventDefault();
var targetID = $(this).attr("data-target");
$("#" + targetID).attr("src", $(this).attr("href"));
var element = $(this).attr("class")
if (element == 'submit') {
submit = $(this).attr("user")
alert("1")
} else if (element == 'view') {
view = $(this).attr("user")
alert("2")
}
});
});
Create var submit and view outside of the function so it has a global scope.
You can store arbitrary data on a matched element with JQuery's .data() function.
Example:
$(this).data("submit", $(this).attr("user")); // set a value
var submit = $(this).data("submit"); // retrieve a value
This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

"Not defined" javascript error in Firefox

I'm very new to JS, and understand that my script is probably terrible, but it all works fine in Safari and Chrome, just not in Firefox.
Amongst other things, I'm calling two functions to hide and reveal a custom Quicktime movie controller by placing a "mask" over the top of it (I know a toggle would be a more elegant solution, but I couldn't get such a function to work the way I wanted). Anyway, this is what the Javascript looks like:
function revealControls(){
document.getElementById("controlsCover");
controlsCover.style.display ="none"
}
function hideControls(){
document.getElementById("controlsCover");
controlsCover.style.display ="block"
}
I'm calling these functions with different mouse events applied to various divs, such as:
<div id = "controls" onmouseout = "hideControls()">
Firefox is telling me
"Error: controlsCover is not defined",
and I have no idea how to define the element as null.
Any help would be appreciated. I'm sure it's something very simple — but I have virtually no experience with Javascript. Yet.
You need to create the controlsCover variable first to reference it.
When you first use document.getElementById("controlsCover"), this will return a HTML element of which you pass to a variable to use.
If you uncomment the console.log - you'll see what is inside the variable.
function revealControls()
{
var controlsCover = document.getElementById("controlsCover");
/* console.log(controlsCover) */
controlsCover.style.display ="none"
}
function hideControls()
{
var controlsCover = document.getElementById("controlsCover");
controlsCover.style.display ="block"
}
You need to assign document.getElementById return value to controlsCover variable:
var controlsCover = document.getElementById("controlsCover");
Fixed will be:
function revealControls() {
var controlsCover = document.getElementById("controlsCover");
controlsCover.style.display ="none"
}
function hideControls() {
var controlsCover = document.getElementById("controlsCover");
controlsCover.style.display ="block"
}
Try this:
var ele =document.getElementById("controlsCover");
ele.style.display = "none";
Try this:
function revealControls()
{
var oControlsCover = document.getElementById("controlsCover");
if (oControlsCover) {
oControlsCover.style.display ="none";
}
}
function hideControls()
{
var oControlsCover = document.getElementById("controlsCover");
if (oControlsCover) {
oControlsCover.style.display ="block";
}
}

Categories

Resources