Passing data from buttons to server through the modal window - javascript

On my site I have a modal window (Bootstrap) that can be shown by clicking a few buttons with such markup:
Click me!
...
Click me!
...
Click me!
My modal window has this peace of code:
<form data-formname="Hero Section" class="forms">
<div class="form-group">
<label class="sr-only" for="phone">Ваш телефон</label>
<input type="tel" id="phone" class="form-control phone" placeholder="Please enter your phone number:">
</div>
<button type="submit" class="btn btn-danger">Send</button>
</form>
And JS:
$(".forms").on('submit', function(e) {
e.preventDefault();
var data = {
phone: $(this).find(".phone").val(),
formname: $(this).data('formname'),
// datalink: ???
};
$.ajax({
type: "POST",
url: "contact.php",
data: data
});
return false;
});
In addition to phone and formname, I want to get a button's data-link. Obviously, I can't use event.relatedTarget inside $(".forms").on('submit', function(e) {...});. Any thoughts?

You can use get the source in the show.bs.modal event handler
$('#myModal').on('show.bs.modal', function (e) {
var source = $(e.relatedTarget);
//Persist it for later use
$(this).data('relatedTarget', source)
});
Now, You can use it to retrieve source element in the form submit event handler and get the data-link
$(".forms").on('submit', function(e) {
e.preventDefault();
var source = $('#myModal').data('relatedTarget');
var datalink = $(source).data('link');
});
Side note: Identifiers in HTML must be unique, remove duplicate id="btn"

Related

Local storage doesn't work after submitting data on the server

I need to keep the values of the rangeSlider after refreshing the page, as the selected range is reset. Local storage in my case for some reason doesn't work.
HTML Markup:
<input type="text" class="js-range-slider" name="my_range" value="" data-min="100" data-max="4000" data-from="1000" data-to="2000"/>
<input type="hidden" id="startPrice" name="startPrice" value="" />
<input type="hidden" id="endPrice" name="endPrice" value="" />
<button class="filter-btn_send filter-btn_send--active" type="submit">Select</button>
Code:
$(document).ready(function () {
if (localStorage.getItem('startPrice')) {
$('.js-range-slider').data('from', localStorage.getItem('startPrice'));
$('#startPrice').attr('value', localStorage.getItem("startPrice"))
}
if (localStorage.getItem('endPrice')) {
$('.js-range-slider').data('to', localStorage.getItem('endPrice'));
$('#endPrice').attr('value', localStorage.getItem("endPrice"))
}
$('.filter-btn_send filter-btn_send--active').submit(function () {
let startPrice = $('#startPrice').attr('value');
let endPrice = $('#endPrice').attr('value');
localStorage.setItem('startPrice', startPrice);
locacStorage.setItem('endPrice', endPrice);
});
}
UPD! My solution: https://codepen.io/funn1k1/pen/qBqMmgx
submit events
Submit events are fired on form objects, not buttons or input elements that trigger submission (as covered in MDN documentation. The following snippet shows that, as posted, the submit handler is not called by monitoring "submit" events on the submit button - the expected outcome is that only the form submit handler will be called:
"use strict";
$(document).ready(function () {
$('form').submit(function(e) {
console.log( "form submit handler called");
e.preventDefault();
});
$('input').submit( function(e) {
console.log( "submit button handler called");
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- body-html -->
<form>
<input type="submit">
</form>
beforeunload event
The "beforeunload" event can be monitored to save slider values when the page is unloading, even if the form has not been submitted. As a code pattern example:
$(document).ready(function () {
window.addEventListener("beforeunload", function(event) {
// get values from range widget
let startPrice = "1000" // example only
let endPrice = "1174" // example only
// save in localStorage
localStorage.setItem('startPrice', startPrice);
localStorage.setItem('endPrice', endPrice);
});
});
Note this doesn't include code to create, set or get the values of dual pointer jQuery-UI range widgets.

Used 'needs-validattion' bootstrap in the HTML javascript ,but it's not going inside the check validation method

I have a two text fields and one submit button in my application. When I click the submit button if any one of the text field is empty it should tell me 'Please fill out the field'. So I used bootstrap 'needs-validation' in my script. Now when I click the submit it is not going inside the if or else loop of the validation. If the condition is true it should go inside the else loop and should do the ajax call.If the ajax call is success it should send the alert message to the user. But I dont see the alert message and POST call is also not happening.
My HTML script is
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
console.log("I am inside function");
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
console.log("I am inside submit")
if (form.checkValidity() === False) {
console.log("I am inside true");
event.preventDefault();
event.stopPropagation();
}
else {
console.log("I am inside else");
var departments = $("#role").val();
var facultyList = $("#faculty").val().split(',');
facultyList.pop();
console.log(facultyList);
$.ajax({
type: 'POST',
url: '/departments/add',
data: {
'role': departments,
'facultylist': JSON.stringify(facultyList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
}
form.classList.add('was-validated');
}, false);
});
}, false);
}) ();
<div class="row top-space-30">
<form class="needs-validation">
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="deprole">Department :</label>
<div class="col-md-6">
<input id="role" name="deprole" type="text" placeholder="QA" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="faculty">Faculties:</label>
<div class="col-md-8">
<input class="form-control" type="text" id="faculty" required>
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="submit" id="submit">Submit</button>
</div>
</form>
</div>
When I run the script I can see in the console log 'I am inside submit'. But When I click the submit button without entering the details I dont see 'I am inside true' in the console log. But validation will happen. When I enter the details in two fields and click the submit button I dont see 'I am inside else' in the console log and I dont see the alert function in my application also
What I need is:
-When I click the submit button with details I should see the ajax call and should see the alert message.
There are a few problems..
The JS boolean value should be false not False
The preventDefault() and stopPropagation() should be called regardless of validation
since you want to stop the default behavior of the submit button
Demo: https://codeply.com/p/wtSkr8Eucc
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
if (form.checkValidity() === false) {
console.log("I am inside true");
}
else {
console.log("I am inside else");
var departments = $("#role").val();
var facultyList = $("#faculty").val().split(',');
facultyList.pop();
console.log(facultyList);
$.ajax({
type: 'POST',
url: '..',
body: {
'role': departments,
'facultylist': JSON.stringify(facultyList)
},
success: function (result) {
alert("The department has been added");
}
})
}
form.classList.add('was-validated');
}, false);
});
When you click on the 'Submit' button, your form makes a default action, which is sending the form data (in a form of GET attribute) to the same page that holds the form (normally those can be controlled by the 'action' and 'method' attributes of form tag).
That in effect means that the page 'reloads' itself before executing any JS code.
To prevent that default action, add event.preventDefault(); in your event listener code block and it should be fine.
form.addEventListener('submit', function (event) {
event.preventDefault();
console.log("I am inside submit")
Also important, don't rely on browser validation, which can be easily avoided. Make sure to implement a back-end validation / sanitation function as well.

PHP-AJAX passing input text to action url directly with ajax

Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.

In form data, pass info about which button was clicked -- after confirmation modal

The click event on my submit button triggers a confirmation modal.
When the user clicks on the confirmation button, the form is sent without the original submit button data, which I need.
Simplified code:
<form action="/action" method="post">
<!-- inputs -->
<button type="submit" name="foo" class="with-confirmation-modal" />
</form>
<script>
$(document).on('click', '.with-confirmation-modal', function() {
$form = $(this).closest('form');
$modal = $('#modal');
$modal.on('click', 'button[type=submit]', function() {
// form is sent without the info about which button
// was clicked prior to modal
$form.submit();
return false;
});
$modal.modal('show');
return false;
});
</script>
What's a good way to deal with this ?
When you post a form clicking on
<button type="submit" name="foo" />
data posted includes the name of the button :
...&foo=&...
This behaviour is broken by the confirmation popup. Here we simulate it by adding a hidden input with the name of the clicked button before calling $form.submit().
<script>
$(document).on('click', '.with-confirmation-modal', function() {
var $clickedBtn = $(this);
var $form = $clickedBtn.closest('form');
$modal = $('#credit-headsup-modal');
$modal.on('click', 'button[type=submit]', function() {
$(this).parent('.btn-wrapper').addClass('btn-wrapper--active');
$(this).siblings('.btn-loading').show();
// Pass info about which btn was clicked prior to modal
// by adding a hidden input with same name as btn
$form.append('<input type="hidden" name="'+$clickedBtn.attr('name')+'" value="">');
$form.submit();
return false;
});
$modal.modal('show');
return false;
</script>
If there is a better way, please share.

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Categories

Resources