Uncaught Reference Error with inline javascript - javascript

I have the following function:
if ($(this).find('#sel').length == 0) {
var before = $(this).text();
var title_id = $(this).parent().attr('id');
$(this).html("<select id='sel' onchange='selectdone(this, title_id=title_id)>
...</select>");
}
From this I get Uncaught ReferenceError: title_id is not defined. Why isn't the onchange function inside on line 4 not picking up on the variable that I've defined previously? How would I rewrite the above correctly?

Did you mean this?
$(this).html("<select id='sel' onchange='selectdone(this, "+title_id+");'>...</select>");

Use string concatenation here:
$(this).html("<select id='sel' onchange='selectdone(this, title_id=" + title_id +");'>...

It's happening because you're defining the "change" handler as part of a string, so the language has no idea that there's code in there.
Try this:
$(this).html($("<select/>", {
id: 'sel',
change: function() { selectdone(this, title_id) }
}));
Since you're using jQuery anyway, you should get in the habit of managing your event handlers via the library instead of with "onfoo" attributes.

Related

Cannot pass jQuery object.method to another function to be executed

I have the following JavaScript:
function MyMethod(func)
{
func();
}
$('#Btn').on('click', function(e)
{
e.preventDefault();
var form = $(this).parent();
MyMethod(form.submit);
});
http://codepen.io/chrisnicholson/pen/YGxOdJ
This doesn't work, giving the following error in Chrome:
jquery.min.js:4 Uncaught TypeError: Cannot read property 'trigger' of undefined
If I modify the call to MyMethod to use the following then it works:
MyMethod(function(){
form.submit();
});
http://codepen.io/chrisnicholson/pen/amyRXX
Can someone explain why this is?
Ah, good ol' binding of this at work! If you only provide the method, it will not be called on the form but on the global object, like
submit.call(window) // resp. undefined in strict mode. Hence the error, I guess.
where what you want is
submit.call(form)
One way to fix this: Bind the submit method to the form:
MyMethod(form.submit.bind(form));
Your code be. Just pass the object is enough.
function MyMethod(formSubmit)
{
formSubmit.submit();
}
$('#Btn').on('click', function(e)
{
e.preventDefault();
var form = $(this).parent();
MyMethod(form);
})
Without the parentheses, .submit would just be a property of the jQuery object that you have. In this instance, your form.
Adding the parentheses actually calls the .submit() method on the form object.

onclick attribute not working as expected

I have a jquery file as follow :
$('.font').click(function(){
for(i=0;i<FontArray.length;i++){
var font = FontArray[i];
$('#view_container').append("<button class='b_font' id='"+font+"' onclick='saveMe("+font+");'>"+font+"</button>");
$('.'+font).css('font-family',font);
}
// event.preventDefault();
});
And the function saveMe is defined as follow :
function saveMe(font){
alert(font);
}
But when i click any of the button i get the following error :
Uncaught ReferenceError: saveMe is not defined
Can anyone help me on this ?
Thanks in advance!
The line
onclick='saveMe("+font+");'
renders as
onclick='saveMe(arial);'
So when you click on it, it is looking for a variable arial not the string "arial". You need to quote it.
onclick='saveMe(\""+font+"\");'
Now for saveMe not being defined, that needs to have more context. When is saveMe defined? If it is inside of a document ready/window onload method, than you need to put it outside of it so it is available in window scope.
And the line
$('.'+font).css('font-family',font);
Should probably be
$('#'+font).css('font-family',font);
The most important thing is where the saveMe function is defined. onclick has only access to global scope and that's there the fuction would have to be for this solution to work.
That'd be a quick workaround:
window.saveMe = function (font){
alert(font);
}
However, you should note that cluttering global scope is usually undesirable and quickly leads to errors. It's better to attach events to selected elements by using .click(). In your code - you can attach the element and then bind click event to it.
var $button = $("<button class='b_font' id='"+font+"' onclick='saveMe("+font+");'>"+font+"</button>");
$('#view_container').append($button);
$button.click(function () {
alert($(this).attr('id'));
});
EDIT: As epascarello also pointed out - the string is not escaped properly
I'm guessing saveMe is out of scope, you probably put it inside the DOM ready handler.
As you're using jQuery, why not use it, and get rid of those inline event handlers
$(function() {
$('.font').click(function() {
$('#view_container').append(
$.map(FontArray, function(index, font) {
return $('<button />', {
'class' : 'b_font',
id : font,
on : { click : saveMe },
css : { fontFamily : font }
})
})
)
});
function saveMe() {...}
});
You could simply add this code and get rid of the code in the markup:
$('#view_container').on('click','.b_font',function(){
saveMe($(this).text());
});
OR perhaps better make this change:
$('#view_container').append("<button class='b_font' id='"+font+"' data-fontsave='"+font+"'>"+font+"</button>");
then this works and is less prone to error perhaps:
$('#view_container').on('click','.b_font',function(){
saveMe($(this).data('fontsave'));
});

passing the value from a textbox to another function

I have an html textbox and get the value from it with the following code:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
I then attempted to pass that value to a different function
function loadPdf(pdfPath) {
var pdf = PDFJS.getDocument(pdfPath);
return pdf.then(renderPdf);
}
loadPdf(value);
But the value isn't being passed. I then attempted to do the following:
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
to see if the value was displayed, but that didn't work either (didn't get any output)
EDIT: I do get an error in the console:
ReferenceError: $ is not defined
And if I remove the $ it says ('#getTextBoxValue).on is not a function
$ is a reference to jQuery. This works for me if jQuery is included:
<input id="textbox1"></input>
<button id="getTextBoxValue">Get value</button>
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
JSFiddle example
If you wanted to do it without jQuery, use document.getElementById("textbox1").value; and add the onclick either inline or via normal javascript also:
document.getElementById("getTextBoxValue").onclick = function(){
var value = document.getElementById("textbox1").value;
alert('The Value in Textbox is '+value);
};
After you get that to work, just replace the alert with loadPdf(value);
the var value is local to the onclick function, so has to be accessed inside of that function or made global.
Once you have jQuery loaded on the page, it should be as easy as calling your helper function inside the click event.
$('#getTextBoxValue').on("click", function(){
loadPdf( $("#textbox1").val() );
});
You've tagged this as javascript but The code you are using to grab your values and bind your functions is jQuery. The error you are getting is telling you that there is no mapping of "$" to jQuery. If you want to make sure you have the reference set, you can replace the $ with the string "jQuery" so $('someselector') becomes jQuery('someselector').
BUT, this may just be the console you are using. You have another error which is probably the issue. You have this:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
In this your value is locally scoped in the callback. Unless you do something with it before the function exits, you lose it completely. If you intend to do something with it later, you have to globally scope it by bringing it out of any function definition.
var value;
...
function someFunction(){
...
$('#getTextBoxValue').on("click", function(){
value = $("#textbox1").val();
});
}
The reason for this is due to scope.
You are defining your variables within the function with var.
$(document).ready(function() {
var value;
var pdf;
var value;
/* Then do your functions. This will make then global.
When you type then within your functions do not put var in front of them */
});

Give an object which calls a function

I'm new in jQuery and i'm trying to give an object which triggers a function and gets its parent's ID. I have HTML:
<tr id="9"><td>First</td><td class="edit"></td><td class="delete" onclick="DeleteMaster(this)"></td></tr>
And jQuery function:
function DeleteMaster(f){
var master = f.parent().attr('id');
alert (master);
}
But i'm getting an error:
Uncaught TypeError: Object # has no method 'parent'
What's wrong?
You're passing in the DOM element, you need to convert this to a jQuery object:
function DeleteMaster(f){
var master = $(f).parent().attr('id');
alert (master);
}
BUT
You shouldn't declare onclick handlers like that. It's bad practice and can lead to hassle if you want to change it in the future. The standard jQuery way of doing things is:
// Wait for DOM to become ready
$(function() {
// This replaces your "onclick" and "DeleteMaster" function
$(".delete").on("click", function() {
// Now you can access that <td> by calling $(this)
var master = $(this).parent().attr("id");
});
});
That way, you don't have to add code into your HTML markup.
It is because f is not jquery object. You should use $(f) .Try this:
function DeleteMaster(f){
var master = $(f).parent().attr('id');
alert (master);
}
Demo

Javascript Namespace + onchange = impossible?

I am using a namespace for my javascript code, and I think I have hit a brick wall with a onchange attribute for a select element. When I attempt to call a function with (or without) my namespace the error console is reporting that the function is not found.
var MYNS = {}; //namespace
MYNS.modifySearchPage = function () {
....
var eSelect = document.createElement("select")
.....
eSelect.setAttribute('onchange', 'MYNS.handleChange(this)');
.....
//set up the options (value, textcontent, eSelect.appendChild(theOption)
...
// add the eSelect to the DOM
}
MYNS.handleChange = function (select) {
//parse the select options
}
The result I get in the console when I select an item from the dropdown list is:
Uncaught ReferenceError: MYNS is not defined
I have attempted to add the namespace to the windows but that does not seem to help (and I'm not convinced that is a safe thing to do).
I have tried adding a onclick handler to the select element but obviously that is a bad idea as select does not handle onclicks.
Stripping the MYNS from both the call and function definition also didn't help.
Any ideas?
Thanks,
mwolfe
Don't use attributes to attach handlers - use properties:
eSelect.onchange = function() {
MYNS.handleChange(this);
};
More generically you could also use the standard and more recommended addEventListener:
function changeHandler() {
MYNS.handleChange(this);
}
if (eSelect.addEventListener) {
eSelect.addEventListener('change', changeHandler, false);
} else if (eSelect.attachEvent) {
eSelect.attachEvent('onchange', changeHandler); // fallback for IE
}
It's also worth noting that you can call
eSelect.addEventListener('change', MYNS.handleChange, false);
You will need to modify your callback though - the argument passed will be an event object and this inside the function will refer to the element that triggered the event.
You just code a different word of wrong case MyNS.handleChange, it should be MYNS.handleChange. In JavaScript variables are case sensitive.

Categories

Resources