Button click pass argument to callback - javascript

I have this code , very simple , not working :
$(function() {
$(document).on('click', '#NetworkSearch', NetworkMarketSearching("NETWORK"));
$(document).on('click', '#MarketSearch', NetworkMarketSearching("MARKET"));
$(document).on('click', '#CableSearch', NetworkMarketSearching("CABLE"));
});
you can see - I am very simply using .on() to make NetworkMarketSearching() fire from a click, here is the function. This function works just fine on its own if called from the console.
function NetworkMarketSearching(types) {
var name, searchType;
if (types == 'NETWORK') { name = $('#NetworkName').val(); searchType = 0; }
else if (types == 'MARKET') { name = $('#MarketName').val(); searchType = 1; }
else if (types == 'CABLE') {name = $('#CableName').val();searchType = 2;}
$.ajax({
type: 'POST',
url: '/Talent_/Common/NetworkMarketSearch',
dataType: 'json',
data: { 'name': name, 'searchType': searchType },
success: function(data) {
}
});
}
The error is 'undefined is not a function' it repeatedly happens when putting NetworkMarketSearching('NETWORK') in the line of .on('click', ...

try this:
$(function() {
$(document).on('click', '#NetworkSearch', function() { NetworkMarketSearching("NETWORK"); });
$(document).on('click', '#MarketSearch', function() { NetworkMarketSearching("MARKET"); });
$(document).on('click', '#CableSearch', function() { NetworkMarketSearching("CABLE"); });
});
The click method doessnt support the string parameter, it expects the event object parameter.

This NetworkMarketSearching("NETWORK") calls the function immediately and attempts to assign its return result (which is undefined) as the callback.
You can use the data argument to pass information to your function calls:
$(function() {
$(document).on('click', '#NetworkSearch', { types: 'NETWORK' }, NetworkMarketSearching);
$(document).on('click', '#MarketSearch', { types: 'MARKET' }, NetworkMarketSearching);
$(document).on('click', '#CableSearch', { types: 'CABLE' }, NetworkMarketSearching);
});
Then the function definition would be:
function NetworkMarketSearching(event) {
and, within the function, the types would be referenced as
event.data.types
This is the way the jQuery docs specify passing arguments to the callback, but it can be done also with an inline anonymous function. That is to say, like this:
$(function() {
$(document).on('click', '#NetworkSearch', function () {
NetworkMarketSearching('NETWORK');
});
$(document).on('click', '#MarketSearch', function () {
NetworkMarketSearching('MARKET');
});
$(document).on('click', '#CableSearch', function () {
NetworkMarketSearching('CABLE');
});
});

Are you sure the function exists at the moment you call it?
Try go simple, use this sample of jquery site (http://api.jquery.com/on/):
function notify() {
alert( "clicked" );
}
$( "button" ).on( "click", notify );
then you pass a parameter, if it works you move to your code.

Related

change event doesn't work on dynamically generated elements - Jquery

I generate a dropdownList dynamicly with jquery Ajax , generated dropdown's id
is specificationAttribute . I want create add event for new tag was generated (specificationAttribute) , to do this I created Belowe script in window.load:
$(document).on('change', '#specificationattribute', function () {
alert("Clicked Me !");
});
but it does not work .
I try any way more like click , live but I cant any result.
jsfiddle
Code from fiddle:
$(window).load(function () {
$("#specificationCategory").change(function () {
var selected = $(this).find(":selected");
if (selected.val().trim().length == 0) {
ShowMessage('please selecet ...', 'information');
}
else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: { categoryId: categoryId, controlId: 'specificationattribute' },
type: 'POST',
success: function (data) {
$('#specificationattributes').html(data);
},
error: function (response) {
alert(response.error);
}
});
}
});
$(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});
}
Your fiddle has syntax errors. Since a dropdownlist generates a select, let's use one.
For my answer I used THIS HTML, more on this later: things did not match in your code
<select id="specificationAttribute" name="specificationAttribute">
</select>
Code updated: (see inline comments, some are suggestions, some errors)
$(window).on('load', function() {
$("#specificationCategory").on('change',function() {
var selected = $(this).find(":selected");
// if there is a selection, this should have a length so use that
// old: if (selected.val().trim().length == 0) {
if (!selected.length) { // new
// NO clue what this is and not on the fiddle so commented it out
// ShowMessage('please selecet ...', 'information');
alert("select something a category");// lots of ways to do this
} else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: {
categoryId: categoryId,
controlId: 'specificationattribute'
},
type: 'POST',
success: function(data) {
// THIS line id does not match my choice of specificationAttribute so I changed it
$('#specificationAttribute').html(data);
},
error: function(response) {
alert(response.error);
}
});
}
});
// THIS should work with the markup I put as an example
$(document).on('change', '#specificationAttribute', function() {
alert("changed ");
});
});// THIS line was missing parts
#Uthman, it might be the case that you have given different id to select and using wrong id in onchange event as i observed in the jsfiddle link https://jsfiddle.net/a65m11b3/4/`
success: function (data) {
$('#specificationattributes').html(data);
},and $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
}); $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});.
It doesnt work because at the moment of attaching event your html element doesnt existi yet.
What you need are delegated events. Basically, you attach event to parent element + you have selector for child (usually by classname or tagname). That way event fires for existing but also for elements that meet selector added in future.
Check documentation here:
https://api.jquery.com/on/#on-events-selector-data-handler
Especially part with this example:
$( "#dataTable tbody" ).on( "click", "tr",
function() {
console.log( $( this ).text() );
});

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

jQuery calculate hours function not working

I am trying to pass $(this) value to a jQuery function. The function is below but does not work. There are no errors in console.
The function is firing because when I place an alert at the top it works.
(function($){
$.fn.calculateHours = function() {
var tbody = $(this).closest('tbody'); // get closest tbody
var table = $(this).closest('table'); // get closest table
var params = table.find('.disguise').serialize(); // parameters
$.ajax({
type: 'post',
dataType: 'json',
url: '/calculateHours',
data: params,
success: function (response) {
// loop over object
$.each(response.rows, function(index, array) {
$.each(array, function(key, value) {
$('#row_' + index).find('.' + key).html(value);
});
});
if($.isPlainObject(response.columns)) {
$.each(response.columns, function(day, hour) {
$('.totalsRow').find('.total_' + day).html(hour);
});
}
$('.totalsRow').find('.grand_total').html(response.grand_total);
}
});
}
})(jQuery);
$(document).on('change', '.disguise', function(e) {
$.fn.calculateHours();
});
Adding functions to $.fn is meant to extend the jQuery object. In other words, you should be calling .calculateHours on your jQuery object:
$(document).on('change', '.disguise', function(e) {
$(this).calculateHours();
});
You want jquery to set the context automatically. To do that just pass a reference to the function as the handler.
$(document).on('change', '.disguise', $.fn.calculateHours);

Jquery click functions runs before clicking

I want my jquery to load a function when a button is clicked.
This works fine:
$(document).ready(function() {
$("#register").click(function() {
alert("button");
});
This one will show the test() function before the document loads:
$(document).ready(function() {
function test(param1, param2){
alert("param1: "+param1+" param2: "+param2);
}
$("#register").click(test("a","b"));
});
How can i fix this ?
$(document).ready(function() {
$("#register").click(function() {
alert("button
});
should be:
$(document).ready(function () {
$("#register").click(function () {
alert("button");
});
});
And
$(document).ready(function() {
function test(param1, param2){
alert("param1: "+param1+" param2: "+param2);
}
$("#register").click(test("a","b"));
});
should be
$(document).ready(function () {
function test(param1, param2) {
alert("param1: " + param1 + " param2: " + param2);
}
$("#register").click(function () {
test("a", "b");
});
});
$(document).ready() fires once the DOM is ready.
I think your problem is in this code:
$("#register").click(test("a","b")); // I suppose it is executing test().
you just pass the parameters through event handler like this.t allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.
$(document).ready(function() {
function test(e){
alert(e.data.param1); // returns "a"
alert(e.data.param2); // returns "b"
}
$("#register").click({param1 : "a" , param2 : "b"} , test);
});
More you want about event Handler Stack Overflow
The problem is in your click event handler. This is what you have:
$("#register").click(test("a","b"));
Here you are immediately executing the test("a","b") function. Instead you want to pass in a function that calls this. Therefore the corrected code is
$("#register").click(function (){
test("a","b");
});

How to call javascript function with parameter in jquery event handler?

I am stuck. Searched and tried for hours.
EDIT:
I still can't make it work. Okay, I'll just put the source code to make it clear what I want to accomplish.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
var date_fmt="yyyy-mm-dd";
var time_fmt="HH:MM";
var date_field="#id_start_0, #id_end_0"; //id refering to html input type='text'
var time_field="#id_start_1, #id_end_1"; //id refereing to html input type='text'
function clearFmt(fmt_type)
{
if($(this).val() == fmt_type) {
$(this).val("");
}
}
function putFmt(fmt_type)
{
if($(this).val() == "") {
$(this).val(fmt_type);
}
}
$(document).ready(function() {
$(date_field).attr("title",date_fmt);
$(time_field).attr("title",time_fmt);
$(date_field).click(function() {
clearFmt(date_fmt);
});
$(date_field).blur(function(){
putFmt(date_fmt);
});
$(time_field).click(function(){
clearFmt(time_fmt);
});
$(time_field).blur(function(){
putFmt(time_fmt);
});
});
</script>
Help ?
Use the jquery bind method:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").bind('click', { key: 'value' }, myfunc);
});
Also see my jsfiddle.
=== UPDATE ===
since jquery 1.4.3 you also can use:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").click({ key: 'value' }, myfunc);
});
Also see my second jsfiddle.
=== UPDATE 2 ===
Each function has his own this. After calling clearFmt in this function this is no longer the clicked element. I have two similar solutions:
In your functions add a parameter called e.g. element and replace $(this) with element.
function clearFmt(element, fmt_type) {
if (element.val() == fmt_type) {
element.val("");
}
}
Calling the function you have to add the parameter $(this).
$(date_field).click(function() {
clearFmt($(this), date_fmt);
});
Also see my third jsfiddle.
-=-
An alternative:
function clearFmt(o) {
if ($(o.currentTarget).val() == o.data.fmt_type) {
$(o.currentTarget).val("");
}
}
$(date_field).click({fmt_type: date_fmt}, clearFmt);
Also see my fourth jsfiddle.
The following should work as seen in this live demo:
function myfunc(bar) {
alert(bar);
}
$(function() {
$("#foo").click( function() {
myfunc("value");
});
});
anyFunctionName = (function()
{
function yourFunctionName1()
{
//your code here
}
function yourFunctionName2(parameter1, param2)
{
//your code here
}
return
{
yourFunctionName1:yourFunctionName1,
yourFunctionName2:yourFunctionName2
}
})();
$document.ready(function()
{
anyFunctionName.yourFunctionName1();
anyFunctionName.yourFunctionName2();
});
Note: if you don't use 'anyFuctionName' to declare any function then no need return method. just write your function simply like, yourFunctionName1().
in $document.ready section parameter is not issue. you just put your function name here. if you use 'anyFuctionName' function then you have to follow above format.
function myfunc(e) {
alert(e.data.bar); //this is set to "value"
}
$("#foo").click({bar: "value"}, myfunc);
People are making this complicated, simply call directly as you would in Javascript
myfunc("value");

Categories

Resources