I'm trying to get my program to create a new button on form submit. I know I've done something wrong but don't know how to fix it. Here is my code:
$("#searches").append('<button id="recent-searches">' + textbox + '</button>')
then later on I have:
$("#recent-searches").on('submit', function() {
I think the second part of the code is where I went wrong. Any help would be awesome.
Thanks!
There is no submit event for a button, did you mean click or submit event on a form?
Try
$("#recent-searches").on('click', function() { // if you are biding this after appending the button.
else
$(document).on('click',"#recent-searches" function() { // if you are binding this prior to appending the button to the DOM. use $("#searches").on(... if that element is available all the time in DOM.
if #searches is a form then you would do:
$("#searches").on('submit', function(){...
You're creating a button #recent-searches which will receive, among others, the event click when you click on it. However it won't fire submit events because those are just for form elements when an input element of type submit is clicked.
So you'd have a form, let's say:
<form id="searches"> ... </form>
Where you are appending the button, maybe this way:
$("#searches").append('<input type="submit" id="recent-searches">' + textbox + '</input>');
, and then you'd do:
$("#searches").on("submit", function (e) { ... });
Or you can also have your button but bind a click event instead like so:
$("#recent-searches").on("click", function (e) { ... });
$("#recent-searches").on('submit', function() {
This is going to bind to the element matching the id recent-searches that event. If the element doesn't exist then jQuery will do nothing. You have to bind the event to the whole document(or to a parent which will contain that element with id recent-searches) and specify the ID, like this:
$(document).on('click', '#recent-changes', function() {
In this case I think that something like this should work:
$('#searches').on('click', '#recent-changes', function() {
Since #recent-changes is appended to that element.
Remember that the submit event is not going to be fired when you click that button, because it is not the submit button, you can use this code:
$("#searches").append('<input type="submit" id="recent-searches" value="' + textbox + '" />');
Related
I am trying to trigger an event when an input textbox changed:
$('.packeta-selector-branch-id').on('change', function () { alert('helo'); })
This works only If I manually type something in the textbox, but in my case where an external javascript is setting the textbox value, not working.
I created a little jsfiddle to show this:
https://jsfiddle.net/6vnuqxa0/
To try out:
Click on Choose pickup point
Select something from list and click on "Choose this pick up point".
Any ideas how to resolve this issue?
The selected answer to jQuery watch for domElement changes? suggests binding to the DOMSubtreeModified event. I have tried iin your fiddle and it works! The answer does mention that this event may be deprecated, but it is worth looking into.
In your case, add an id to your div so that you have:
<div id="packeta-selector-branch-id" class="packeta-selector-branch-id"></div>
Then the following code will trigger the alert when the contents of that div change.
$('#packeta-selector-branch-id').bind('DOMSubtreeModified', function(e) {
if (e.target.innerHTML.length > 0) {
alert('helo');
}
});
Otherwise, I would look at the widget itself and try and determine if it fires any events on select. If so, you could attach some behaviour to that event.
trigger('change') when click button. but a ID or name on your input would be better
$(document).off('click', '.button select-branch').on('click', '.button select-branch', function(){
$('.packeta-selector-branch-id').trigger('change');
})
I have an script in which I'm going to add a file XLS, once that I validate the file format, I close a bootstrap's modal and open another modal which is an confirmation window to see whether the user is sure to upload that file.
This confirmation window has a confirmation button, once clicked I want that execute me an function which it's going to run an AJAX to make the request to the server.
However, because of that, I had the following doubts:
Which of the 2 ways is better (and the most correct) to run the code and why?
Why is the click event of the first input file executed if there has not been an event change? I mean, I add a file and the event change is executed and I can make clicks many times as I want, is not it supposed that I must add another file so that I can run the function inside again?
Put an event inside an event, has it a name?
$(document).ready(function(){
//First input file
$(document).on('change','#file', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 1</button>';
$('#button').html(button);
$('#button').click(function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
});
//Second input file
$(document).on('change','#file2', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
$('#button2').click(function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<div id="button"></div>
<div style="margin-top:20px"></div>
<input type="file" id="file2" name="file2"/>
<div id="button2"></div>
Put an event inside an event, has it a name?
It has, the name is Bad Idea. Let me Expain. What happens when you execute the following code.
$('#button').click(function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
A click event is registered to the button. Once an event is registered, it will fire everytime no matter how many times you click.
When you put that code inside another event handler like the first example, it gets executed everytime the file-input changes and a new event handler is registered. So when you select a file, and then decide to change it, file-input changes twice and you get 2 click events registered. Now click on the button, you get 2 new console log printed by one click!!! Try it..
Why is the click event of the first input file executed if there has
not been an event change
Because that's how event handler works, you register once, they get fired everytime after that.
Which of the 2 ways is better (and the most correct) to run the code
and why?
Obviously not the first one, because it is a bad idea, Not the second one either. In case of second one you are attaching event to a division that will contain the button. So you don't need to click on the button, just click anywhere right side of the button, the event gets fired!!!
So if none of them is right, what can we do?
Do not generate button/any html element by javascript for such simple tasks. Do it with HTML, plain and simple.
Do not nest event handler into another i.e put one event handler inside another, it will complicate things. Just put all event handlers directly inside document.ready event of jQuery. document.ready only fires once.
When you need to control user action then show/hide your button or other html element by javascript based on required conditions.
My suggestion is doing something like this.
$(document).ready(function(){
// Hide the button at first
$('#button').hide();
// When File-input changes
$('#file').change(function(){
if(**the file-input has a file selected**){
$('#button').show();
}
else{
$('#button').hide();
}
});
// When Button Clicked
$('#button').click(function(){
// Do the action
});
});
Which of the 2 ways is better (and the most correct) to run the code and why?
I believe this is better:
//Second input file
$(document).on('change','#file2', function(){
let file = $(this);
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
$('#button2').click(function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
Mainly because it's more readable and easy to follow. There is no need to have the button click event set up AFTER the input has been changed. It is better to change the STATE of the button, as you are doing. Even better would be to hide/show the button like:
$('#button2').show();
And have it initially hidden with:
<div id="button2" style="display: none">Click me</div>
Why is the click event of the first input file executed if there has not been an event change?
In my test, this all worked correctly.
How is called this?
The change events should only be called when you click and assign a file to the input.
you are binding the same event multiple times to the same button object. binding the same event to the same object in another event that may reoccur will result in binding it over and over (stacks events and fire them and in this case "it" multiple times). binding an action to an event should happen only one time per object. and I see that you are binding the click event to the div instead of the button. maybe you need to consider dynamic binding using .on() like this
$(document).ready(function(){
//first file change event
$(document).on('change','#file', function(){
let file = $(this);
//handling empty selection
if(file[0].files.length == 0){
$('#button').html("");
return;
}
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 1</button>';
$('#button').html(button);
});
//second file change event
$(document).on('change','#file2', function(){
let file = $(this);
//handling empty selection
if(file[0].files.length == 0){
$('#button2').html("");
return;
}
let nameFile = file[0].files[0].name;
let button = '<button type="button">Clic input 2</button>';
$('#button2').html(button);
});
//first button dynamic event (doesn't stack)
$('#button').on('click','button', function(){
console.log('CLICK IN FIRST INPUT FILE!');
});
//second button dynamic event (doesn't stack)
$('#button2').on('click','button', function(){
console.log('CLICK IN SECOND INPUT FILE!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<div id="button"></div>
<div style="margin-top:20px"></div>
<input type="file" id="file2" name="file2"/>
<div id="button2"></div>
note that you need to handle not choosing a file (e.g. files count is 0) like in my code
Put an event inside an event, has it a name?
It does have a name. It's called "daisy chaining" and it's not a good idea.
not enough rep to comment
I've had cause to do this. I had the unpleasant task of mucking through 2 years of code written by one person with little maintenance or code discipline. I wanted to keep the code structure intact, so I daisy-chained click events to perform some enhancements.
To avoid some problems mentioned in the better answers above, simply remember to call $(selector).off("click") before binding the next event.
const mainevent = (e)=>{
e.preventDefault();
your event data
.then((e) => {
second event()
})
.catch((error) =>
alert(error.message))
};
}
In a form, i have a button and an image... when i click on image, form action is called, that work... but when i click on the button action is not called.
Is there a specific thing to do for a button?
js
$('#formUser').submit(function() {
$(this).attr("action", "/secure/downloaduserinfo/" + reportName);
});
$('#formUser').submit(function() {
$(this).attr("action", "/secure/deleteuser/" + reportName);
});
web part
<button type="button" id="deleteUserButton${statusReport.count}"></button>
<input id="downloadUserButton${statusReport.count}" type="image"/>
type="button" elements are not submit buttons, they exist solely to run client side code.
If you want to submit the form, use type="submit" (or don't specify a type attribute at all, submit is the default).
That said, I'd avoid the dependancy on JavaScript. Give the buttons and name and a value and use that on the server to determine if you want to download or delete.
The input of type "image" is similar to "submit", it does submit your form, that's why your submit handler is working. While the input of type "button" does not submit the form, it just looks like a button.
You have 2 submit listeners for the same element so every time the #formUser is submitted it uses the first submit listener it finds.
You can use the onclick listener and tie it to the specific element being clicked.
I'm not sure how the templating system it looks like you're using is tied in but I'd use a class instead of the id.
<button type="button" class="delete-user-button" id="deleteUserButton99">Delete</button>
<img src="http://placehold.it/200x200" class="download-user-button" id="downloadUserButton99"/>
<script>
$('.delete-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/deleteuser/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
$('.download-user-button').click(function() {
// store object that was clicked
var obj = $(this);
// set that objects action attribute
obj.attr("action", "/secure/downloaduserinfo/" + obj.attr('id'));
// show the action attribute's value
alert(obj.attr('action'));
});
</script>
Here's a fiddle that demonstrates manipulating the object by the click listener: http://jsfiddle.net/chapmanc/HHfQT/2/
Is there a way to get the hyperlink name when you click on it using jQuery? I have the following code, I need some jQuery direction:
<a href="#" id="imageClick" name='<%# Eval("fileName1") %>'><asp:Image ID="myImage" name='<%# Eval("fileName1") %>' runat="server" ImageUrl='<%#"~/Image/" + Eval("fileName") %>' /></a>
Basically I would like to return the value of whatever <%# Eval("fileName1") %> is.
Thanks.
EDIT: To be more clear, I have a popup page which contains a listView which that has images and radio buttons. The requirement is if you click on the radio button, it should get the value of that specific choice and close the popup. I'm also passing a value back to the parent window. So this is what I have:
$(document).ready(function () {
$("#form1").change(function () {
var val = "";
if ($('input:radio[name=myRadio]:checked').val()) {
val = $('input:radio[name=myRadio]:checked').val();
}
if (val != "") {
$(window.opener.document).find('#txtLogos').val(val);
// Close the window
window.close();
}
});
});
This works fine when I click on one of the radio buttons. But now they added another requirement that if they click on the images they want the same result (Obviously without disrupting the functionality that the radio button has).
You can just access it using this.name inside your click handler. this here is the Dom element (Don't need jquery to retrieve the element attribute value), so just directly access the name attribute of the element.
$('#imageClick').click(function(){
alert(this.name);
});
Edit
Form change will not be triggered if you click on an image; unlike input, select, textarea etc. So you need to trigger form change manually on image click event (to simulate a radio button click triggering the form change event).
Bind a click handler to your images to add class:
$('yourimageselector').click(function(){
$(this).toggleClass('checkedImage'); // Add a class on first click and again clicked on it remove the class to say it is turned off. If you dont want a turn off functionality simply say :
//$(this).addClass('checkedImage'); //or if this is the only class then this.className = 'checkedImage' classList is not yet supported in all browsers.
$('yourform').change(); //as this is image it wont trigger form change event so you need to manually trigger form's change event (only for input, select, textarea etc form change will be triggered).
});
And in your form event:
$("#form1").change(function () {
var imgNames= $('.checkedImage')
.map(function(){return this.name; })
.get(); // Will get you all the image names in an array.
//if it is just one image then simply do if($('.checkedImage').length > 0) $('.checkedImage')[0].name,
//Code follows
});
Fiddle
this can also work in the event handler of your click :
document.getElementById("new-answer-activity").name
First, sorry for my bad English.
I'm making a Coupons site and have trouble with selecting and deselecting the coupons. Each coupon is in a DIV 'box' in which there is a checkbox.
I made a onClick function on the DIV box (so the user can select the coupon by clicking on anything inside the DIV box. What I need now is, when the user want to deselect the coupon (by clicking on the checkbox inside the DIV box), I need to 'override' the DIV's onClick function (execute the checkbox onClick event, not the DIV's onClick event).
I know that everyone prefers some code as an example, but the question/problem is simple and I don't think you need all of my un'useless code inside the events/functions :)
Thanks :)
It seems like you want stopPropagation if the checkbox is being unchecked: http://jsfiddle.net/8Dcq8/.
$("div").click(function() {
alert("add"); // clicking anywhere in div to add coupon
});
$(":checkbox").click(function(e) {
if(!this.checked) { // if unchecking, remove coupon
alert("remove");
e.stopPropagation(); // don't run parent onclick
}
});
If the <div> click handler looks something like this:
var $boxes = $('div.box');
$boxes.on('click', function ()
{
// do whatever to select the coupon
});
Then the checkbox handler should look something like this:
$boxes.find('input[type="checkbox"]').on('click', function (event)
{
event.stopPropagation();
// do whatever to deselect the coupon
});
See event.stopPropagation().
You have to cancel bubbling. See here for an explanation.
You can use the jQuery Alternative, or create sub-elements with onClicks that don't target your checkbox. you might be able to use something like this also.
document.getElementById('element').checked.onreadystatechange=function(){
//code
}
good luck