form action call button - javascript

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/

Related

jQuery Validation with "formnovalidate" in submit button outside the <form>

I have an edit form using the jQuery Validation plugin. It's part of an ASP.NET Core project, also using ASP.NET's Unobtrusive Validation plugin. The form has two submit buttons, posting to different handlers server-side:
Submit changes
Delete entry
"Submit changes" is working fine, however I'd like the "Delete" button to skip any client-side validation. Currently it won't post the form if any required fields are missing (or any other validation condition doesn't pass).
I've tried the HTML5 formnovalidate attribute on the "Delete" button without success. Is there an equivalent feature in the jQuery Validation plugin? If not, how would you bypass validation only for a specific submit button?
EDIT:
The "Delete" button is actually outside the <form> tag, but referencing the form by ID through the form attribute:
<form id="my-form">
<!-- form fields and submit button here -->
</form>
<button type="submit" form="my-form" noformvalidate asp-page-handler="Delete">
Delete entry
</button>
I've found that when moving the "Delete" button inside the <form>, the noformvalidate attribute works as expected. I would really like to keep this button outside the <form> tag (due to the page's layout), though I might be able to work around it if there's no other way.
Any ideas on how to make it skip validation while placed outside the form?
The problem you have seems to be summarized in this issue:
Typical save vs submit button where save does not validate and submit
does. Save button is declared with the formnovalidate attrribute. Only
thing is that these buttons are outside of the form itself.
See, the plugin expects the submit buttons to be inside your form. It actually still handles both 'preventing' flags - cancel class and formnovalidate attribute - within click handler propagated from buttons to the top of the form (source):
// "this" is jQuery-wrapped HTMLFormElement with validator attaching
this.on( "click.validate", ":submit", function( event ) {
// Track the used submit button to properly handle scripted
// submits later.
validator.submitButton = event.currentTarget;
// Allow suppressing validation by adding a cancel class to the submit button
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
} );
... which clearly doesn't work if buttons are outside of form DOM hierarchy, like in your case. Only submit.validate handler is fired, but it expects to check validator.cancelSubmit flag (and set it to false if it's truthy).
One idea that comes to mind is to place your own click handler on Delete button that will override that flag. Validator instance is accessible through form $.data, as usually with jQuery plugins:
const validator = $.data(form, 'validator');
Perhaps you are looking for something like this:
var $frm = $('#my-form')
, frm = $frm[0]
, $btnsubmit = $('button[type="submit"]');
frm.addEventListener('submit', (evt) => {
var skipValidation = evt.submitter.hasAttribute('formnovalidate')
, validator = $frm.data('validator');
skipValidation && validator !== undefined
? (validator.cancelSubmit = true)
: ($frm.valid() && $btnsubmit.prop('disabled', true));
})
here I'm using a mix of vanilla JS and JQuery because not all submit-event properties are available in JQuery and is not so recommended to access JQuery data using vanilla JS.
In this case, there is no matter where are declared your submit-buttons but... you should be sure to execute the above script before $.validator.unobtrusive.parse(document) that mean before validator.unobtrusive become obtrusive.

Javascript onblur & onclick function saves record multiple times

I have one Javascript function named "saveForm()" from which I am saving the records in the database.
My form has one button as 'Save in draft' which saves the record in draft mode. On this button, there is onclick event which calls above javascript "saveForm()" function.
Now, I have a feature about autosave the record which calls javascript above "saveForm()" function on every onblur event of the form field.
Now, the scenario is when I fill one of the fields & directly clicks on 'Save in draft' button, it saves the records multiple times as both(onblur & onclick) events called parallel.
Onclick :
<input type="button" class="btn" id="draftsave" value="Save in draft" onclick="javascript: saveForm(this.form.id, 'draft');" />
Onblur :
jQuery(document).delegate(":input[type!='button']", "blur", function() {
saveForm(this.form.id, "draft");
});
HTML Form
You can do something like below or you can check before inserting in database but in that case it will make multiple backend calls, its better to keep a check in front end while making the backend call, so you can try the below code and see if it solves your problem:
var clicked;
$("#draftsave").click(function() {
clicked = true;
});
jQuery(document).delegate(":input[type!='button']", "blur", function() {
if (!clicked) {
saveForm(this.form.id, "draft");
} else {
//do something
}
});
okay so if you want this functionality(but you can just keep yout submit associated to onChange) just send a boolean filed on change event like
<input type="text" onChange="someFunction(true);">
Now you can take a global boolean variable and update its value with the value of onChange boolean param.
boolean isOnChangeCalled=false;//global variable
function someFunction(isOnchange)
{
this.isOnChangeCalled=isOnchange
}
and in case of onClick just check if this boolean ie isOnChangeCalled is set to true only then perform a onClick event otherwise prompt user that form is already saved
To verify in back end
In case data is already submitted and user clicks submit button then then just check if the data is already updated in database by comparing two objects but that is an extra overhead and return appropriate reponse in case data is already there
UPDTATE
you can maintain a clone of your form object and before your onClick event you can compare both objects and if they are same just prompt user the relevant message

Javascript new button on form submit

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 + '" />');

Form submit/update onclick

I must rebuild a form, there are two buttons, one is for increasing the value of an input and second for decrease the value, and I must delete submit button and update form always if I click on increase or decrease, i have tried this with jquery onchange:
I have read also this: http://api.jquery.com/submit/
$("#increaseButton").change( function() {
$("#quantityForm").submit();
});
I can't edit form, because I must work only with submit, is that possible?
I think a click would be better here:
$('#increaseButton').on('click', function() {
increaseValue(); //call a function to increase the value
$("#quantityForm").submit(); //submits the form
});
what is #increaseButton? is it just a link? or actual
<input type="button" />
I don't think buttons can have a "change" event attached to them

Getting the name of a hyperlink when it's clicked using jQuery

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

Categories

Resources