I have a delete hyper link
Delete
and my Jquery function
$(document).ready(function()
{
$("#password_validate").validate({
rules:{
current_pwd:{
required: true,
minlength:6,
maxlength:20
},
new_pwd:{
required: true,
minlength:6,
maxlength:20
},
confirm_pwd:{
required:true,
minlength:6,
maxlength:20,
equalTo:"#new_pwd"
}
},
errorClass: "help-inline",
errorElement: "span",
highlight:function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
}
});
$("#delCategory").click(function(){
alert("Test");
if(confirm('Are you sure you want to delete this Category?')){
return true;
}
return false;
});
});
My other parts of the code can access the #password_validate and make sure the password field is required and all. But the #delCategory from the same HTML page is unable to access the function and return confirmation.
I am able to call the Jquery function from Chrome Console and get the pop-up and confirmation, but my href is failing to call it and it processes the delete without confirming.
Add event.preventDefault() to your click(...) event handler to prevent the default action/behaviour that belongs to the event from occurring. i.e:
Event.preventDefault()
<form method="POST" action="{{ url('/admin/delete-category/'.$category->id) }}">
#csrf
#method("DELETE")
<input type="hidden" name="id" value="{{$category->id}}">
<input id="delCategory" type="submit" class="btn btn-danger text-center btn-mini" value="Delete">
</form>
jQuery
$("#delCategory").click(function (e) {
e.preventDefault();
if (!confirm('Are you sure you want to delete this Category?')) {
return;
}
const $form = $(this).closest("form");
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: {
"_method": $form.find("input[name=_method]").val(),
"_token": $form.find("input[name=_token]").val(),
"id": $form.find("input[name=id]").val()
}
});
});
ADDENDUM
If you have multiple "delete" buttons in a single document, you may consider using a class=... attribute instead of id=....i.e:
<!-- Instead of: -->
<input id="delCategory" ...> ❌
<!-- Use this: -->
<input class="delCategory" ...> ✅
Modify the JavaScript accordingly. i.e:
$(".delCategory").click(function (e) {
// ...
That would ensure that the event handler is applied to all relevant 'dom' elements with a particular class attribute instead of a single dom element matching a unique id attribute.
Resources:
What's the difference between an id and a class?
What is the difference between id and class in CSS, and when should I use them?
Related
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
I want to use an onlick event handler to validate some form fields using jquery Validate. To do this I have the following code:
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
<script>
$(".js-add-names").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Name: {
required: true
}
},
messages: {
Name: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Age: {
required: true
}
},
messages: {
Age: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
</script>
What I've noticed is that only one event handler works out the two based on whichever one was clicked first i.e. if I click the button with class js-add-names, the validation for that handler works as expected.
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work and vis versa?
Any ideas why this is happening and what is the fix?
* UPDATE *
Further to suggestion by Sparky I have re-written the code as below but now when I click js-add-names, the validation for that handler works as expected
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work becuase the validation has previously added a rule for input #Name. How do I reset the form or remove the rules each time the event handlers fire?
<form>
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
// other inputs
<input type="checkbox" name="CarOwner" value="Yes"> Car owner
<input type="submit" value="Submit">
</form>
<script>
$("form").validate();
$(".js-add-names").click(function (e) {
e.preventDefault();
$("#Age").rules("remove");
$("#Name").rules("add", {
required: true,
messages: {
required: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Name").val('');
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("#Name").rules("remove");
$("#Age").rules("add", {
required: true,
messages: {
required: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Age").val('');
});
</script>
Any ideas why this is happening and what is the fix?
The .validate() method is only used for initializing the plugin on your form and therefore should only be called once when the page is loaded. Subsequent calls are always ignored. So when you use one click handler, you initialize the validate plugin, and the other call to .validate() in the other click handler will do nothing.
The fix...
Call .validate() ONE time to initialize the plugin on your form.
Do NOT call .validate() from a click handler since this is not the testing method; it's only the initialization method.
Use the plugin's built-in submitHandler and invalidHandler functions for stuff you need to do when the form is valid and invalid.
Since you appear to be using your click handlers to add fields/rules to an existing form, then use the .rules('add') and .rules('remove') methods to add and remove any rules dynamically.
I tried validation on HTML element which get printed via PHP but it is not working, but it does work when I put the same HTML without PHP.
Below is the HTML in which the actual data will be printed via AJAX:
<div class="row" id="live_data">
// here will all radio buttons and images echo via ajax
</div>
Here is the AJAX:
function fetch_all() {
var form_name = 'package_form2';
$.post('ajax/ajax_form_get_all_packages.php',{form_name:form_name}, function(result) {
console.log(result);
$('#live_data').html(result);
});
} fetch_all();
Here is the actual data which gets echoed via Ajax:
$output .= '
<div class="col-md-4">
<label for="'.$id.'">
<img src="uploads/'.$img.'" class="img-responsive">
</label>
<div>
<div class="radio text-center">
<input type="radio" id="'.$id.'" value="'.$code.'" name="optradio" class="optradio">
</div>
</div>
</div>
';
Here is the code of FormValidation:
$(document).ready(function() {
$('#menu1_info').formValidation({
message: 'This value is not valid',
icon: {
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
optradio: {
validators: {
notEmpty: {
message: 'Please choose one of the Package'
}
}
}
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var fv = $form.data('formValidator');
$form.bootstrapValidator('disableSubmitButtons', false);
});
});
There is no element with class optradio in your markup. Instead there is one with attribute name equal to optradio:
$(document).on('change', '[name="optradio"]', function() {
alert("Radio button clicked");
});
UPDATE
If I understood correctly, #menu1_info element comes from the ajax response
$(document).ready(function() {
$('#menu1_info').formValidation({
Here you are trying to select an element on document ready, but this element is not present to the DOM yet because it is appended asynchronously (after document ready event).
So, you have to initialize your plugin after the target element is present to the DOM (in the ajax callback function).
// The $('#menu1_info') element is not present now
$.ajax({
url: '...',
...,
success: function(data) {
// Append data from ajax call
$('#target').append(data);
// Now, $('#menu1_info') element is present
$('#menu1_info').formValidation({ ... });
}
});
There is no such element in the response '.optradio'.
Better to change to this:
$('#live_data').on('change', ':radio', function() {
alert("Radio button clicked");
});
Also you can delegate to closest static parent which in your case is #live_data
I know how to validate a form using Semantic UI, and can even read in console the message "Form has no validation errors, submitting." However, where is this submitting to? I want to actually submit the form, but the way Semantic UI is laid out I don't seem to be able to specify where to submit to or anything.
I read this tutorial, but that uses Angular for submission and not just Semantic UI.
Am I missing something really simple here?
You can use jQuery's ajax:
//Get value from an input field
function getFieldValue(fieldId) {
// 'get field' is part of Semantics form behavior API
return $('.ui.form').form('get field', fieldId).val();
}
function submitForm() {
var formData = {
field1: getFieldValue('someId')
};
$.ajax({ type: 'POST', url: '/api/someRestEndpoint', data: formData, success: onFormSubmitted });
}
// Handle post response
function onFormSubmitted(response) {
// Do something with response ...
}
EDIT: also, you can use the onSuccess method of the form to run the submitForm function, ie when you initialize the form:
$('.ui.form').form(validationRules, { onSuccess: submitForm });
onSuccess will only be called when the 'Submit' button is clicked and the form is valid based on the rules you specify.
EDIT: If you want the regular HTML form behavior, you will need to add the semantic css classes to the form tag.
<form class="ui form" method="POST" action="/signup">...</form>
And then you set up the validation rules using jQuery. This will give you the default HTML form behavior, ie when you hit the submit button, it will make a POST request to /signup in the case above. If any of your rules trigger, the submit is prevented until there is no validation errors.
use the original submit button but add semantic button style:
<input type="submit" value="Submit" class="ui button" />
<input type="submit" value="Submit" class="ui teal button big"/>
Semantic UI has it's own API to submit form. for example:
$('.ui.form .submit.button')
.api({
url: 'server.php',
method : 'POST',
serializeForm: true,
beforeSend: function(settings) {
},
onSuccess: function(data) {
}
});
The easiest way is to retrofit a standard HTML form use the code below.
Start with a basic working standard HTML form with a submit button and this will take your values and post them to your form destination, returning the output below your form submit button.
Its a good time to double check you are successfully linking to jquery, semantic javascript and semantic css at this point.
Add class="ui form" to your form tag .
Add the javascript below.
.
$(document).ready(function() {
// validation
$('.ui.form').form({
email: {
identifier : 'email',
rules: [
{
type : 'email',
prompt : 'Please enter an email'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'fade down',
onSuccess: validationpassed
});
// called if correct data added to form
function validationpassed() {
// Multiple instances may have been bound to the form, only submit one.
// This is a workaround and not ideal.
// Improvements welcomed.
if (window.lock != "locked") {
var myform = $('.ui.form');
$.ajax({
type: myform.attr('method'),
url: myform.attr('action'),
data: myform.serialize(),
success: function (data) {
//if successful at posting the form via ajax.
myformposted(data);
window.lock = "";
}
});
}
window.lock = "locked";
}
// stop the form from submitting normally
$('.ui.form').submit(function(e){
//e.preventDefault(); usually use this, but below works best here.
return false;
});
function myformposted(data) {
// clear your form and do whatever you want here
$('.ui.form').find("input[type=text], textarea").val("");
//$('.ui.submit.button').after("<div>Message sent. Thank you.</div>");
$('.ui.submit.button').after(data);
}
});
Basic form:
<form action="process.php" method="post" class="ui form">
<div class="field">
<label>title</label>
<input name="email" type="text">
</div>
<input type="submit" class="ui button"/>
</form>
If you want the error message to show in a box rather than within the form itself include this in your form, and remove the words "inline: true," and Semantic UI does the rest:
<div class="ui info message"></div>
NOTE: Using form tags with Semantic UI isn't strictly necessary as you only really need a div with the classes "ui form", however this retrofit code does require a form tag.
What if you don't wana use ajax?!
Use this one:
$( "#reg_btn" ).click(function(event){
event.preventDefault();
$('#register_form').submit();
});
in this case u can use <button> tag... there is no need to use classic tag instead
Semantic UI is based on jQuery and CSS so if you want to submit your form data you have some way to do that:
Send your form data with AJAX
Use some jqQuery plugins like this
Trick!
Put a submit button and set its display to none. When a user clicks on the div button throw that event to the submit button, in this way:
$("div_button_selector").on("click", function(){
$("input[type='submit']").trigger('click');
});
See post Adding errors to form validation doesn't work? for form and error validation. Since Semantic UI is a client side tool for user interface, this is the php for "self submitting / same code page" contact email. Since the purpose of Semantic UI is not logic processing, what language and or method do you want to use for form submission? JS/jquery client side or serverside php, rails, etc.? Keep in mind Semantic UI is dependent on jquery.
<?php
if (isset($_POST["email"]))
{
if ($_POST["email"] != "")
{
$from = htmlentities($_POST["email"]);
$subject = htmlentities($_POST["subject"]);
$message = htmlentities($_POST["message"]);
$message = wordwrap($message, 70);
mail("valid-server-email-username#valid-server-address", $subject, $message, "From: $from\n");
$_POST["email"] = "";
$_POST["subject"] = "";
$_POST["message"] = "";
unset($GLOBALS['email']);
header("location: /");
}
}
If you have a form like this
<div class="ui form segment">
<p>Tell Us About Yourself</p>
<div class="field">
<label>Name</label>
<input placeholder="First Name" name="name" type="text">
</div>
<div class="field">
<label>Username</label>
<input placeholder="Username" name="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="ui blue submit button">Submit</div>
</div>
you can use the foolowing script to send the form
$('.ui.blue.submit.button').on('click', function() {
submitForm();
});
function submitForm() {
var formData = $('.ui.form.segment input').serializeArray(); //or .serialize();
$.ajax({
type: 'POST',
url: '/handler',
data: formData
});
}
There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});