How do you show/hide content inside a form with jquery? - php

How do you show/hide content in a form with jquery? When I click this button it just wants to submit.
$(document).ready(function(){
$( ".hide1" ).toggle();
$( ".show_next_div" ).click(function() {
$( ".hide1" ).toggle();
});
});
<form method="post" action="form_submit_action.php">
<button class="btn btn-primary show_next_div">Next Step</button>
<div class="hide1">
<p>something here hidden, now show with button press</p>
</div>
</form>

just add type="button" to the button tag to stop the submit action
<form method="post" action="form_submit_action.php">
<button type="button" class="btn btn-primary show_next_div">Next Step</button>
<div class="hide1">
<p>something here hidden, now show with button press</p>
</div>
</form>
Note : there is another option like stop event or return false onsubmit at the form

A button usually triggers the form action unless you override it.
So it is better to use input type="button"
Use the below in the form code - This should work !
<form method="post" action="form_submit_action.php">
<input type = "button" class="btn btn-primary show_next_div" value="Next Step" ></input>
<div class="hide1">
<p>something here hidden, now show with button press</p>
</div>
</form>

You can stop the propagation and default action of the click event in the event listener closure.
$(".show_next_div").click(function(e) {
e.preventDefault();
e.stopPropagation();
$(".hide1").toggle();
});

Related

Jquery replace strange behaviour in action form

I'm trying to create a modal popup that contains a confirmation delete button when I press delete on my index view, that button contains the ID of the object you are going to delete, I get it with jquery and replace the form action with it.
My problem is replace it not just replacing the placeholder ID on my action form, its replacing whole route with something like http://localhost/project/public/logout.
Delete button on my index.blade.php:
<button type="button" class="btn btn-outline-danger" data-toggle="modal" data-target="#deleteModal" data-id="{{$category->id}}"><i class="far fa-trash-alt"></i> Delete</button>
Form on modal:
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST">
#csrf
#method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
Jquery function that replaces the placeholderId on form action attribute:
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('form').attr('action');
modal.find('form').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
Result:
<form action="http://localhost/project/public/logout" method="POST">
Expected result:
<form action="http://localhost/project/public/manager/categories/1" method="POST">
give the submit form another id, and on jQuery find the form by that Id, cause right now, its gettign the first form on the DOM and thats logout form
basically put id="categoriesForm" and on jQuery $("#categoriesForm").submit()
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('#categoryForm').attr('action');
modal.find('#categoryForm').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
or what you can do, is capture when the form is submit, then prevent the default, do the confirmation pop up and then submit
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST" id="categoryForm">
#csrf
#method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
$(document).ready(function() {
$("#categoryForm").on('submit', function(e) {
e.preventDefault();
var confirmDelete = confirm("Are you sure you want to delete this category!");
if(confirmDelete) {
$(this).submit()
}
})
});

jQuery form submit not working php

I am creating a form that need to be submit using jQuery. Below is my code -
<script src="js/app.js" type="text/javascript"></script>
<form method="post" class="needs-validation" id="new-item" action="admin-add-inventory2.php">
<div class="mb-3">
<label>Item Name</label>
<input type="text" class="form-control" id="itemname" name="itemname" placeholder="Item name" required>
<span id='inmessage'>
</div>
<div class="mb-3">
<label>Description
<span class="text-muted">(Optional)</span>
</label>
<input type="text" class="form-control" id="description" name="description" placeholder="description...">
<span id='dmessage'>
</div>
<hr class="mb-4">
<input type="submit" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
</form>
<div id="form-messages"></div>
Code for app.js --
$(function() {
// Get the form.
var form = $('#new-item');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#itemname').val('');
$('#description').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, please try again.');
}
});
});
});
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Its not taking the question in stackoverflow due to more code and less text, so i am adding extra text to submit. Pls ignore the below text.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Please replace button type from submit to button.
Eg: <input type="button" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
Also replace $(form).submit(function(e) { with $("#submit").click(function(e) { if you want to call the AJAX code in your JS file on click of the button.

JQuery Ajax post method is not working in laravel

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
});
});

How to get button value + Bootstrap's Modal's Button value launched from PHP by first button

I want to get clickMe buttons value to confirm thing's from users by showing them confirm's modal.
Button:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<button type="submit" class="btn btn-primary" value="clickMeValue" name="clickMe">Click Me</button>
</form>
PHP:
<?php
if (isset($_POST['clickMe'])){
echo "<script>$(document).ready(function(){
$('#confirmModal').modal('show');
});</script>"; // showing modal from php
//after shoeing modal from php
if(isset($_POST['confirm'])){
echo $_POST['confirm'];
echo "<br/>";
echo $_POST['clickMe']; //this is not echoing
}
}
?>
How can i get clickMe value inside of bootstraps modals confirm thing.
Add an ID to the button and then here is how you can access the value of the clicked button ..
<button type="submit" id="my-button" class="btn btn-primary" value="clickMeValue" name="clickMe">Click Me</button>
And then ..
$(document).ready(function() {
$('#my-button').click(function() {
var the_value = $(this).val();
alert(the_value);
});
});

Getting the ID of the form when clicked sumbit button

I have set up a multiple form in a page with different IDs. I wanted to take ID of the form when one of the is submitted by submit btn. Here's what i got so far
<div class="form-wrap">
<form action="../administrator/apps/image_process_2D.php" method="post" enctype="multipart/form-data" id="upload_form_2D" class="submit_form">
<input name="__files[]" type="file" multiple />
<input name="__submit__" type="submit" class="btn btn-info submit_form" value="Upload"/>
</form>
<div class="form-wrap">
<form action="../administrator/apps/image_process_3D.php" method="post" enctype="multipart/form-data" id="upload_form_3D" class="submit_form">
<input name="__files[]" type="file" multiple />
<input name="__submit__" type="submit" class="btn btn-info submit_form" value="Upload"/>
</form>
<script>
var my_form_id = '#upload_form'; //ID of an element for response output
$(my_form_id).on( "submit", function(event) {
var post_url = $(this).attr("action");
//codes here//
});
</script>
so i need the 'my_form_id' to take the value if the form ID when the submit button is clicked.
Any help if much appreciated
You can traverse to closest parent form element using closest() and get the id of element using prop or attr:
$('form').on( "submit", function(event) {
console.log($(this).closest('form').prop('id'));
});
You can use .parent()
Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
$(my_form_id).on( "submit", function(event) {
console.log($(this).parent('form').attr('id'));
});

Categories