jQuery custom event not firing or triggering - javascript

Can anyone tell me what am I doing wrong in the given below code?
<script type="text/javascript">
$('#sp7').on("test", processData);
function processData(e){
recievedData=null;
recievedData[e.message[id]] = e.message;
return recievedData;
}
function testData(id,a){
temp = {id:id, a:a};
$.event.trigger({
type : "test",
message : temp,
time : new Date()
});
}
</script>
I am calling the testData on a button click:
<input type = "button" onclick="testData(1,'a1');" value="test1"/>

I don't know if you specifically need to resort to custom events. However, the event should be triggered on the dom element that is supposed to listen to it. Like
$('#sp7').trigger('test',[parameters]);

Related

jQuery nested functions

I am still new to JavaScript and jQuery, so I am confused as to why the following code is not working as I anticipated. All I am trying to do is save input on a button click (id=recordInput) and display it with another button click (id=displayInput). What I observe is that tempInput is stored, (the code works until that point) but assignment of displayInputs onclick attribute is not executed. My question is, can you not nest a $().click() call inside of another &().click() call?
<script>
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
</script>
My thinking is this in pseudocode:
assign recordInput onclick attribute to the following function:
store tempInput
set displayInput onclick to alert the tempInput value
what is wrong with my thinking?
NOTE: I did not include any html tags but all of the ids are referenced correctly
It's not working because you have put & instead of $ here
$('#displayInput').click(function(event) {
Fixing this may work, but you shouldn't set event handlers this way. Because every time your first handler function is called it will set an event handler for the second one. You can try with your console.log and you will see that the number of console.log is increasing by every click on #recordInput. So you should better set it like this :
var tempInput;
$('#recordInput').click(function(event) {
tempInput = $('#testInput').val();
});
$('#displayInput').click(function(event) {
console.log(tempInput);
});
I would change
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
to
$(function(){
var testInput = '';
$('#recordInput').click(function(){
testInput = $('#testInput').val();
});
$('#displayInput').click(function(){
if(testInput !== ''){
console.log(testInput);
}
});
});
You are using & instead of $. Of course, you don't have to format the code exactly like I did.

Backbone Event Map Doesn't Recognize Classes

Stack.
I'm using Backbone's event map in my View.
JS:
events: {
"click .edit-info-button": "pullEdits"
},
pullEdits: function(e){
// Get the value of the button clicked
e.preventDefault();
$(".edit-info-button").click(function(){parseEdits(this.value);});
}
HTML:
<button class="button edit-info-button" value="edit address">EDIT</button>
When edit-info-button is a class, the event listener does not work. pullEdits() never fires.
When I change edit-info-button into an id ("click #edit-info-button", "button id='edit-info-button', etc.) pullEdit() and all functions after it run successfully.
The issue is, the page I'm working on needs multiple edit buttons and I'd like to give them the same class and pull the value instead of giving them all unique ids.
Am I missing something? Thanks.
Try this instead.
...
events: {
"click .edit-info-button": "pullEdits"
},
pullEdits: function(e){
var val = $(e.target).attr('value')
return parseEdits( val );
}
...

Javascript oninput(setTimeout 2s) / onchange - fire that comes as first

Hi I have a function Save that's triggered onchange event or oninput after 2s timeout.
Problem is that function Save is triggered twice in this scenario:
type something
wait 2s
oninput fires save event
click out of input
onchange fires save event
I need save only once depending on what happens first. If user types something and immediately leaves input, then save via onchange and oninput timeout should be cancelled. But if types something and waits 2s then save via oninput and onchange shouldn't be triggered.
I need some simple and clean solution. Does it exist? Thanks :)
edit:
here is my code http://jsfiddle.net/TQ9KR/
jQuery('#text').on('change', function() {
save();
});
jQuery('#text').on('input', function(){
clearTimeout(this.delayer);
var context = this;
this.delayer = setTimeout(function () {
jQuery(context).trigger('change');
}, 2000);
});
function save(){
jQuery('#a').text('saved on ' + new Date().getTime());
}
You could set a flag to indicate whether save is needed:
jQuery('#text').on('change', function() {
save();
});
jQuery('#text').on('input', function(){
jQuery(this).data('unsaved', true);
clearTimeout(this.delayer);
var context = this;
this.delayer = setTimeout(function () {
jQuery(context).trigger('change');
}, 2000);
});
function save(){
if (jQuery('#text').data('unsaved')) {
jQuery('#a').text('saved on ' + new Date().getTime());
jQuery('#text').data('unsaved', false);
}
}
Demo: http://jsfiddle.net/TQ9KR/1/
Update: for your requirement of dealing also with changes to the field value from other JavaScript functions you could do the following instead (keeping your original 'change' and 'input' handlers:
function save(){
var $text = jQuery('#text');
if ($text.data('prevVal') != $text.val()) {
jQuery('#a').text('saved on ' + new Date().getTime());
$text.data('prevVal', $text.val());
}
}
That is, only save if the current value of the field is different to whatever was saved last time (where the first time around it will automatically be different since there will be no previously saved value).
Demo: http://jsfiddle.net/TQ9KR/2/
Could you not add a data attribute, something like data-hasChanged and check that?
well honestly only cleen solution that i can think of is to initialize global boolean variable that indicates has save hapen
var hasSaveHapen = false;
and now when any of those functions try to save use this:
if(!hasSaveHapen){
do your save action
hasSaveHapen = false;
}

SharePoint add Javascript event to a editForm.aspx page

I have a Sharepoint list where I want to customize the editForm.aspx page with Javascript.
The problem is that I can't manage to add any events to the controls in that page. I am able to get a reference to my control with this code:
var textarea1;
var objForm = document.forms[0];
function FindField() {
var title;
title= $().SPServices.SPGetDisplayFromStatic({ listName: "MyList", columnStaticName: "mycolumn" });
textarea1 = ChooseFieldByTitle("TextField", title);
}
function ChooseFieldByTitle(TypeField, title) {
var elem;
for (idx = 0; idx < objForm.elements.length; idx++) {
elem = objForm.elements[idx];
if (elem.id.indexOf(TypeField) != -1 &&
elem.title == title) {
return elem;
}
}
return null;
};
This runs fine but I can't attach any event on this control. I have tried the following code (Field is a textArea):
Field.attachEvent("onchange", myFunction);
Field.addEventListener("onchange", myFunction, false);
Field.onchange = myFunction() {};
When I change the content of the textArea nothings happen. When I debug with IE developers tools "myFunction" is never called. What am I doing wrong? I have look at SPServices JQuery library but nothing seems to be related to Javascript events.
Does anyone have a clue?
Try to use Jquery, this is a Javascript library that is used a lot. It makes for instance selecting objects easier. If you want to combine it with spservices (or another library), add the following lines in your aspx page under the PlaceHolderMain:
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<script language="javascript" type="text/javascript" src="/SiteAssets/js/jquery-1.9.0.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/js/jquery.SPServices-0.7.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/js/myjavascriptfile.js"></script>
You can then select objects on your page via jquery and immediately tie to the events e.g.:
$(":input[title$='atitleofsomefield']").keyup(function() {
// do stuff
})
Here is a list of Jquery events: http://api.jquery.com/category/events/
The "onchange" event is fired by a dropdown box when you select a new value. It won't fire for a Textarea. In your case you may want to check the KeyUp event for example, or the Blur event.
Also, you may want to use jQuery or another library to handle the events.
The only way that I have found to accomplish this is via a timer. Look at something like this:
$(document).ready(function() {
var initialValue = undefined;
Field.on('change', function(){
//If the value has changed, run the function
if(initialValue==undefined || Field.val()!=initialValue){
initialValue = Field.val();
myFunction();
});
//Reinitialize the timer
checkForChange();
});
//Timer function to throw the 'changed' event
function checkForChange() {
setTimeout(triggerChange, 1500);
}
//Send the changed event for Field
function triggerChange(){
Field.trigger('change');
}
And then within your function you do your regular logic.

Need to sent onclick event string var from hyperlink to javascript event function(e)?

Can someone tell me how i can sent a string from an onclick event to the searchfunction?
onclick="SearchFunction("mystring"); -->This doesnt works.
$(document).ready(function() {
var SearchFunction = function(e) {
searchwords=$("#q").val();
STR=??? -->Needs to get the string from the onclick hyperlink.
};
$("#q").keyup(SearchFunction);
});
$(this).text() should do it.

Categories

Resources