How to have a function with event object and parameter - javascript

I show a page in a jQuery dialog box. The user fills in the fields and submits the form.
In the function I need to call e.preventDefault(). In the underlying code I used the RegisterStartupScript method on the submit button. I know how to do it by passing parameters:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, GetType(Page),
"Script", "OrderForm('Item.aspx?OrderNum=" & _ID & "');", True)
How can I pass an event object in registerStartupScript?
I want a function like this:
function OrderForm(e, number) {
e.preventDefault();
//do something using number;
}

The .click() method is part of a framework (in this case I'm pretty sure it's jQuery) and it accepts a predefined number of arguments. You can use (for example) a data- attribute in your button with the number and then access to it through the object this.
// html
<button data-number="3">my button</button>
// js
$('button').click(function(e){
e.preventDefault();
var number = $(this).data().number; // or $(this).data('number')
alert(number);
});
Try with this jsfiddle: https://jsfiddle.net/q3fvxk93/

the event object is in the scope $(this)
I don't know where number should come from.
So your code would look this
$('btn').click(function(e) {
e.preventDefault();
$(this).attr('id'); //the button and it's properties like attributes in this example I get the ID of the button
});

Related

How can I pass an object value name to a function in Jquery

I'm working with the JQuery Simple modal plugin and I would like to pass a Freemarker variable/object on the click of a link to my Jquery function.
As a test, I created an alert box to see if the value is being passed and it doesn't seem to work.
$(function() {
// Load dialog on page load
//$('#basic-modal-content').modal();
// Load dialog on click
$('#hey').click(function myName(uid) {
var x = uid;
alert(uid);
return false;
});
});
HTML
<div id="disclaimer${item.uid}">
Modal data
</div>
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
The alert box just comes up as a blank object. Any help would be appreciated. Thanks!
First off, you look like you are confusing the html onclick attribute with the jquery .click method.
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
This will call a javascript function named "myName" and pass it a the string ${item.uid}. Note, this is a string because you wrapped it in single quotes. If you do an alert, your alert will literally say "${item.uid}".
Then you have a jquery bind event for click:
$('#hey').click({....
Ok, you need to pick one. Either use the onclick to call a javascript function or use the bind click event. Both methods can work (I prefer javascript onclick functions myself but that is just opinion).
If you want to use the jQuery bind, put a debugger; line in it so that you can step through it easily and watch. I typically use e for my event variable and e.target gets the target of the event. It will look something like this:
$('#hey').click(function(e){
debugger;
alert($(e.target).attr('data-uid'));
});
--- edit---
Adding my note below here so it is easier to read.
One thing I like to do in my onclick functions is to pass the this pointer. This is especially useful if you have multiple of the same kind of node that are calling the same function.
<a onclick="myName(this)" id="hey2">Read the blog</a>
<a onclick="myName(this)" id="hey3">Read the blog</a>
then, in the javascript you function looks like:
function myName(ptr)
{
$(ptr).....
// do some stuff
}
try using this:
function myName(uid){
alert(uid);
}
You dont need to wrap it in a jquery event handler, because you are already calling it as an onclick event from your Freemarker template.
Alternatively, you could do something like this:
<a data-uid="${item.uid}" id="hey">...</a>
And have your javascript like this:
$('#hey').click(function(){
alert($(this).data('uid'));
}

Simple javascript to update a textbox when a button is hit?

I have a simple form that I'm playing around with and I'm trying to update a textbox value when a command button is clicked. The command button is called btnVerifyLocation and the textbox is called txtGeoLocation. I've attempted to do this in Javascript with the following:
The code I have is as follows:
<script type="text/javascript" id="testing">
$("btnVerifyLocation").click(function ()
{
$("input[name*='txtGeoLocation']").val("testing");
});
</script>
However when I click the button nothing happens.
A) You're missing a # in 'btnVerifyLocation' (I'm assuming that's its ID, otherwise if it's a class then use '.btnVerifyLocation'
B) Second, this should be in a $(document).ready(), otherwise you are trying to bind a click handler to a DOM element that hasn't yet been rendered.
Code should be as follows:
$(document).ready(function() {
$('#btnVerifyLocation').click(function(e) {
e.preventDefault(); // In case this is in a form, don't submit the form
// The * says "look for an input with a name LIKE txtGeoLocation,
// not sure if you want that or not
$('input[name*="txtGeoLocation"]').val('testing');
});
});
jQuery’s selector function uses CSS selector syntax, so to identify an object with an ID, you need to prefix the ID with a #:
$("#btnVerifyLocation").click(function () {
$("input[name*='txtGeoLocation']").val("testing");
});
Also just in case: You do have jQuery included, right?

How to pass dynamic values to event listener

I am using a server side technology (JSP) to render my views. Therefore I have a for loop that loops through a list. Now, I want to bind a click listener to a button that is rendered for each item in the list. The code in the click listener needs the item ID, which I don't understand how to pass to the JavaScript code.
I also use requirejs, if that matter to the solution.
Maybe you just don't need to pass the html ID to your javascript. You can use a css class to retrieve your buttons in your DOM. The javascript code depends of what framework you use.
In native javascript, you can retrieve your buttons like this :
var buttons = document.querySelectorAll('button.my_class');
Just replace my_class by what you want.
You can access a button id by doing this :
var button_id = buttons[0].id
If you want to attach the item id to the button, you can use a data attribute. For example :
<button id="my_button" data-id="item_id" />
In the javascript, you can access to data_id like this :
var item_id = buttons[0].getAttribute('data-id');
In most event handlers, this is the DOM node that triggered the event, so something like this works:
button.onclick = function() {
alert(this.id);
}
Here is the live example
If you were using jQuery and requirejs this would be like this:
require(['jQuery'], function ($) {
$('.container_element').on('click', '.button_class', function () {
console.log('You have clicked button with id ', $(this).attr('id'));
})
})

How to get the form of an element in jQuery

I have a javascript function that runs quite nicely from html
'onClick="my_function(this.form)"
but I also want to call this function if a specific element within the form has data keyed in I have tried
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form').options-i-have-tried();
my_function(myform);
});
});
options-i-have-tried() include html() (and that shows that I have html inside of the correct form ok),
get() a bit of a stab in the dark,
serializeArray() from some answers to similar questions,
and nothing at all.
In each case my function complains that its argument form, or more specifically form.myelement is undefined
Many thanks in anticipation
Well your passing the FORM Element into the function in the inline handler (onclick attribute) so you need to do the same with the jQuery handler.
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0]; //because the form element is at the first index in the jquery object
my_function(myform);
});
});
OR even better, why don't you just stick to doing this:
jQuery(document).ready(function($){
$('#option_field_bizpostcode').keyup(function() {
my_function(this.form);
});
});
I think you should be passing myform not form
this in a jQuery callback will be the element where the handler is attached. It is the native DOM element, without any jQuery wrapper.
So presuming that #option_field_bizpostcode is a form element, you should be able to do this.form just as you would in the onclick method.
my_function(this.form);
I think if you use the first element from the closest call you will be successful:
$('#option_field_bizpostcode').keyup(function() {
var myform = $(this).closest('form')[0];
my_function(myform);
});

Get the element triggering an onclick event in jquery?

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit();" type="button" value="Send" />
</form>
In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:
var form = $(this).parents("form");
where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?
EDIT - got the answer from #claudio below, for clarity here's the complete function and call:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit($(this));" type="button" value="Send" />
</form>
and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:
function confirmSubmit(caller) {
var form = caller.parents("form");
jConfirm('Are you sure?', 'Please Confirm', function(result){
if (result) {
form.submit();
} else {
return false;
}
});
}
You can pass the inline handler the this keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
Try this
<input onclick="confirmSubmit(event);" type="button" value="Send" />
Along with this
function confirmSubmit(event){
var domElement =$(event.target);
console.log(domElement.attr('type'));
}
I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.

Categories

Resources