LARAVEL Insert MULTIPLE ROWS in database - javascript

I'm trying to insert multiple row data in two DB tables using single click but this code insert only one row at a time. When i try dd($request->all()); i got data in array but insert only one row. What is the problem and how can i fix it?
protected $table = 'biniyojan';
////Modified Controller//////
public function bbcreate(Request $request)
{
//dd($request->all());
$biniyojan_details = new BiniyojanDetails();
$biniyojan = new Biniyojan();
$biniyojan->details_id = $biniyojan_details->details_id;
$biniyojan->date = $request->date;
$biniyojan->ab = $request->ab;
$biniyojan->school = $request->school;
$biniyojan->behora = $request->behora;
$biniyojan->save();
$biniyojan_details = new BiniyojanDetails();
if (!empty($request->school)) {
for ($i = 0; $i < count((array)$request->school); $i++) {
$biniyojan_details['biniyojan_id'] = $biniyojan->id;
$biniyojan_details['school'] = $request->school[$i];
$biniyojan_details['source'] = $request->source[$i];
$biniyojan_details['kriyakalap'] = $request->kriyakalap[$i];
//$biniyojan_details->debit_credit = $request->debit_credit[$i];
//$biniyojan_details->debit_credit_type = $request->debit_credit_type[$i];
$biniyojan_details['cash'] = $request->cash[$i];
$biniyojan_details->save();
}
}
return redirect()->back()->with('status', 'Inserted');
}
/////View Blade////////
<form method="POST" action="{{ route('bbcreate') }}">
#csrf
<div class="form-row col-x1-3">
<div class="form-group col-md-2">
<input type="date" placeholder="मिति" value="#php echo $today; #endphp" name="date" class="form-control" id="inputCity" required>
</div>
<div class="form-group col-md-2">
<select id="inputState" placeholder="" name="ab" class="form-control" required>
<option>2079-080</option>
<option>2078-079</option>
</select>
</div>
<div class="form-group col-md-2">
<select id="inputState" name="school" class="form-control" required>
<option selected disabled>स्रोत पाउने संस्था </option>
#foreach ($school_array as $sch)
<option value="{{ $sch -> name }}">{{ $sch -> name}}</option>
#endforeach
</select>
</div>
</div>
<div id="form-field">
<div class="form-row col-x1-3">
<div class="form-group col-md-2">
<select id="source" name="source[]" class="form-control" required>
<option selected disabled value="">स्रोत</option>
<option>केन्द्र</option>
<option>प्रदेश</option>
<option>स्थानीय</option>
<option>अन्य</option>
</select>
</div>
<div class="form-group col-md-2">
<select id="kriyakalap" name="kriyakalap[]" class="form-control" required>
<option selected disabled>क्रियाकलाप</option>
#foreach ($bini as $bi)
<option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option>
#endforeach
</select>
#foreach ($bini as $bi)
#endforeach
</div>
<div class="form-group col-md-2">
<select name="debit_credit[]" id="debit_credit" class="form-control" >
<option selected="selected" disabled>डेबिट / क्रेडिट</option>
</select>
</div>
<div class="form-group col-md-2">
<select name="debit_credit_type[]" id="debit_credit_type" class="form-control" >
<option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" placeholder="रकम" name="cash[]" class="form-control" id="price" required>
</div>
<div class="form-group col-md-2">
<input type="button" class="btn btn-success" name="add" id="add" value="+">
</div>
</div>
</div>
<div class="form-row col-x1-3" style="justify-content:left ;">
<div class="form-group col-md-2">
<input type="text" placeholder="ब्यहोरा" name="behora" class="form-control" id="behora" required>
</div>
<div class="form-group col-md-2">
<input type="submit" id="submit" name="submit" value="राख्नुहोस्" class="btn btn-primary ">
</div>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
{{-- message --}}
{!! Toastr::message() !!}
</div>
#endif
</div>
<div form-row col-x1-3 id="showdata" class="showdata">
<p class="show_data"></p>
<p id="showdata" class="showdata"></p>
</div>
</form>
//////jQuery For Repeat form////////[enter image description here][1]
<!-- form repeat -->
<script type="text/javascript">
$(document).ready(function() {
var html = '<span><div id="form-field"> <div class="form-row col-x1-3"> <div class="form-group col-md-2"> <select id="source" name="source[]" class="form-control" required> <option selected disabled value="">स्रोत</option> <option>केन्द्र</option> <option>प्रदेश</option> <option>स्थानीय</option> <option>अन्य</option> </select> </div> <div class="form-group col-md-2"> <select id="kriyakalap" name="kriyakalap[]" class="form-control" required> <option selected disabled>क्रियाकलाप</option> #foreach ($bini as $bi) <option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option> #endforeach </select> #foreach ($bini as $bi) #endforeach </div> <div class="form-group col-md-2"> <select name="debit_credit[]" id="debit_credit" class="form-control" required> <option selected="selected" disabled>डेबिट / क्रेडिट</option> </select> </div> <div class="form-group col-md-2"> <select name="debit_credit_type[]" id="debit_credit_type" class="form-control" required> <option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option> </select> </div> <div class="form-group col-md-2"> <input type="text" placeholder="रकम" name="cash[]" class="form-control" id="price" required> </div> <div class="form-group col-md-2"> <input type="button" class="btn btn-danger" name="remove" id="remove" value="-"> </div> </div> </div></span>';
var max = 5;
var x = 1;
$("#add").click(function() {
if (x <= max) {
$("#form-field").append(html);
x++;
}
})
$("#form-field").on('click', '#remove', function() {
$(this).closest('span').remove();
x--;
});
});
</script>
<!-- form repeat -->

As #aynber pointed at, you need to move the line $biniyojan_details = new BiniyojanDetails(); inside the loop so it initiate a new object for each iteration.
Another solution would be to insert all the entries in the same time(better performance). For that, we prepare the data to be inserted first
public function bbcreate(Request $request)
{
//dd($request->all());
$biniyojan_details = new BiniyojanDetails();
$biniyojan = new Biniyojan();
$biniyojan->details_id = $biniyojan_details->details_id;
$biniyojan->date = $request->date;
$biniyojan->ab = $request->ab;
$biniyojan->school = $request->school;
$biniyojan->behora = $request->behora;
$biniyojan->save();
$biniyojanDetailsToBeInserted = [];
if (!empty($request->school)) {
for ($i = 0; $i < count((array)$request->school); $i++) {
$biniyojan_details = [];
$biniyojan_details['biniyojan_id'] = $biniyojan->id;
$biniyojan_details['school'] = $request->school[$i];
$biniyojan_details['source'] = $request->source[$i];
$biniyojan_details['kriyakalap'] = $request->kriyakalap[$i];
//$biniyojan_details['debit_credit'] = $request->debit_credit[$i];
//$biniyojan_details['debit_credit_type'] = $request->debit_credit_type[$i];
$biniyojan_details['cash'] = $request->cash[$i];
$biniyojanDetailsToBeInserted[] = $biniyojan_details;
}
}
if ($biniyojanDetailsToBeInserted) {
BiniyojanDetails::insert($biniyojanDetailsToBeInserted);
}
return redirect()->back()->with('status', 'Inserted');
}

Your code create only one row but the noticeable thing is that it create one row but with last data of the array.
Because you are not making object inside the loop it is outside of the loop so the loop runs on the same object and update its properties each time loop runs and save it.
Make object inside the loop so it make new object each time which means it will create new row each time instead of updating the same row.
There is a better way for this if you have same names of your array keys as database table columns.
Biniyojan::insert($request->data);
It works like this.
User::insert([
['name' => 'John', 'email' => 'john#example.com'],
['name' => 'Marina', 'email' => 'marina#example.com'],
]);

Related

How to convert string to integer then sum in javascript

I have two text boxes that will have currency strings in them which I then need to sum from the two text boxes into the total text box
srv_trk
but, the result an error like this:
how to fix this?
total_price
how to delete rupiah so that srvPrice and trkPrice return to integer and the total is not error?
the code:
<script>
const rupiah = (number)=>{
return new Intl.NumberFormat("id-ID", {
style: "currency",
currency: "IDR"
}).format(number);
}
</script>
<script type="text/javascript">
$("#service").change(function(){
var element = $("option:selected", this);
var srvPrice = element.attr("srvPrice");
var trkPrice = $('#trkPrice').val();
var total = Number(trkPrice) + Number(srvPrice);
$('#srvPrice').val(rupiah(srvPrice));
$('#totalPrice').val(rupiah(total));
});
</script>
<script type="text/javascript">
$("#trucking").change(function(){
var element = $("option:selected", this);
var trkPrice = element.attr("trkPrice");
var srvPrice = $('#srvPrice').val();
var total = Number(trkPrice) + Number(srvPrice);
$('#trkPrice').val(rupiah(trkPrice));
$('#totalPrice').val(rupiah(total));
});
</script>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="service">Service Name</label>
<div class="col-sm-8">
<select class="form-control selectric" name="service_id" id="service">
<option srvPrice="" selected>Select an Option</option>
#foreach ($service as $s)
#if(old('service_id') == $s->service_id)
<option value="{{ $s->service_id }}" {{ old('service_id') == $s->service_id ? 'selected' : '' }} srvPrice="{{ $s->service_price }}">{{ $s->service_name }}</option>
#else
<option value="{{ $s->service_id }}" srvPrice="{{ $s->service_price }}">{{ $s->service_name }}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="trucking">Trucking</label>
<div class="col-sm-8">
<select class="form-control selectric" name="trucking_id" id="trucking">
<option trkPrice="" selected>Select an Option</option>
#foreach ($trucking as $t)
#if(old('trucking_id') == $t->trucking_id)
<option value="{{ $t->trucking_id }}" {{ old('trucking_id') == $t->trucking_id ? 'selected' : '' }} trkPrice="{{ $t->trucking_price }}">{{ $t->trucking_name }}</option>
#else
<option value="{{ $t->trucking_id }}" trkPrice="{{ $t->trucking_price }}">{{ $t->trucking_name }}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Service Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="srvPrice" required readonly>
<div class="invalid-feedback">
Please make a selection on Service Option.
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Trucking Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="trkPrice" readonly>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Total Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="totalPrice" required readonly>
<div class="invalid-feedback">
Please make a selection on Service Option.
</div>
</div>
</div>
You can simply achieve this with a single line of code by using String.replace() method along with parseInt()
Live Demo :
const servicePrice = 'Rp 550.000,00';
const truckingPrice = 'Rp 100.000,00';
const totalPrice = parseInt(servicePrice.replace('Rp', '').trim()) + parseInt(truckingPrice.replace('Rp', '').trim());
console.log(totalPrice);
Maybe you can just use the replace function on both strings before adding them up. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
So just variableName.replace("Rp ", "")
If the Number is written in text format e.g. number = "5", then you can use parseInt(number) to convert it to integer, then you will be able to treat it as a normal number.
Example:
let text = "5", x = 10;
console.log(parseInt(text) + x);

Laravel Error Exception. Array to string Conversion

I'm trying to insert multiple row data in two databse table using single click but the only one row inserted .
protected $table = 'biniyojan';
it throw an another error like this:
(Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given)
How can i solve this issue??
////Modified Controller//////
public function bbcreate(Request $request)
{
//dd($request->all());
$biniyojan_details = new BiniyojanDetails();
$biniyojan = new Biniyojan();
$biniyojan->details_id = $biniyojan_details->details_id;
$biniyojan->date = $request->date;
$biniyojan->ab = $request->ab;
$biniyojan->school = $request->school;
$biniyojan->behora = $request->behora;
$biniyojan->save();
$biniyojan_details = new BiniyojanDetails();
if (!empty($request->school)) {
for ($i = 0; $i < count((array)$request->school); $i++) {
$biniyojan_details['biniyojan_id'] = $biniyojan->id;
$biniyojan_details['school'] = $request->school[$i];
$biniyojan_details['source'] = $request->source[$i];
$biniyojan_details['kriyakalap'] = $request->kriyakalap[$i];
//$biniyojan_details->debit_credit = $request->debit_credit[$i];
//$biniyojan_details->debit_credit_type = $request->debit_credit_type[$i];
$biniyojan_details['cash'] = $request->cash[$i];
$biniyojan_details->save();
}
}
return redirect()->back()->with('status', 'Inserted');
}
/////View Blade////////
<form method="POST" action="{{ route('bbcreate') }}">
#csrf
<div class="form-row col-x1-3">
<div class="form-group col-md-2">
<input type="date" placeholder="मिति" value="#php echo $today; #endphp" name="date[]" class="form-control" id="inputCity" required>
</div>
<div class="form-group col-md-2">
<select id="inputState" placeholder="" name="ab[]" class="form-control" required>
<option>2079-080</option>
<option>2078-079</option>
</select>
</div>
<div class="form-group col-md-2">
<select id="inputState" name="school[]" class="form-control" required>
<option selected disabled>स्रोत पाउने संस्था </option>
#foreach ($school_array as $sch)
<option value="{{ $sch -> name }}">{{ $sch -> name}}</option>
#endforeach
</select>
</div>
</div>
<div id="form-field">
<div class="form-row col-x1-3">
<div class="form-group col-md-2">
<select id="source" name="source[]" class="form-control" required>
<option selected disabled value="">स्रोत</option>
<option>केन्द्र</option>
<option>प्रदेश</option>
<option>स्थानीय</option>
<option>अन्य</option>
</select>
</div>
<div class="form-group col-md-2">
<select id="kriyakalap" name="kriyakalap[]" class="form-control" required>
<option selected disabled>क्रियाकलाप</option>
#foreach ($bini as $bi)
<option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-2">
<select name="debit_credit[]" id="debit_credit" class="form-control" required>
<option selected="selected" disabled>डेबिट / क्रेडिट</option>
</select>
</div>
<div class="form-group col-md-2">
<select name="debit_credit_type[]" id="debit_credit_type" class="form-control" required>
<option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" placeholder="रकम" name="cash[]" class="form-control" id="price" required>
</div>
<div class="form-group col-md-2">
<input type="button" class="btn btn-success" name="add" id="add" value="+">
</div>
</div>
</div>
<div class="form-row col-x1-3" style="justify-content:left ;">
<div class="form-group col-md-2">
<input type="text" placeholder="ब्यहोरा" name="behora[]" class="form-control" id="behora" required>
</div>
<div class="form-group col-md-2">
<input type="submit" id="submit" name="submit" value="राख्नुहोस्" class="btn btn-primary ">
</div>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
</div>
<div form-row col-x1-3 id="showdata" class="showdata">
<p class="show_data"></p>
<p id="showdata" class="showdata"></p>
</div>
</form>`enter code here`
//////jQuery For Repeat form////////[enter image description here][1]
<!-- form repeat -->
<script type="text/javascript">
$(document).ready(function() {
var html = '<span><div id="form-field"> <div class="form-row col-x1-3"> <div class="form-group col-md-2"> <select id="source" name="source[]" class="form-control" required> <option selected disabled value="">स्रोत</option> <option>केन्द्र</option> <option>प्रदेश</option> <option>स्थानीय</option> <option>अन्य</option> </select> </div> <div class="form-group col-md-2"> <select id="kriyakalap" name="kriyakalap[]" class="form-control" required> <option selected disabled>क्रियाकलाप</option> #foreach ($bini as $bi) <option value="{{$bi->kriyakalap}}"> {{$bi->kriyakalap}}</option> #endforeach </select> #foreach ($bini as $bi) #endforeach </div> <div class="form-group col-md-2"> <select name="debit_credit[]" id="debit_credit" class="form-control" required> <option selected="selected" disabled>डेबिट / क्रेडिट</option> </select> </div> <div class="form-group col-md-2"> <select name="debit_credit_type[]" id="debit_credit_type" class="form-control" required> <option selected="selected" disabled>डेबिट / क्रेडिट प्रकार</option> </select> </div> <div class="form-group col-md-2"> <input type="text" placeholder="रकम" name="cash[]" class="form-control" id="price" required> </div> <div class="form-group col-md-2"> <input type="button" class="btn btn-danger" name="remove" id="remove" value="-"> </div> </div> </div></span>';
var max = 5;
var x = 1;
$("#add").click(function() {
if (x <= max) {
$("#form-field").append(html);
x++;
}
})
$("#form-field").on('click', '#remove', function() {
$(this).closest('span').remove();
x--;
});
});
</script>
<!-- form repeat -->
[1]: https://i.stack.imgur.com/rzb3C.png
please try this:-
public function bbcreate(Request $request){
$biniyojan_details = new BiniyojanDetails();
$biniyojan_details->school = $request->school;
$biniyojan_details->source = $request->source;
$biniyojan_details->kriyakalap = $request->kriyakalap;
$biniyojan_details->debit_credit = $request->debit_credit;
$biniyojan_details->debit_credit_type = $request->debit_credit_type;
$biniyojan_details->cash = $request->cash;
$biniyojan_details->save();
if(!empty($request->school)){
for($i=0; $i< count($request->school); $i++){
$biniyojan = new Biniyojan();
$biniyojan->details_id = $biniyojan_details->id;
$biniyojan->date = $request->date[$i];
$biniyojan->ab = $request->ab[$i];
$biniyojan->school = $request->school[$i];
$biniyojan->behora = $request->behora[$i];
$biniyojan->save();
}
}
return redirect()->back()->with('status', 'Inserted');
}
As you said you are trying to insert multiple row data.
Then You must convert array into json to store it into database.
Do like this - json_encode($request->school,true);

Last-child not working inside iteration of div

In browser, the HTML is generated dynamically and is rendered as
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status0" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div><div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status1" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
The code is
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName =$this.find("input[type=text]:first-child").val();
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
I am trying to fetch values of contact numbers i.e with id's relationship-type-contact(n) values in the line "
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();"
This is fetching values of first-child textboxes in the variable relationshipContactNumber in the loop.
Please help !!!
This should work, use the .first() and .last() selectors.
Another way, if you have access to alter the HTML, is to add class names for the input fields and select them by using that instead.
function getData() {
var relationship_details_array = [];
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName = $this.find("input[type=text]").first().val();
var relationshipContactNumber = $this.find("input[type=text]").last().val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
console.log(relationship_details_array);
}
$("#getData").on("click", getData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="getData">Show data in console log</button>
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control">
<option value="">Select Relationship</option>
<option value="Father">Father</option>
<option value="Mother" selected>Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" value="Mommy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" value="1234" placeholder="Contact Number">
</div>
</div>
<div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control">
<option value="">Select Relationship</option>
<option value="Father" selected>Father</option>
<option value="Mother">Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" value="Daddy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" value="5678" placeholder="Contact Number">
</div>
</div>
</div>

angular: Function is not getting invoke

there is form in my html and I am using default validation "required" field property to validate the fields and checking using $valid at last and calling a function which is not getting invoke. when I removed "batchAttForm.$valid" then funciton is working but with that line its not getiing called. what can be the problem ??
html
<form id="batchAttForm" name="batchAttForm" class="form-horizontal">
<div class="form-group row">
<label class="control-label col-md-1" align="right" for="batchDate"></label>
<label class="control-label col-md-1" align="right" for="batchDate">Date</label>
<div class="col-md-2 ">
<div class="input-group" >
<span class="input-group-btn">
<button class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
<input type="text" id="batchDate" ng-change="dateChange()" name="batchDate" ng-model="batch.date" datepicker class="form-control digits" required>
</div>
</div>
<label class="control-label col-md-1" align="right" for="selectBatch">Batch</label>
<div class="col-md-2" >
<select id="selectBatch" name="selectBatch" ng-change="selectedBatch(batch.id)" ng-model="batch.id" class="form-control" required>
<option value="">Select</option>
<option ng-repeat="batch in batch.batches" value="{{batch.id}}">{{batch.batch}}</option>
</select>
</div>
<label class="control-label col-md-1" align="right" for="selectBatch">Timing</label>
<div class="col-md-2 ">
<select id="selectBatch" name="selectBatch" ng-model="batch.time" class="form-control" required>
<option value="">Select</option>
<option ng-repeat="time in batch.times" value="{{batch.time}}">{{time.start_time_string}} - {{time.end_time_string}}</option>
</select>
</div>
</div>
<br>
<div class="form-group form-action">
<label class="control-label col-md-3" align="right" for=""></label>
<div class="col-md-2">
<button type="submit" id="reschedule" ng-click="batchAttForm.$valid && reschedule()" class="btn btn-default"><i class="fa fa-undo"></i> Re-schedule</button>
</div>
<div class="col-md-2" >
<button type="submit" id="punchAtt" ng-click="batchAttForm.$valid && punchAttendance()" class="btn btn-success"> <i class="fa fa-check"></i> Punch </button>
</div>
</div>
</form>
controller
app.controller('batchAttendanceController',function($scope,apiCall) {
$scope.batch = {};
$scope.batch.date = moment().format("DD-MM-YYYY");
//methods
$scope.selectedBatch = selectedBatch;
$scope.punchAttendance = punchAttendance;
$scope.reschedule = reschedule;
$scope.dateChange = dateChange;
function punchAttendance() {
console.log("foo");
}
function reschedule() {
console.log("bar");
}
function dateChange() {
initController($scope.batch.date);
}
function selectedBatch(batch_id) {
var b = $scope.batch.batches;
for (var i=0; i < b.length; i++) {
if (b[i].id == batch_id) {
for (var j=0; j < b[i].batch_time.length; j++) {
b[i].batch_time[j].start_time_string = moment(b[i].batch_time[j].start_time,"HH:mm:ss").format("hh:mm A");
b[i].batch_time[j].end_time_string = moment(b[i].batch_time[j].end_time,"HH:mm:ss").format("hh:mm A");
}
$scope.batch.times = b[i].batch_time;
} else {
$scope.batch.times = [];
}
}
}
});
The reason for error is, you have two form elements select with same name and idattribute . This is the reason, your form is always invalid. .
<label class="control-label col-md-1" align="right" for="selectBatch">Batch</label>
<div class="col-md-2" >
<select id="selectBatch" name="selectBatch" ng-change="selectedBatch(batch.id)" ng-model="batch.id" class="form-control" required>//same name and id
<option value="">Select</option>
<option ng-repeat="batch in batch.batches" value="{{batch.id}}">{{batch.batch}}</option>
</select>
</div>
<label class="control-label col-md-1" align="right" for="selectBatch">Timing</label>
<div class="col-md-2 ">
<select id="selectBatch" name="selectBatch" ng-model="batch.time" class="form-control" required>//same name and id
<option value="">Select</option>
<option ng-repeat="time in batch.times" value="{{batch.time}}">{{time.start_time_string}} - {{time.end_time_string}}</option>
</select>
</div>
Try using the ng-click as ng-submit in form element and remove ng-click in button

using javascript to grab multiple id's

I have a table that lists all of the users invoices, and each invoice contains a pay button to allow them to pay the bill.
I currently have a loop that goes through each invoice and displays each invoice in its own row, and when a user goes to click on the pay button the JavaScript will show a selection box to use a saved card or a new card, if the user chooses a saved card then the JavaScript will show the other select box containing their saved cards, if the new card is chosen then the other input fields will be displayed, right now the showing and hiding part when selecting a saved card or new card ONLY works for the very first row in the table, no other rows work with that JavaScript, I'm sure its because JavaScript is grabbing that first id and stopping there. How can I do this correctly to where it grabs all of the ids and runs the code when the user chooses a saved card or new card on each invoice?
I created a JSFiddle to show my exact situation, can someone modify it to where it will work? I would really appreciate it!
https://jsfiddle.net/s0fbrcw6/1/
payments.blade.php
#if($payments)
#foreach($payments as $payment)
<tr>
<td>${{number_format(($payment->price /100), 2, '.', ' ')}}</td>
<td>{{$payment->product_name}}</td>
<td>{{$payment->created_at->toFormattedDateString()}}</td>
<td>{{$payment->created_at->addMonth()->toFormattedDateString()}}</td>
<td>{{$payment->reoccurring}}</td>
<td>{{$payment->status}}</td>
#if($payment->status == "Paid")
#else
<td>
<div class="add-payment-container">
<button class="toggle-add-payment mdl-button mdl-js-button mdl-js-ripple-effect pull-right btn-info">
#if($payment->reoccurring == "Yes")
Subscribe
#else
Pay Here
#endif
</button>
<div class="add-payment">
</br>
<form action="{{'/users/payment'}}" method="post"
id="checkout-form">
<input type="text" name="price" class="hidden"
value="{{$payment->price}}">
<input type="text" name="productName" class="hidden"
value="{{$payment->product_name}}">
<input type="text" name="paymentID" class="hidden"
value="{{$payment->id}}">
<input type="text" name="reoccurring" class="hidden"
value="{{$payment->reoccurring}}">
<div class="row">
<div class="col-sm-4">
<div id="paymentMethodDiv"
class="form-group label-floating">
{!! Form::label('paymentMethod', 'Payment Method') !!}
</br>
{!! Form::select('paymentMethod', ['Saved Card'=>'Saved Card','New Card'=>'New Card'], null, ['class' => 'browser-default mdl-selectfield', 'placeholder' => 'Choose Option', 'id' => 'paymentMethod'])!!}
</div>
</div>
<div class="col-sm-4">
<div id="savedCardsDiv" class="form-group label-floating" style="display: none;">
{!! Form::label('card', 'Previous Cards') !!}
</br>
{!! Form::select('card', $cardLast4, null, ['class' => 'browser-default mdl-selectfield', 'placeholder' => 'Choose Option', 'id' => 'savedCards'])!!}
</div>
</div>
<div class="col-md-4">
<div id="cardHolderNameDiv" class="form-group label-floating" style="display: none;">
<label class="control-label">Card Holder
Name</label>
<input type="text" id="card-name"
class="form-control">
</div>
</div>
<div class="col-md-4">
<div id="cardNumberDiv" class="form-group label-floating" style="display: none;">
<label class="control-label">Card Number</label>
<input type="text" id="card-number"
class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-5">
<div id="expirationMonthDiv" class="form-group label-floating" style="display: none;">
<label class="control-label">Expiration
Month</label>
<input type="text" id="card-expiry-month"
class="form-control">
</div>
</div>
<div class="col-md-5">
<div id="expirationYearDiv" class="form-group label-floating" style="display: none;">
<label class="control-label">Expiration Year</label>
<input type="text" id="card-expiry-year"
class="form-control">
</div>
</div>
<div class="col-md-2">
<div id="cvcDiv" class="form-group label-floating" style="display: none;">
<label class="control-label">CVC</label>
<input type="text" id="card-cvc"
class="form-control">
</div>
</div>
</div>
{{csrf_field()}}
<button type="submit" class="btn btn-primary pull-right">Make
Payment
</button>
<div class="clearfix"></div>
</form>
</div>
</div>
</td>
#endif
</tr>
<script>
var paymentMethodSelect = document.getElementById('paymentMethod');
paymentMethodSelect.onchange = function () {
if (paymentMethodSelect.value == 'Saved Card') {
document.getElementById("savedCardsDiv").style.display = "block";
document.getElementById("cardHolderNameDiv").style.display = "none";
document.getElementById("cardNumberDiv").style.display = "none";
document.getElementById("expirationMonthDiv").style.display = "none";
document.getElementById("expirationYearDiv").style.display = "none";
document.getElementById("cvcDiv").style.display = "none";
} else if (paymentMethodSelect.value == 'New Card') {
document.getElementById("savedCardsDiv").style.display = "none";
document.getElementById("cardHolderNameDiv").style.display = "block";
document.getElementById("cardNumberDiv").style.display = "block";
document.getElementById("expirationMonthDiv").style.display = "block";
document.getElementById("expirationYearDiv").style.display = "block";
document.getElementById("cvcDiv").style.display = "block";
} else {
document.getElementById("savedCardsDiv").style.display = "none";
document.getElementById("cardHolderNameDiv").style.display = "none";
document.getElementById("cardNumberDiv").style.display = "none";
document.getElementById("expirationMonthDiv").style.display = "none";
document.getElementById("expirationYearDiv").style.display = "none";
document.getElementById("cvcDiv").style.display = "none";
}
};
</script>
Advice: use jQuery. For situations like this, it significantly simplifies the js function part of it.
jsFiddle Solution: https://jsfiddle.net/brednmuc/4/
Brief Description:
Move away from using HTML IDs for everything and just make attributes that make the most sense for your web application. This methodology allows you to practically define an unlimited number of attributes that you can key certain behaviors off of. This also prevents conflicts with libraries that you may use / integrate with your project.
Code:
jQuery:
$(document).ready(function() {
$("select[name='paymentMethod']").change(function() {
var dropdownValue = $(this).val();
var transactionId = $(this).parent().attr('transactionId');
switch (dropdownValue) {
case 'Saved Card':
$("td[transactionId='" + transactionId + "'] div.savedCardsDiv").show();
break;
case 'New Card':
$("td[transactionId='" + transactionId + "'] div.savedCardsDiv").hide();
break;
default:
$("td[transactionId='" + transactionId + "'] div.savedCardsDiv").hide();
break;
};
});
});
HTML:
<table>
<tr>
<td transactionId="1">
<select name="paymentMethod" form="carform" class="paymentMethod">
<option value="">Select your option</option>
<option value="Saved Card">Saved Card</option>
<option value="New Card">New Card</option>
</select>
<div class="savedCardsDiv" style="display: none;">
<select name="savedCards" form="carform" class="savedCards">
<option value="">Select your option</option>
<option value="Saved Card">****4242</option>
<option value="New Card">****5423</option>
</select>
</div>
</td>
</tr>
<tr>
<td transactionId="2">
<select name="paymentMethod" form="carform" class="paymentMethod">
<option value="">Select your option</option>
<option value="Saved Card">Saved Card</option>
<option value="New Card">New Card</option>
</select>
<div class="savedCardsDiv" style="display: none;">
<select name="savedCards" form="carform" class="savedCards">
<option value="">Select your option</option>
<option value="Saved Card">****4242</option>
<option value="New Card">****5423</option>
</select>
</div>
</td>
</tr>
</table>

Categories