Laravel insert dynamic input values with radio button - javascript

I am a beginner at Laravel, I want to insert a more dynamic address field to the database and I want to select one primary address using the radio button. I can able to add more address fields, but, I am unable to select one primary address because it's selecting all radio button values. I have given below using my code
This is My Blade File
<div>
<form action="{{ route('register.post') }}" enctype="multipart/form-data" accept-charset="utf-8" method="POST" >
#csrf
<div class="form-group row">
<label for="address" class="col-md-4 col-form-label text-md-left">Address</label>
<div>
<table id="dynamicAddRemove">
<tr>
<td><button type="button" name="add" id="add-btn" class="btn btn-success">Add More Details</button></td>
</tr>
<tr>
<td>
</td>
<tr>
</table>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Save
</button>
</div>
</form>
<div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
var i = 0;
$("#add-btn").click(function(){
//alert("I am an alert box!");
++i;
$("#dynamicAddRemove").append('<tr><td><input type="text" name="moreFields['+i+'][house_no]" placeholder="House No" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][street_name]" placeholder="Street Name" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][area]" placeholder="Area" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][pincode]" placeholder="Pincode" class="form-control" /></td><td style="padding-left:50px;"><input type="radio" class="form-check-input" name="moreFields['+i+'][primary_address]" value="'+i+'"></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
</script>
This is My Controller File
public function postRegistration(Request $request)
{
$id = DB::getPdo()->lastInsertId();
foreach ($request->moreFields as $key => $value) {
Address::create([
'user_id'=>$id,
'house_no'=>$value['house_no'],
'street_name'=>$value['street_name'],
'area'=>$value['area'],
'pincode'=>$value['pincode'],
'primary_address'=>$value['primary_address'],
]);
}

You dont need to make different name radio buttons use same name for all radio buttons so that user can not select other radio button after selecting one
<input type="radio" class="form-check-input" name="moreFields" value="'+i+'">

Laravel 8 Dynamic Radio Button Edit Page
This worked for me
#foreach($lease_stores as $lease_store)
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="lease_store_id" id="inlineRadio1" #if($general_details->lease_store_id==$lease_store->id) checked value="{{$lease_store->id}}"
#else value="{{$lease_store->id}}"
#endif>
<label class="form-check-label" for="inlineRadio2">{{$lease_store->name}} </label>
</div>
#endforeach
Controller master fetch
$lease_stores=Leasestore::all();

Related

How to check which checkbox is checked and save the data into database using Angular

I have 4 different checkboxes and when I check one(or two, or three, or all) I want to save some data into a database with a click on the button "Save". I'm using angular.
How I can do this?
I have this HTML code:
<div class="addMode1" style="display: none;">
<div class="form">
<form ng-submit="createReason(reasonsForm1.$valid)" name="reasonsForm1">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="database_address">Name of reason:</label>
<input type="text" class="form-control" ng-model="reasonname" placeholder="Име основание за добавяне" />
</div>
<div class="container">
<p>Using in::</p>
<input type="checkbox" ng-model="all">Buy<br>
<input type="checkbox" ng-checked="all">Sell<br>
<input type="checkbox" ng-checked="all">PKO<br>
<input type="checkbox" ng-checked="all">RKO
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-primary" id="cnlbtn1" type="button">Cancel</button>
<!--ng-click="createUser()"-->
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
And Angular code(createReason function which saves data from input box into the database):
$scope.createReason=function()
{
var objectToSave = {
name: $scope.reasonname,
};
defaultAdapter.query('INSERT INTO reasons(name) VALUES(:name)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
Please help me.
Thanks!
enter image description here
<label><input type="checkbox" name="test" ng-model="testModel['item1']" /> Testing</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
After this on submit check the testModel index value which one is true or false then send that value in database.
try this i hope its helpful to you

Submit form without redirection with ajax

i'm trying to make some things with ajax and it doesn't work.
I have a view with some divs where i will be all the functionality of the page.
The view's code is this:
#extends('cms.public.layouts.default')
#section('content')
<div class="col-md-10">
<h3 style="letter-spacing:40px;text-align:center;color:f15d5e;">PROYECTOS</h3>
</div>
<div id="listall"> <!-- DIV TO LIST ALL THE PROJECTS START HERE -->
<div class="col-md-2" style="padding:20px;">
<button type="button" id="buttoncreate" class="btn btn-danger">Crear Proyecto</button>
</div>
<table class="table">
<thead style="color:white">
<tr>
<th>Id</th>
<th>Slug</th>
<th>Order</th>
<th>Public</th>
<th>Path header</th>
<th>Path home</th>
<th>Fecha creación</th>
<th>Fecha ultima actualización</th>
<th><span class="glyphicon glyphicon-cog"></span></th>
</tr>
</thead>
<tbody style="color:white">
#foreach ($projects as $key => $project)
<tr>
<th>{{$project->id}}</th>
<td>{{$project->slug}}</td>
<td>{{$project->order}}</td>
<td>{{$project->public}}</td>
<td>{{$project->pathheader}}</td>
<td>{{$project->pathhome}}</td>
<td>{{ date('M j, Y', strtotime($project->created_at))}}</td>
<td>{{ date('M j, Y', strtotime($project->updated_at))}}</td>
<td>View Edit
#endforeach
</tr>
</tbody>
</table>
<br><br>
</div> <!-- DIV TO LIST ALL THE PROJECTS END HERE -->
<div id="form1" style="display:none;" class="col-md-8"> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 START HERE-->
<div>
<h3>Crear nuevo proyecto</h3>
</div>
<div id="formcreateproject">
<form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data" id="myForm" name="myForm">
<div class="form-group">
<label name="title">Slug:</label>
<input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
<label name="order">Order:</label>
<input type="number" id="order" name="order" class="form-control form-control-sm">
<label name="public">Public:</label>
<input type="number" id="public" name="public" class="form-control form-control-sm">
<label name="body">Header</label>
<input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp"><br>
<label name="body">Home</label>
<input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>
<input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
<input type="hidden" name="_token" value="{{ Session::token() }}">
<br><br><br>
</div>
</form>
</div>
</div> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 END HERE-->
<div id="form2" style="display:none;" class="col-md-6">
<div class="col-md-">
<h3>Crear nuevo proyecto</h3>
</div>
<form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data">
<div class="form-group">
<label name="title">Slug:</label>
<input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
<label name="order">Order:</label>
<input type="number" id="order" name="order" class="form-control form-control-sm">
<label name="public">Public:</label>
<input type="number" id="public" name="public" class="form-control form-control-sm">
<label name="body">Header</label>
<input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp"><br>
<label name="body">Home</label>
<input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>
<input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
<input type="hidden" name="_token" value="{{ Session::token() }}">
<br><br><br>
</div>
</form>
</div>
</div>
#stop
And the javascript function is this:
//Javascript view /projects/menu.blade.php
$(document).ready(function(){
$("#buttoncreate").click(function(){
$("#listall").hide();
$("#form1").fadeIn(1000);
$("#createprojectsubmit").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUpload',
type:'post',
data:$('#myForm'),
success: function(){
$("#form1").fadeOut(1000);
$("#form2").fadeIn(1000);
}
});
});
});
});
The function of hide the first div and fade in the second works, and it submit and create the new project. But url change and show me a white page.
My first thing to do is fadeOut the form1 and fadein the second form. It will be great, if when fadeOut the form1, in her space appears a tick/check.
Thanks a lot, any help will be appreciated.
you are calling submit event on button which does not belong to button. It belongs to form. So call the click event on button and use preventDefault() to stop the form to be submitted as
$("#createprojectsubmit").submit(function(e){
e.preventDefault();
//your further code goes here
}
use like this
$("#createprojectsubmit").click(function(e){
e.preventDefault();
//your further code goes here
}
You can also trigger the submit event on your form as
$("#myForm").submit(function(e){
e.preventDefault();
//your further code goes here
}
This is because you are mixing 2 ways to handle the submission of your form: the click on the button and the form submission itself.
The function submit as you call in your script is making the binding of the submit event when the button is clicked.
Here is how to bind your code only on the submit event of your form:
$(document).ready(function(){
$("#buttoncreate").click(function(){
$("#listall").hide();
$("#form1").fadeIn(1000);
$("#myForm").submit();
});
$("#myForm").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUpload',
type:'post',
data:$('#myForm'),
success: function(){
$("#form1").fadeOut(1000);
$("#form2").fadeIn(1000);
}
});
});
});
EDIT: Edited answer to take in account the click on the button.
At first, we bind the click event on the button to handle animations and trigger the form submission by calling submit function on the form.
Then, we bind the submit event on the form to handle the ajax call in replacement of the classic postback form submission.

How to perform if else operation in angular js depends on which radio button is selected?

I have two radio buttons in my project. Depending on which radio button is selected I need to send a command to back-end. I tried many ng-**** if else operations which didn't work for me. Kindly help me over the same
$scope.compareReference = function() {
if($scope.radoreslt is checked){
Factory.send("GetAddonData(CompareBkcXml,$scope.filetxt,File)");
}else{
Factory.send("GetAddonData(CompareBkcXml,$scope.filetxt,All)");
}
};
<div id="collapseTwo" class="panel-collapse collapse" aria-expanded="false">
<div class="box-body">
<div class="input-group">
<div class="form-group">
<label>
<input type="radio" ng-model="radoreslt" name="r1" checked>Compare with File Specific
</label>
<label>
<input type="radio" ng-model="radoreslt" name="r1">Compare All
</label>
</div>
<input type="text" class="form-control" ng-model="filetxt">
<span class="input-group-addon"><input type="File" onchange="copyMe(this)" ></span>
</div>
<br/>
<button class="btn btn-primary btn-sm" ng-click="compareReference()">Compare</button>
</div>
</div>
You should always pass a value attribute to each radio button since the bind model is updated with that value only. Here is an example.
<input type="radio" ng-model="radoreslt" name="r1" value="compareWithSpecific">
<input type="radio" ng-model="radoreslt" name="r1" value="compareAll">
JS
$scope.compareReference = function() {
if ($scope.radoreslt == "compareWithSpecific") {
Factory.send("GetAddonData(CompareBkcXml,$scope.filetxt,File)");
} else {
Factory.send("GetAddonData(CompareBkcXml,$scope.filetxt,All)");
}
};

Symfony search form without reload page

I use symnfony and have form for search entity by parameters, but when submit form my page reload, I don't know how realized search form when fill out fields and under form I have result without reload page, like write in filed some word and in this time under update block with result
this my form with action, action wait get parameters and rendering in this view with form and result
<div class="filters" id="filter_form">
<form action="{{ path('outbound_invoices') }}" method="get">
<div class="choice-group" role="group" data-toggle="buttons">
<label class="btn active">
<input type="radio" name="status" value={{ status_draft }} checked="checked">{{ status_draft|trans }}
</label>
<label class="btn">
<input type="radio" name="status" value={{ status_sent }}>{{ status_sent|trans }}
</label>
<label class="btn">
<input type="radio" name="status" value={{ status_paid }}>{{ status_paid|trans }}
</label>
</div>
<div class="choice-group" role="group" data-toggle="buttons">
<label class="btn active">
<input type="radio" name="type" value="all" checked="checked">all
</label>
<label class="btn">
<input type="radio" name="type" value="contract">contract
</label>
<label class="btn">
<input type="radio" name="type" value="other">other
</label>
</div>
<input name="search" id="filter-employees" placeholder="{{ 'search'|trans }}" class="form-control">
<p>from Date: <input type="text" name="from_date" id="from_datepicker" dataformatas="dd-mm-yyyy"></p>
<p>to Date: <input type="text" name="to_date" id="to_datepicker" dataformatas="dd-mm-yyyy"></p>
<input type="submit" value="Submit">
</form>
</div>
// block result
<table class="table">
<thead>
<tr>
<th>
{% trans %}invoice_number_short{% endtrans %}
</th>
</tr>
</thead>
<tbody>
{# #var outboundInvoice \AppBundle\Entity\OutboundInvoice#}
{% for outboundInvoice in outboundInvoices %}
<tr class="clickable" data-href="{{ path('outbound_invoices_show', {'id': outboundInvoice.id}) }}">
<td>
{{ outboundInvoice.invoiceNumber }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
in action I just create query builder for find entities and rendering in template. How it's realized with ajax without reload and search in real time ?
Here is an example to post your form via ajax with jQuery:
var form = $('#my-form');
$.post(
form.prop('action'), //action url
form.serializeArray(), //serialized form data
function(result){ //callback
console.log(result);
}
);
Use the AJAX as you'd normally do:
//add jquery here
$('#filter-employees').click(function(e){
e.preventDefault();
$.ajax({
action:"/invoices"
//...
}).done(function(resp));
});
Then in the controller action, you need to verify if the request is a XMLHttpRequest one, and create the functionality accordingly.
/**
* #Route("/invoices", name="outbound_invoices")
*/
public function processAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
//do work
}
return $this->redirectToRoute('whatever');
}
OBS: I would recommend you to use Angular for this type of things.

Multiple products in one form

I would like to add a functionality in my form, in which a user can add as many entries before hitting submit button, like a 'add to cart' functionality, show the added entries in same page, in a separate div with submit button then save those multiple entry in database using that submit button(in a separate div that shows added entry).
So far my form allows only entries on per submit bases, meaning is if the user wants to add another entry, he/she has to go back to the form and add and click to submit again.
<form method="POST" name="myForm" action="saveto.php">
<label> Speed Rating:</label>
<select name="speed_rating" required class="form-control" id="speed_rating" ></select>
<div class="form-group col-sm-8">
<label> Description:</label>
<select name="description" required class="form-control" id="description" >
</select>
</div>
<div class="form-group col-sm-4">
<label> Load Index:</label>
<select name="load_index" required class="form-control" id="load_index" >
</select>
</div>
<div class="form-group col-sm-6">
<label> Vendor:</label>
<select name="vendor" required class="form-control" id="vendor" >
</select>
<div class="note"> Recommended Vendor : <span id="recomvend"> </span> </div>
</div>
<div class="form-group col-sm-6">
<label> Quantity:</label>
<input type="text" required name="qty" class="form-control" id="qty"></div>
<div style="clear:both"> </div>
<input type="submit" name="submit" class="btn btn-primary smp" value="Submit">
<button id="clear" type="button" class="btn btn-primary smp smp2" > Reset </button>
</div>
<input type="submit" value="submit" name="submit">
</form>
How would you achieved this? My saveto.php is just a normal script that will process the submitted data to database, one entry in a per submit bases.
I created this jsfiddle https://jsfiddle.net/jy6vh4rp/31/
If that's what you are looking for then you should add this to your front end:
<form action="validate.php" method="post">
<div style="padding: 30px 0; text-align: center;">
<button type="button" onclick="createDOM()">Add</button>
<input type="submit" value="submit" name="submit" />
</div>
<div class="productsContainer"></div>
</form>
<script>
$(document).ready(function() {
id = 0;
createDOM = function() {
$(".productsContainer").append('<input type="text" id="' + id + '" name="products[]" value="' + id + '" />');
id++;
};
});
</script>
And this to your validation backend :
foreach($_POST['products'] as $prodInput){
$product = filter_var($prodInput,FILTER_SANITIZE_NUMBER_INT);
if( is_numeric($product) ){
echo $product;
}
}

Categories