How do I get a button to trigger a javascript function? - javascript

I have a C#/.NET web application I am working on. On one of the pages I have a table of values generated from a database. I need each value to be clickable so that when you click a value it filters data in a separate table next to it.
So what I decided to do was to make each value into a button:
<input type="button" id="exampleID" class="exampleClass" value="#Model.Data.Value1" />
In my Javascript I have this:
$(".exampleClass").click(function () {...
The code inside the function isn't relevant to the question because it isn't getting called when I click the button. Each button has a unique ID that I am using in my function and I gave them each the same class so that I can catch when any of them are called and then use their unique ID to determine which was clicked. I have set a breakpoint inside the function using Firebug but it's not getting tripped when I click the button. I am stumped as to why this isn't working.

Could be any number of things: are you attaching the click event in the ready method? Is jQuery even loaded on the page? Have you tried refining the selector? For example, $('input.exampleClass').click(). It has to be some dumb mistake.

Related

How can I share javascript/html among several elements on a page?

I have web page with two textboxes on it. Upon clicking on the first, I have a bootstrap modal that displays with a searchable treeview. You click an item in the treeview, the modal closes, and the selection appears in the textbox. Works perfectly!
Now I have decided that for the other textbox I want to do the same thing. The only difference is the modal has a different title, and the source data for the modal treeview comes from a different endpoint. All the other javascript to support searching and highlighting within a treeview, opening and closing a modal, etc, is the same.
To get it to work, I duplicated all html for the modals and the js code and just changed the ID's to avoid clashes between the two. I cannot live with myself for doing this!
So in the end, I have some js and html that work together as a component that I want to reuse on a page among several textboxes or whatever type of widget I may create. How can I design my app so I can share this code and not duplicate it all over the page?
I think webcomponents is the way to go. You could create a component that receives the id and other needed data as parameters and then create instances of it...
There is a lot to unpack in this question. High level, to achieve what you're asking with JS…
You could:
Build a method that accepts an event object (or jQuery event object) as its argument; and handles extracting extracting data from the attributes of that element, setting the title, AJAXing the treeview, and returning the selection/setting the text box value
embed the unique data in data-attributes on each text box
set the click event listener to pass the event.target element, with its unique data- attributes to the method
Markup:
<input type="text" id="foo" data-endpoint="/path/to/endpoint_1" data-title="Modal Foo" value="" />
JS
function on_click_modal_spawning_textbox( event ) {
// get the salient data from the `data-` attributes on the `event.target`
// do modal stuff, programmatically replace the modal title, AJAX treeview, et cetera…
}
// assuming you're using jQuery, otherwise this would be a vanilla `.addEventListener()`
$( document ).on( 'click', 'input[ data-endpoint ]', on_click_modal_spawning_textbox );

How can I select this element with javascript?

I am trying to write an applescript application that logs into a website upon launching. So far I can successfully open Chrome, load the web page into the active tab, select and input the password, but I cannot click the submit button.
Below is the element on the page:
<button type="submit" class="btn btn--ac" alt="Login"
title="Login" tabindex="6"><i aria-hidden="true"
class="lush lush-locked"></i> Login</button>
My skill level in javascript is little to none, yet I cannot find a way to successfully select this item and click it. I have tried already using the TagName and ClassName but it does not work, perhaps my syntax is incorrect. Is there a way to do this without a ID type?
I have tried:
execute front window's active tab javascript
"document.getElementByClassName('btn, btn--ac').click()"
execute front window's active tab javascript
"document.getElementByTagName('button').click()"
I should note this script runs in Google Chrome.
Thanks for any help in advance.
First of all you're using a wrong function. It should be
document.getElementsByClassName
Try using: (Assuming the Submit button is the only button with class btn)
document.getElementsByClassName('btn')[0].click();
Here's basic definition of the function from Mozilla:
document.getElementsByClassName():
Returns an array-like object of all child elements which have all of
the given class names.
Hence, you get a list of elements. Hence, you select the first element in it (using the 0 as index), and then click on it.
The correct syntax in plain js to select an element by his class is:
document.getElementsByClassName('btn--ac');
With this you'll get an array with all elements with the class 'btw--ac'. In your case try this:
document.getElementsByClassName('btn--ac')[0].click();

Javascript only firing once

long-time lurker here asking my first public questions because I am truly stuck.
I'm working on a hosted shopping cart platform so I only have access to add code in certain designated divs. I have a javascript code that I'm calling externally (because inline is bad unless you have to, right?)
So my issue is, There is a <select> dropdown that I do NOT have direct access to change HTML and the silly shopping cart platform didn't give it an id, only the name attribute is set.
I need to clear the <div id="result_div"> when the <select name="ShippingSpeedChoice"> drop-down is clicked so I have:
$("[name=ShippingSpeedChoice]").change(function(e) {
$("#result_div").empty();
});
It fires once, but that's it. My question is, how do I make it fire EVERY TIME the <select name="ShippingSpeedChoice"> is clicked?
Here's all the relevant javascript (in case it's preventing #result_div from clearing somewhere):
$("[name=ShippingSpeedChoice]").change(function(e) {
$("#result_div").empty();
});
$("#btn_calc").click(function(e) { /// onclick on Calculate Delivery Date button
Thanks in advance, any help is appreciated!
If you want something to happen every time the element is clicked, use .click() rather than .change(). The latter only fires if they select a different value from the menu than it had before.
$("[name=ShippingSpeedChoice]").click(function(e) { $("#result_div").empty(); });
First of all, I'd probably try and setup the shopping cart select to have an id.
$("[name=ShippingSpeedChoice]").id = 'shopping_cart_select';
then try binding the "change" function to the element via it's id.
$('#shopping_cart_select').bind('change', function(){
//rest of code goes here
}
I still wasn't able to use the name attribute to call the function, so I found a way around it by using the id of the td the ShippingSpeedChoice dropdown was in:
$("#DisplayShippingSpeedChoicesTD").change(function(e) {
$("#result_div").empty();
And it fires every time now. Thank you so much for all your feedback & assistance - I still wish I could figure out how to use the name attribute rather than the id, but that will be a puzzle for another day!

Onclick event with an argument = Not implemented?

Hoping for some advice here, I'm quite new to javascript and coding in general so I'm sure there are better ways to do what I need, however any help much appreciated ....
I have a piece of javascript that creates a table, the amount of rows being dynamic.
When I call the javascript I'm passing a few bits of info over, and one of these is an array. The array contains in each element a long string of text.
So I create the table with X rows showing some identifying data. I also create a radio button for each row with an on click event. The idea being that when the user clicks on the radio button, then the long string from the array element will be displayed in a separate text box.
I have managed to get to the point that the table is created and that when the radio button is selected the onclick event fires and loads a piece of data into the txt box. However that piece of data is hardcoded (txtbox.value=array[1])
What I'm now trying to do is load the relevant string from the array, depending on what radio button is clicked.
If i change my onclick event to onclick=function(ID) and my function to function(ID) I'm getting an error 'Not implented'
It appears to be generated from the onclick event rather than the function ...
The following works :
R1.onclick=clicktest;
function clicktest()
{
txtbox.value=array[1]
}
The following generates the error
R1.onclick=clicktest(1);
function clicktest(id)
{
txtbox.value=array[id]
}
Apologies if this isn't so clear.
Using this code
R1.onclick=clicktest(1);
You're executing clicktest(1) and assigning the result as event handler.
You could change it by this in to make it work
R1.onclick = function() { clicktest(1) };

Datepicker initialization for class fields added after page load

I have fields where multiple extra fields can be added after the page loads (think education & work experience fields on job resumes). I am using this.
I can add a datepicker on the first field, but subsequent added fields do not access the datepicker, despite being cloned/essential duplicates of the original. I'm guessing that the datepicker only intializes on page load or for only one class on the page.
So on a page I initialize the datepicker:
$('.input-append.date').datepicker();
for a block of form code encapsulated by this class. OK for initial page load; and also OK if there is an error and the page reloads multiple fields previously input(there is a datepicker for all fields returned with any error). However, with another js function that adds new fields to the form, additional new fields do not have access to the datepicker. I do not see how to do this now, perhaps someone with more experience/wisdom can provide me a hint.
EDIT:
Simple enough: I simply added:
$('.input-append.date').datepicker();
to the code calling the new field. As to being the optimal solution I do not know, anyone who specializes in js can comment on that, and there are many other similar questions here I found once I expanded my search terms. However, good enough for me now in what I'm doing.
For elements which are being added on fly use data-provide="datepicker" attribute. It will be initialized lazily. For example if an input field is coming up in an ajax response and loaded in a container div. So in this case:
<input type="text" data-provide="datepicker" />
so when when you will load this ajax response it in cotainer div like
$('#container-div').html(ajax_response);
this will work.
In the same way if you are creating an element through jquery and appending it to some container (I think this is happening in your case), for example you have a function that creates textbox and append it to some container div and this function is called on click event of some element let's say it's button. Again data-provide attribute is the solution to this problem. For example
function createTextBox(){
var t = $('<input>').attr('data-provide','datepicker');
$('#container-div').append(t);
}
And this function is called on click event of some button like in this way:
$(document).ready(function(){
$('#someBtn).click(createTextBox);
});
In short whether that dynamic element is coming in ajax response as a string or being created through jquery, just use data-provide attribute to set bootstrap datepicker. Because in this case datepicker is initialized lazily in Bootstrap fashion.

Categories

Resources