How to pass a value from textbox into a jQuery function? - javascript

I'm trying to figur out how I can set the var number and then use it in my other function Custom.init(number); and make it stay on the page.
//Set number onclick
function setVar() {
var number = document.getElementById("textbox").value;
//Pass in number
jQuery(document).ready(function() {
Custom.init(number);
});
};

If you're using jQuery, the ready function should wrap all other functions as it will be invoked first and foremost.
$(document).ready(function(){
var number = document.getElementById("textbox").value;
//Then do your validation here
var setVar = function(){
Custom.init(number);
//whatever else is involved with this
}
})
If that doesn't work I'd check the console for a specific error and ensure your Custom.init function is working as expected.

It doesn't make sense to hide the ready handler inside a function. The comments in your code do also suggest that you wish to call Custom.init in response to a mouse click on some element. You would register an event handler to this end.
A suggested streamlining:
//Set number onclick
$(document).ready(function() {
$(<selector for clickable elements>).on (
"click"
, function (eve) {
Custom.init(parseInt($("#textbox").val()));
1;
}
);
});

Related

Embed javascript function within another javascript function

I have a form with a conditional field that is only shown if the user selects a radio button for "other." If I remove the conditional on this field, my original javascript function works; however, with the conditional I can not get it to fire correctly.
The form has an event "cf.add" that fires when a conditional field is made visible, and using this jquery I get a correct response in the console:
jQuery( document ).on( 'cf.add', function(){
console.log('cf.add triggered' );
});
And if I remove the conditional so that this field is rendered when the page is rendered, I get the correct response in this field, which is to add a '$':
$("#fld_3169487_4").on("blur", handleChange);
function handleChange() {
var myValue = document.getElementById("fld_3169487_4").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("fld_3169487_4").value = myValue;
}
I've tried putting this second function within the first, but no luck. I feel like I'm adding them in the incorrect order when I try to combine the two, I'm not sure what I'm doing wrong though.
I've also tried to call the function handleChange() on the 'cf.add' trigger, but that did not work for me either.
After some playing around, I figured it out:
jQuery( document ).on( 'cf.add', function(){
var otherField = $("#fld_3169487_3");
otherField.focus();
var dollarValue;
$(otherField).on("blur", function() {
dollarValue = otherField.val();
if (dollarValue.indexOf("$") != 0) {
dollarValue = "$ " + dollarValue;
}
$(otherField).val(dollarValue);
});
});
Since cf.add is an custom even that is published by your form, you can have other elements subscribe to the event:
$("#fld_3169487_4").on('cf.add', function(event){
if ($(this).val().indexOf("$") != 0)
{
$(this).val("$" + $(this).val());
}
});
Using $(this), we can target just the field the event is attached to. Additionally, data from the event publisher can be passed to the subscribers via the event argument.

How can I observe changes to my DOM and react to them with jQuery?

I have this function where I toggle a class on click, but also append HTML to an element, still based on that click.
The problem is that now, I'm not listening to any DOM changes at all, so, once I do my first click, yup, my content will be added, but if I click once again - the content gets added again, because as far as this instance of jQuery is aware, the element is not there.
Here's my code:
(function($) {
"use strict";
var closePluginsList = $('#go-back-to-setup-all');
var wrapper = $('.dynamic-container');
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
wrapper.append(markup);
} else {
$('.plugins-container').hide();
}
});
//Below here, there's a lot of code that gets put into the markup variable. It's just generating the HTML I'm adding.
})(jQuery);
Someone suggested using data attributes, but I've no idea how to make them work in this situation.
Any ideas?
You could just do something like adding a flag and check for it before adding your markup.
var flag = 0;
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
if(flag == 0){
wrapper.append(markup);
flag = 1;
}
} else {
$('.plugins-container').hide();
}
});
If you want to add element once only on click then you should make use of .one() and put logic you want to execute once only in that handler.
Example :
$(document).ready(function(){
$("p").one("click", function(){
//this will get execute once only
$(this).animate({fontSize: "+=6px"});
});
$("p").on("click", function(){
//this get execute multiple times
alert('test');
});
});
html
<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p>

pass through current target name to function

I'd like to dynamically create event listeners for multiple buttons, and subsequently, show a particular frame label depending on the button clicked, but I'm unsure what to pass through (FYI, this is will be used for HTML5 canvas in Flash CC, but principally the same should apply to a web page for showing divs etc). I currently have this:
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
selfHome["btn" + i].addEventListener('click', openPop);
}
}
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
createListeners();
It creates the listeners fine, but I don't really know where to start with passing through the current button instance name to tell it which frame label to gotoAndPlay.
Based on the code that you have, I'd simply change the .addEventListener() to call a generic function (rather than openPop, directly), and pass it the reference to the button. So, this:
selfHome["btn" + i].addEventListener('click', openPop);
. . . would become this:
selfHome["btn" + i].addEventListener('click', function() {
openPop(this);
});
At that point, you would then have to update openPop to accept a parameter for the reference to the element that triggered it . . . something like:
function openPop (currentButton) {
At that point, you could reference the clicked button, by using currentButton in the openPop logic.
I'm not sure I totally understand your question. However if you just need to pass the button instance (in you case "selfHome["btn" + i]") you could call an anonymous function in your event handler which calls openPop() with the button instance as an arugment. Would this work for you?
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
var currentBtn = selfHome["btn" + i];
currentBtn.addEventListener('click', function(){openPop(currentBtn);} );
}
}
function openPop (btn) {
alert("test");
selfHome.gotoAndPlay(/*use button instance 'btn' to find frame*/);
}
createListeners();
When the event is triggered the this keyword inside the handler function is set to the element is firing the event EventTarget.addEventListener on MDN. If the button have the data needed to be retrieved just get it from the this keyword:
function openPop (btn) {
alert(this.name);
/* ... */
}
It looks like you expect it to contain the function gotoAndPlay() as well as the btn elements (which contain both an ID (of btn[number]) and a name with something special at substr(3) (I assume the same as the id). If those things were all true, it should work in chrome... in other browsers you'll need to add event to the openPop() method signature.
function openPop (event) {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
I believe this is what you are looking for and adding that one word should fix your problem (assuming some things about your dom and what selfHome contains):
JSFiddle
You could also leave out the event from openPop() and replace event.currentTarget with this:
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+this.name.substr(3));
}
JSFiddle

Get the latest value of a variable only

I have this code that creates a random number when click on the button (set number)
Then when you click on the other button (get number), it will retrieve the random number on alert
jQuery('.button1').on('click',function (){
var num = Math.random();
jQuery('.button2').on('click',function (){
alert(num);
});
});
Code in action http://jsfiddle.net/Jim_Toth/dYTEq/
The problem I'm facing is that when the user clicks on (set number) again to get a new number. Then clicks on (get number) the alert retrieves twice with the old number and the new number. If clicked them for the third time it will retrieve triple.
How do you retrieve the latest random number only?
You have your .button2 click handler defined inside your .button1 click handler. Make the num variable global and set it in the first, and then alert it in the second.
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});
See a working version here: http://jsfiddle.net/j8zGP/
Try
fiddle Demo
var num;
jQuery('.button1').on('click', function () {
num = Math.random();
});
jQuery('.button2').on('click', function () {
alert(num);
});
Problem
You are adding click handler in the .button1 click on .button2 so it is attached multiple times that's why you get many alerts
The problem is that with each click of button1 you are adding a new event handler to button2. Each time button2 is clicked it will run all attached event handlers, and that will be the same amount as the number of times your click button1.
Try separating your event registrations and use a global variable so both functions can access it...
var num;//global variable can be accessed by both functions
jQuery('.button1').on('click',function (){
num = Math.random();//sets the global variable ready to be used by other functions
});
jQuery('.button2').on('click',function (){
alert(num);//alerts the global variable, as set by the other function
});
Here is a working example
Don't use closures for this.
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});
http://jsfiddle.net/dYTEq/2/
var num;
jQuery('.button1').on('click',function (){
num = Math.random();
});
jQuery('.button2').on('click',function (){
alert(num);
});
The problem is, that you are adding the click event handler to the second button multiple times. Your code basically says "When button1 is clicked, add a click event handler to button2". But a new click event handler won't rmeove already existing click event handlers.
You could do this:
(function () {
var num;
jQuery('.button1').on('click', function (){
num = Math.random();
});
jQuery('.button2').on('click', function (){
alert(num);
});
}());
This way each event handler is only attached once. I added the function around that code so num won't be in the global (i.e. window) scope.

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

Categories