So As Title says i have modal box which loads after the page load means it is loading after the Ajax Call and i want to validate the fields of this modal box.
for that i'm using the below code , as my HTML is not loaded in DOM :
$(document).on('click', ".add_style", function(e) {
var style_name = "";
style_name = $(".style_name").val();
if($.trim(style_name).length == 0)
{
$("#style_id").parent('div').addClass('has-error');
$(".title_error_msg").css("display","block");
return false;
}
else
{
console.log("In else");
return false;
}
});
But I'm not able to get the values of field of modal form.
Please help, Thanks n advance.
Updated :
Here is the part of the HTML
<div class="form-group">
<input type="hidden" value="" id="style_id" name="style_id">
<label>Title</label>
<input type="text" id="style_name" name="style_name" placeholder="Style Name" class="form-control style_name"> <div style="display:none" id="Styles_style_name_em_" class="errorMessage"></div> <label style="display:none;" class="control-label title_error_msg" for="inputError"><i class="fa fa-times-circle-o"></i> Please enter Style Name</label>
</div>
Related
I have a form that uses the jquery form validator plugin (http://www.formvalidator.net/) to perform client side pre-submit validation. I have the toggleDisabled module activated so that the submit button is disabled until all required fields are filled out and formatted correctly. My jquery then sends the form data to a processing page via ajax. The storeData.php code stores the data in a table. On success, the ajax should open a modal. I have verified that the data is being stored in my table.
The issue lies (I suspect) with the form submit button. In order for my toggleDisabled module to work correctly, the button has to be of type 'submit.' But because of the nature of a submit button the success function of my ajax is effectively being bypassed so that the modal will never be displayed.
I have tested this by changing the submit button to a regular button. At the expense of my toggleDisabled module not functioning this way, my modal is displayed.
I have found many solutions here for enabling/disabling buttons and also for preventing form submit by changing the button type to button. However, I want to use the validator module to disable/enable the button because it is designed to listen to the data-validation attributes for my form fields. But it won't work unless it's a submit button. Is there a simple solution that I'm overlooking?
index.php
<form method="post" name="talentForm" id="talentForm">
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="first" class="form-control" placeholder="First name" data-validation="required">
</div>
<div class="col-auto"> </div>
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="last" class="form-control" placeholder="Last name" data-validation="required">
</div>
</div>
<div class="row rowtm20"></div>
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="email" class="form-control" placeholder="E-mail" data-validation="email">
</div>
<div class="col-auto"> </div>
<div class="col-auto"> </div>
<div class="col">
<input type="text" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
<div class="form-row">
<button type="submit" id="registerButton" class="btn btn-primary mb-2 biggertext">Register</button>
</div>
</form>
<script>
$.validate({
modules : 'security,toggleDisabled',
showErrorDialogs : false
});
$('#registerButton').on('click', function(){
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
</script>
storeEntry.php
if(isset($_POST)){
$data = explode("|",$_POST['registration']);
$addRegistration = "insert into talent (Last,First,email,Phone) values('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
$entry = $dbConn->query($addRegistration) or die ("Error performing addRegistration query: ".mysqli_error($dbConn));
if($entry){
echo "1";
} else{
echo "0";
}
}
Well, I found the answer. I added an argument to the click function and then called the preventDefault method, which will effectively 'turn off' the submit action of a submit button. This allows my toggleDisabled module in the validator to function correctly while also allowing my modal to appear and my ajax to execute. Hre is my revised click function:
$('#registerButton').on('click', function(e){
e.preventDefult();
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
I want to save an image and two text field using JQuery,Ajax. here, i'm using bootstrap modal. But when I submit the modal form it's show MethodNotAllowedHttpException Exception.
My Ajax Method.
$(document).ready(function(){
$('#advisoradd').on('submit',function(){
var name=$('#adname').val();
var title=$('#adtitle').val();
var img=$('#adfile').val();
$.ajax({
url:"{{route('add.advisor')}}",
type:'post',
data:{
'_token':"{{csrf_token()}}",
'name':name,
'title':title,
'img':img,
},
success:function(data)
{
console.log(data);
}
});
});
});
My view Modal code.
<form method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<div class="img_upload_team">
<button class="btn">+</button>
<input type="file" name="myfile" id="adfile">
</div>
<h2>Add A Profile Photo</h2>
<p>Click “+” Sign to Add</p>
</div>
<div class="form-group">
<input type="text" name="adname" class="form-control" id="adname" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="adtitle" class="form-control" id="adtitle" placeholder="Title">
</div>
<button type="submit" class="btn btn_modal_submit" id="advisoradd">Add</button>
</form>
My controller and Route for this Request.
public function addadvisor(Request $request)
{
$advisor=new Advisor();
$advisor->name=$request->name;
$advisor->title=$request->title;
$file = $request->file('img') ;
$fileName = $file->getClientOriginalName();
$destinationpath=public_path().'/images/';
$file->move($destinationpath,$fileName);
$advisor->image=$fileName;
$advisor->save();
return response()->json($advisor);
}
Route::post('/advisor','ImageController#addadvisor')->name('add.advisor');
You've mixed up button and form events. Buttons don't have a submit event, forms do. Since you're adding the event on the button, change it to click.
We should also add a preventDefault() to stop the button from submitting the form.
(We could also add the type="button" attribute on the button element to stop it from submitting the form).
This should work:
$(document).ready(function() {
// Add a 'click' event instead of an invalid 'submit' event.
$('#advisoradd').on('click', function(e) {
// Prevent the button from submitting the form
e.preventDefault();
// The rest of your code
});
});
I have a form where one of the controls(inside a div) has a display of none. When a user checks a particular radio button the hidden div will display which contains an input element allowing him to enter some input.
When I tested it with PHP (using isset() function), I realized that the input variable is set, even if it's parent(div with id of details) is not shown.
What I want however is that serialize should only send the variable to the server when the div containing the input field is displayed. If I however gives display of none to the input element directly, it works as I want. But I want it to be on the div because some controls like labels and many other possible input fields need to also be hidden. One quick solution will be to give all the controls or elements in the div a class and toggles their display using the radio buttons, but I rather prefer the class to be on the div wrapping them all.
HTML:
<form id="form">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="firstname" class="form-control" name="firstname" autofocus placeholder="First Name">
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="surname" class="form-control" name="surname" placeholder="Surname">
</div>
<label>1. Do you program?: </label>
<label class="radio-inline">
<input type="radio" name="one" value="Yes"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="one" value="No" checked> No
</label>
<div class="form-group" id="details" style="display:none;">
<label class="control-label">State your Languages</label>
<input type="text" name="language" class="form-control" autofocus>
</div>
<div class="form-group">
<button id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
JavaScript
$(function(){
$('#form input[name=one]').change(function(event) {
$('#details').toggle();
});
$('#submit').on('click', function(event) {
event.preventDefault();
var form = $('#form');
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'html',
data: form.serialize()
})
.done(function(html) {
console.log(html);
})
.fail(function() {
console.log("error");
})
});
});
PHP
if(isset($_POST['language'])) {
echo 'Language is set';
} else {
echo 'Not set';
}
The PHP reports 'Language is set' even if the div containing the input with name of language is given display of none;
disabled input elements are ignored by $.serialize()
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
To Temporarily enable them.
var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
OR
You could insert input fields with no "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jquery):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
Instead going for complex workaround in JavaScript, you could accomplish it in PHP easy way. Check if the radio button Yes is selected and if it is selected, you can do other processing based on that.
if(isset($_POST['one']) && $_POST['one'] === 'Yes') {
if(!empty($_POST['language'])) {
echo $_POST['language'];
} else {
echo "Language is given empty!";
}
} else {
echo 'Language is not selected!';
}
The PHP code above is a simple workaround. You could go for that. If you're only looking to do that in JavaScript itself, I would direct you to the answer given by Bilal. He has some workaround with JavaScript.
EDIT
I've come up with my own simple workaround in JavaScript. Hope it could help you.
<script>
$(function() {
var details = $('#details');
$('#details').remove();
$('#form input[name=one]').click(function() {
if(this.value === 'Yes') {
details.insertBefore($('#form div.form-group:last-of-type'));
details.show();
} else {
$('#details').remove();
}
});
});
</script>
Storing the reference to div of id details in a variable before removing the details div from the DOM.
Based on the value selected in the radio button, the details div will be added to the DOM and displayed or removed from the DOM in case No is selected.
Hope it helps!
I have a form with a button whose id is calbtn. The form has two input fields whose ids are input1 and input2.
I want to check if the inputs are empty after I click callbtn. If the inputs are empty, then display the alert box (whose id is failurebox) else submit the form.
But this function is executed only once during its first time. When I click again callbtn does not execute the check function. If I leave either of my input1 or input2 empty for second time.
Please help me solve this problem. I am new to using jQuery. Please correct my below jquery code.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if ($("#tempsp").val() == "" || $("#temppv").val() == "")
$("#failurebox").show();
});// end of click function
});
My HTML code is
<form id="newlayerform" role="form" method="post" class="form-horizontal" >
<div class="form-group">
<label for="tempsp" class="col-sm-4 control-label" style="color:red">Temp Set Point</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="tempsp" id="tempsp" placeholder="Enter Temp Set Point">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<div class="form-group">
<label for="temppv" class="col-sm-4 control-label" style="color:red">Temp Process</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="temppv" id="temppv" placeholder="Enter Temp Process">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<button type="button" class="btn btn-success btn-lg btn-block" id="calbtn" name="calbtn">Calculate</button>
</form>
<div id="failurebox" class="alert alert-warning" style="display:none">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Failure
</div>
The form should not be submitted. Use return false; to stop form from submitting.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$.trim($("#input1").val()) || !$.trim($("#input2").val())) {
$("#failurebox").show();
} else {
$("#failurebox").hide();
}
}); // end of click function
});
Try this: jquery way of checking if an input is empty:
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$("#input1").val() || !$("#input2").val()) {
$("#failurebox").show();
}
}); // end of click function
});
I think I've gotten it to work using this sqlfiddle
I did it like this:
$(document).ready(function() {
$("#calbtn").click(function() {
if (!$("#tempsp").val() || !$("#temppv").val())
{
$("#failurebox").show();
}
else{
$("#failurebox").hide();
}
});// end of click function
});
EDIT: my bad I made a slight mistake but fixed it now, should work now
I have got the problem solved.
The problem was in my alert box. I have used dismissible alert box with a close button. When I get the error for first time I was just closing my alert box which is preventing from getting the alert again when I do it for the second time.
The click function was working fine but the problem was due to the alert box.
I have 9 pictures on each page, and when someone clicks on a picture the picture is opened in a fancybox, then if a person wants more information about the piece the click on a link inside the fancybox and the form opens inside a modal box.
All of the code works and the form is send through ajax then php.
The problem that I have is that all 9 pictures open the same form and when I client fills out the request form with their contact information, there is no way of me knowing which photo they are looking at.
It would be nice to add a "Hidden" value that is sent with the form so I can know which photo they are requesting the information.
I have looked around SO but to no avail
basic form
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send Request</button>
</form>
link to photo
<a class="fancybox" rel="gallery" href="inventory/inv_pictures/pic4.jpg"><img
src="inventory/inv_thumbs/thumb4.jpg" alt="Antique Furniture - Pic 4"
id="gallery"/></a>
I figured that maybe there is away to add a title tag or use the alt tag under the tag
that the form can pick up and send it as a "hidden" item. That way each photo can still access the same form but then I can know which item they are requesting for.
Sorry for not posting the whole code for fancy box.
but here it is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
<link rel="stylesheet" href="../js/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />
<script type="text/javascript" src="../js/source/jquery.fancybox.pack.js?v=2.1.5"> </script>
<script type="text/javascript">
$(".fancybox").fancybox({
afterLoad: function() {
this.title = '<a class="modalbox" href= "#inline" >Request more information</a> ' + this.title;
},
helpers : {
title: {
type: 'inside'
}
}
});
</script>
<!-- Hidden inline form -->
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<input type="hidden" id="link" name="link" value="">
<button id="send">Send Request</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\ [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p> <strong>Success! Your request has been sent. We will respond to it as soon as possible. </strong></p>");
setTimeout("$.fancybox.close()", 3000);
});
}
}
});
}
});
});
</script>
As I can see the link you are giving to fancybox is a direct link to a picture.
I am confused how you get a link to the form inside the modal as it doesn't seem to be coded here.
What I would suggest is, instead of giving direct picture link, create another page and code that page to collect a pic url/id from by GET/POST and display the corresponding pic and then embed this page into the fancybox.
So basically what I am saying is, pass the pic id/path from url that you pass to the fancybox, collect it and then further pass it to the form link