Adding OnClick Event with Javascript is not working - javascript

I'm trying to add an onclick event with JavaScript.
$.getJSON(api , function(data) {
//First Option found (not working)
//document.getElementById("today_button").SetAttrribute("onclick", "window.location.replace('" + data[1] + "')");
//Second Option found (not working either)
document.getElementById('today_button').onclick = "window.location.replace('" + data[1] + "');";
});
The Variables exist, the Event is fired, the data transmitted are correct and everything except this works just fine (like altering the disabled state of exactly this button).
I hope you can help me

You need to assign a function to onclick, not a string:
document.getElementById('today_button').onclick = function(event) {
window.location.replace(data[1]);
}

Why are you assigning a string as a click handler? Just use a function.
document.getElementById('today_button').onclick = function () {
location.replace(data[1]);
};

The problem is you assigned string to onclick, but it needs function.
document.getElementById('today_button').onclick = function() {
window.location.replace(data[1]);
}

Related

Cannot Pass event When Using JQuery Click()

I can't get data from event.data when using the click function below. If I put "event" in the click(smedata, function(event){}) it doesn't fire. If I remove event it does fire. I've done this hundred times in the past but for whatever reason it doesn't work this time. All I can think is that this code is generated during a callback from closing a dialogue window and that is some how interfering. Appreciate any help.
//This is a callback function in a library that gets called after a dialogue
//window from SharePoint SP.UI.Dialogue gets closed.
OESme.prototype.CloseCallback = function(result, target){
console.log("callback");
try{
var targetArray = target.split(";#");
}
catch(e){
}
//object to be passed to click event
var smedata = {
smejson: target,
id: targetArray[0],
title: targetArray[1],
rank: targetArray[2],
firstname: targetArray[3],
lastname: targetArray[4]
}
var smeID = "smedata" + smedata.id;
var smeIDJQ = "#" + "smedata" + smedata.id;
$("#SMEAddedBox").append(
'<div class="smeitem">' +
'<span id="' + smeID + '">x</span>' + smedata.title +
'</div>'
);
//*******************
//When clicking the x it is suppose to remove itself
//If event is a parameter in the function, it won't fire, if event is removed it fires, but I can't use the object I am trying to pass
//********************
$(smeIDJQ).click(smedata, function(event){
console.log(event.data);
$(this).parent().remove();
});
}
It doesn't look like you're referencing $(smeIDJQ) properly. Also, use .on instead. Like $('#smeIDJQ').on('click', function(){};
All my code was correct. The problem has to do with SharePoint SP.UI.Dialogue.js. All the javascript and jQuery was correct but it was running in the Dialogue window. Basically there are two separate pages running on one page. When the dialogue window closes after the callback the Console in Internet Explorer 11 breaks and doesn't realize that it is suppose to focus on the parent page instead of the child. So it doesn't receive console logs like it should. Closing the Developer tools and reopening (F12) allows the window to refocus the parent properly.

Tracking users last form field on page unload

I am trying to store the last page and the last form field that the user was focused on prior to his unexpected exit from the page (did not click continue), but my solution is not working.
I am using the onbeforeunload event on the pages themselves, I fully realise that this event does not work consistently across all the browsers, but I could not figure out a way to this in an another way.
window.onbeforeunload = function () {
if (fieldName != null && fieldName.length > 0) {
var formName = location.pathname.substring(1);
if (typeof (TrackFormField) == 'function') {
try {
TrackFormField(formName, fieldName);
}
catch (err) {
}
}
}
};
TrackFormField is function in a separate file that just assigns the value to the property
function TrackFormField(formName, fieldName) {
if (formName) {
s.prop23 = formName + ":" + fieldName;
}
sendOmniture();
}
And sendOmniture does the following:
function sendOmniture() {
var s_code = s.t(); if (s_code) document.write(s_code)
}
The weird thing is that at times it works, but usually I don't see the prop23 neither in the analytics debugger nor in Fiddler.
After some debugging I found out that s_code for some reason is undefined in the send omniture function.
What can I do to fix this issue ?
My guess is the window.onbeforeunload event will kill the (s) object in most cases before it has a chance to execute.
What about using a Direct Call rule with Adobe DTM that will fire your function on focus change? That way you don't need to tie any action to the onbeforeunload event.
Hope this helps.

HTML5 Local Storage - multiple removeItem issue

I'm fiddling about with HTML5 local storage (not had much of a chance to play with it before) and I thought I'd make a little note-taker sort of thing.
I have a function which reads what's in the local storage and displays it on the page, which works fine until you try and delete more than one entry.
function renderNotes() {
$(currentNotes).html('');
Object.keys(localStorage);
Object.keys(localStorage).length;
$.each(localStorage, function(key, value){
$(currentNotes).append('<div class="note"><div class="noteHeader"><p class="noteName">' + key + '</p></div><div class="noteContent"><p>' + value + '</p></div></div>');
});
alert('notes rendered');
}
Go to the JSFiddle: http://jsfiddle.net/AThomas92/MSxQ9/3/ and try deleting some entries by clicking on the bold headers below the form - the first time it works fine, but after that it doesn't work at all.
The weird thing is, the function is also called when you add a new note, and it works over and over again.
Any ideas?
Thanks in advance,
Ash
Since the elements are re-rendered dynamically, you need to use event delegation
// DELETE NOTE
$(document).on('click', '.noteName', function(){
var noteName = $(this).html();
localStorage.removeItem(noteName);
renderNotes();
});
Demo: Fiddle
In addition to Arun P Johny's answer, here is an hint for your use of jquery :
Instead of using jquery object like the following :
var saveBtn = $('#saveBtn');
$(saveBtn).click(function(){
// Code
});
Use it like that :
var saveBtn = $('#saveBtn');
saveBtn.click(function(){
// Code
});
Or even better (to remember that it is a jquery object) :
var $saveBtn = $('#saveBtn');
$saveBtn.click(function(){
// Code
});

insertAfter() is duplicating an element when I don't want it to

Okay, so I'm making a chatbot, and I ran into a problem. So I need to make a function that creates a chat message everytime the enter key is pressed. So far, it's coming out nicely, just one problem. It's duplicating an element, that I only want one of.
To see what I'm talking about, go to http://jsfiddle.net/MatthewKosloski/BHXMa/ and type out a message, then hit enter. Notice how there are two "Foo!" messages? I only want one. I'd also want to make these messages go from top-bottom in chronological order, but I can't do that until I find out why this duplication is occuring!
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var robotMessage = userMessage;
function intelResponse(){
// ROBOT
var robot = document.createElement("h4");
var robotText = document.createTextNode("Robot");
robot.appendChild(robotText);
robot.className = "rtitle";
document.body.appendChild(robot);
insertAfter(userMessage, robot);
// Robot's response
robotMessage = document.createElement("span");
var robotMessageText = document.createTextNode("FOO");
robotMessage.appendChild(robotMessageText);
robotMessage.className = "rmsg";
document.body.appendChild(robotMessage);
insertAfter(robot, robotMessage);
}
A very simple mistake . You are calling the method intelResponse twice. Fixed the issueFIDDLE
if (e.keyCode == 13) {
submitUserMessage();
//intelResponse();
$("#user-input").val("");
}
You're calling "intelResponse" from the "submit" routine, and also explicitly after you call the "submit" routine.
The problem lies at the end of submitUserResponse function, where you also calling intelResponse
The message is appending twice because you call the function twice.
One time on keyup:
$(document).keyup(function (e) {
if (e.keyCode == 13) {
submitUserMessage();
intelResponse();
$("#user-input").val("");
}
});
And in the submitUserMessage.
Comment one of those and it doesnt duplicate: http://jsfiddle.net/BHXMa/2/

Get source of blur when invoked with jQuery

I have a form (for user registration) that's paginated via splitting it up into divs that are hidden/displayed with .slideUp()/.slideDown(). It all works pretty well, but I want to validate each page with javascript before they proceed to the next page to reduce the number of errors that come back from the server-side validation. Right now I have them set to validate onblur. To check all the elements when the "next" button is clicked, I want to use .blur() to force it to validate each input, but I'm getting an error. An example of my onblur function is:
var validateEmpty = function() {
var $src = $('.registrationPage #' + event.srcElement.id);
validate($src, "Can't be left empty!", checkEmptyRequired);
}
It's being bound by setting the onblur attribute to the function.
Where validate is a function that takes a jQuery object, an error message, and a function that returns a boolean. The error I get is
TypeError: Cannot read property 'srcElement' of undefined
So it seems clear to me that .blur() doesn't trigger a javascript event and simply calls the onblur function. How can I get the id of a blurred element in a way that will work both when blurred normally (by losing focus in the page) and with .blur()?
You're not showing us how the function is called, but you should probably pass the event as a parameter, otherwise it will be undefined in some browsers (but not in IE):
var validateEmpty = function(event) {
var $src = $('.registrationPage #' + event.target.id);
validate($src, "Can't be left empty!", checkEmptyRequired);
}
that would work with something like:
$('.elements').on('blur', validateEmpty);
Also, srcElement is rarely used (it's IE specific), I think jQuery normalized target, but you could always do something like this to make sure:
var target = event.target || event.srcElement;
It looks like your code is written to work in Internet Explorer only ?

Categories

Resources