Get old value from dynamic input in Laravel with JavaScript? - javascript

I want to get the old value from dynamic input on Laravel. If it's a regular input, I only need {{ old ('name') }}. But what if the input is dynamic?
View
<tr>
<td>
<input type="text" name="name_progress[]"
value="{{ old('name_progress[]') }}"
placeholder="Enter name" class="form-control"/>
</td>
<td>
<input type="text" name="payment_percentage[]"
value="{{ old('payment_percentage[]') }}"
placeholder="Enter % invoice" class="form-control"/>
</td>
<td>
<a type="button" class="btn btn-danger remove-tr">-</a>
</td>
</tr>
JavaScript
<script type="text/javascript">
$("#add-btn").click(function () {
var tr = '<tr>' +
'<td>' +
'<input type="text" name="name_progress[]" ' +
'placeholder="Enter name" class="form-control" /></td>' +
'<td><input type = "text" name = "payment_percentage[]" ' +
'placeholder = "Enter per_invoice" class = "form-control" />' +
'</td>' +
'<td><a type="button" class="btn btn-danger remove-tr">-</a></td>' +
'</tr>';
$("#dynamicProgress").append(tr);
});
$(document).on('click', '.remove-tr', function () {
$(this).parents('tr').remove();
});
</script>

Since name_progress and payment_percentage fields are arrays, you may simply loop through the old input values.
#forelse (old('name_progress', []) as $i => $name_progress)
<tr>
<td>
<input type="text" name="name_progress[]" value="{{ $name_progress }}" placeholder="Enter name" class="form-control" />
</td>
<td>
<input type="text" name="payment_percentage[]" value="{{ old('payment_percentage')[$i] }}" placeholder="Enter % invoice" class="form-control" />
</td>
<td>
<a type="button" class="btn btn-danger remove-tr">-</a>
</td>
</tr>
#empty
<tr>
<td>
<input type="text" name="name_progress[]" placeholder="Enter name" class="form-control" />
</td>
<td>
<input type="text" name="payment_percentage[]" placeholder="Enter % invoice" class="form-control" />
</td>
<td>
<a type="button" class="btn btn-danger remove-tr">-</a>
</td>
</tr>
#endforelse
If old('name_progress') is empty or null, initial fields with empty values will be displayed.

Related

Remove selected items from a dropdown that contains items from a database table

I'm trying to solve a problem with my POS module on Laravel 8 that removes an item from a dropdown once it is selected. The items from the dropdown are from a database table. My POS module consists of a table with Name (dropdown), Quantity, Price, and Total with the ability to add more rows. Here's the code I'm working on right now as well as screenshot of my POS.
pos.blade.php
<tbody class="addMoreProduct">
<tr>
<td>1</td>
<td>
<select name="product_id[]" id="product_id" class="form-control product_id">
<option value="s" selected>Select Item</option>
#foreach($products as $product)
<option data-price="{{ $product->price }}"
value="{{ $product->id }}">{{ $product->name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text" name="quantity[]" id="quantity" class="form-control quantity" required>
</td>
<td>
<input type="number" name="price[]" id="price" step=".01" class="form-control price" readonly>
</td>
<td>
<input type="number" name="total_amount[]" id="total_amount" step=".01" class="form-control total_amount" readonly>
</td>
</tr>
</tbody>
<script>
//Add a row
$('.add_more').on('click', function(){
var product = $('.product_id').html();
var numberofrow = ($('.addMoreProduct tr').length - 0) + 1;
var tr = '<tr><td class="no">' + numberofrow + '</td>' +
'<td><select class="form-control product_id" name="product_id[]">' + product +
'</select></td>' +
'<td><input type="number" name="quantity[]" class="form-control quantity"></td>' +
'<td><input type="number" name="price[]" class="form-control price" readonly></td>' +
'<td><input type="number" name="total_amount[]" class="form-control total_amount" readonly></td>' +
'<td><a class="btn btn-danger btn-sm delete rounded-circle"><i class="fa fa-times-circle"></i></a></td>';
$('.addMoreProduct').append(tr);
});
//Delete a row
$('.addMoreProduct').delegate('.delete', 'click', function(){
$(this).parent().parent().remove();
});
</script>
I did try looking for this problem and came across these code, I tried, but unfortunately it did not solve my problem. Any help would be appreciated. Thank you.
var selectobject = document.getElementById("product_id");
for (var i=0; i<selectobject.length; i++) {
if (selectobject.options[i].value == 's')
selectobject.remove(i);
}
var index = $('#product_id').get(0).selectedIndex;
$('#product_id option:eq(' + index + ')').remove();

How to get dynamic id from a class name?

I am creating dynamic row with jquery. Now each row has different ID and common class name. How can I get the different id from same class name?
https://imgur.com/a/JCEhSna
See in the above picture. While I will select an option, then I want the ID name.
My Try:
HTML:
<tbody id="dynamic_row">
<tr id="firstTR">
<td>
<select name="product_id[]" class="invoiceProducts">
#foreach($products as $product)
<option value="{{ $product->id }}">{{ $product->productName }}</option>
#endforeach
</select>
</td>
<td>
<input type="text" class="form-control" name="itemDescription[]" id="itemDescription">
</td>
<td><input type="text" class="form-control" name="itemCost[]" id="itemCost"></td>
<td><input type="number" class="form-control" name="itemQuantity[]"></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</tbody>
$('#add').click(function(){
i++;
j=i;
console.log("Inside: " + i);
var html = '<tr id="row'+i+'" class="dynamic-added">';
html += '<td><select name="product_id[]" class="invoiceProducts" id="itemSelect'+i+'">#foreach($products as $product)<option value="{{ $product->id }}">{{ $product->productName }}</option>#endforeach</select></td>';
html += '<td><input type="text" class="form-control" name="itemDescription[]" id="itemDescription'+i+'"></td>';
html += '<td><input type="text" class="form-control" name="itemCost[]" id="itemCost'+i+'"></td>';
html += '<td><input type="text" class="form-control" name="itemQuantity[]" id="itemQuantity'+i+'"></td>';
html += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>';
let tb = $("table.invoice-table").find("tbody");
tb.append(html);
tb.find('tr').last().trigger('select-added');
});
$('body').on('change', '.invoiceProducts', function() {
var idOfSelect = $('.invoiceProducts').attr('id');
console.log("Select ID: " + idOfSelect);
});
Output:
Select ID: undefined
You can find the id using this.closest('tr').id in the change event
var i =0;
$('#add').click(function(){
i++;
j=i;
console.log("Inside: " + i);
var html = '<tr id="row'+i+'" class="dynamic-added">';
html += '<td><select name="product_id[]" class="invoiceProducts" id="itemSelect'+i+'">#foreach($products as $product)<option value="1">1</option><option value="2">2</option>#endforeach</select></td>';
html += '<td><input type="text" class="form-control" name="itemDescription[]" id="itemDescription'+i+'"></td>';
html += '<td><input type="text" class="form-control" name="itemCost[]" id="itemCost'+i+'"></td>';
html += '<td><input type="text" class="form-control" name="itemQuantity[]" id="itemQuantity'+i+'"></td>';
html += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>';
let tb = $("table.invoice-table").find("tbody");
tb.append(html);
tb.find('tr').last().trigger('select-added');
});
$('body').on('change', '.invoiceProducts', function() {
var idOfSelect = this.closest('tr').id
console.log("Select ID: " + idOfSelect);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="invoice-table">
<tbody id="dynamic_row">
<tr id="firstTR">
<td>
<select name="product_id[]" class="invoiceProducts">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
</select>
</td>
<td>
<input type="text" class="form-control" name="itemDescription[]" id="itemDescription">
</td>
<td><input type="text" class="form-control" name="itemCost[]" id="itemCost"></td>
<td><input type="number" class="form-control" name="itemQuantity[]"></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</tbody>
</table>
I think this could help
$('body').on('change', '.invoiceProducts', function() {
var idOfSelect = $(this).attr('id');
console.log("Select ID: " + idOfSelect);
});
The trick is select ID of changed element, right?
If you have <select> element, you should have <option> elements also as a children.
Just set "value" attribute of these children.
<select id="mySelect">
<option id="1" value="1"> A <option>
<option id="2" value="2"> B <option>
<option id="3" value="3"> C <option>
</select>
$("#mySelect").change(function(){
var selectedOption = $(this). children("option:selected").val();
console.log(selectedOption)
})
You should try with "document" It may help you Like:
$(document).on('change', '.invoiceProducts', function() {
var idOfSelect = $(this).attr('id');
console.log("Select ID: " + idOfSelect);
});

Enable Edit button if new record exists

I created a modal where I can insert new client record and edit the same record. But in relation to the edit button, I wanted it to be active only when there was a new record in the database and until the end of the day it was registered.
<a type="button" name="editar" id="'.$row["IdCliente"].'" data-toggle="modal" href="#add_data_Modal" class="btn btn-primary edit_data">Update</a>
I'm trying this way:
if(isset($_POST["employee_id3"]))
{
$output = '';
$query = "SELECT * FROM centrodb.PsicUtentes LEFT OUTER JOIN centrodb.PsicUtentesConsulta ON centrodb.PsicUtentesConsulta.CodigoUtente2 = centrodb.PsicUtentes.CodigoUtente WHERE centrodb.PsicUtentes.Id = '".$_POST["employee_id3"]."' ORDER BY IdConsulta DESC ";
$result = mysqli_query($conn, $query);
$output;
while($row = mysqli_fetch_array($result))
{
$dataAtual = DATE('Y-m-d');
$disabled = "";
if(DATE($row['Data2'])!=$dataAtual){
$disabled = "disabled";
}
$output .= '
<h4 class="modal-title">Histórico de Consultas</h4>
<div>
<button type="button" class="exibir botao" href="#" aria-hidden="true">+</button>
<button type="button" href="#" class="ocultar botao" aria-hidden="true">-</button>
</div>
<div class="conteudo">
<form method="post" id="insert_form6">
<div style="float:right">
<a type="button" name="edit3" id="'.$row["Id"].','.$row["IdConsulta"].'" data-toggle="modal" href="#add_data_Modal3" class="btn btn-primary edit_data3" "$disabled">Editar</a>
</div>
<br/>
<br/>
<br/>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<input type="Hidden" id="IdConsulta1" name="IdConsulta" class="form-control" value="'.$row["IdConsulta"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Data Consulta</label>
<input type="text" id="Data23" name="Data2" class="form-control" value="'.$row["Data2"].'" style="width:150px;" readonly="true" />
</td>
<td>
<label>Código Utente</label>
<input type="number" id="CodigoUtente5" name="CodigoUtente" value="'.$row["CodigoUtente"].'" class="form-control" style="width:100px;" readonly="true"/>
</td>
<td>
<label>Nome Utente</label>
<input type="text" id="Nome5" name="Nome" value="'.$row["Nome"].'" class="form-control" style="width:400px;" readonly="true"/>
</td>
<td>
<label>Data Nascimento</label>
<input type="date" id="DataNasc5" name="DataNasc" value="'.$row["DataNasc"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Data Admissao</label>
<input type="date" id="DataAdmissao5" name="DataAdmissao" value="'.$row["DataAdmissao"].'" class="form-control" style="width:150px;" readonly="true"/>
</td>
<td>
<label>Valência</label>
<input type="text" id="ValenciasDescricao5" name="ValenciasDescricao" value="'.$row["ValenciasDescricao"].'" class="form-control" style="width:200px;" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>Observação</label>
</p><textarea rows="6" cols="130" readonly="true">'.$row["Descricao"].'</textarea>
</td>
</tr>
</table>
</fieldset>
<fieldset class="grupo">
<table class="campo" cellspacing="10">
<tr>
<td>
<label>O Psicologo/a</label>
<input type="text" id="Colaborador2" name="Colaborador2" class="form-control" style="width:150px;" value="'.$row["Colaborador2"].'" readonly="true"/>
</td>
</tr>
</table>
</fieldset>
</form>
</div>
';
}
$output;
echo $output;
}
<script>
$(document).ready(function(){
$(document).on('click', '.edit_data3', function(){
var employee_id3 = $(this).attr("Id");
$.ajax({
url:"./fetch2",
method:"POST",
data:{employee_id3:employee_id3},
dataType:"json",
success:function(data){
$('#IdConsulta').val(data.IdConsulta);
$('#Data22').val(data.Data2);
$('#CodigoUtente6').val(data.CodigoUtente2);
$('#Descricao1').val(data.Descricao);
$('#Colaborador2').val(data.Colaborador2);
$('#employee_id3').val(data.Id);
$('#insert3').val("Gravar");
$('#add_data_Modal3').modal('show');
}
});
});
$('#insert_form7').on("submit", function(event){
event.preventDefault();
if($('#CodigoUtente6').val() == "")
{
alert("Código Utente é necessário");
}
else if($('#Descricao1').val() == "")
{
alert("Observação é necessária");
}
else
{
$.ajax({
url:".conexao9",
method:"POST",
data:$('#insert_form7').serialize()
,
beforeSend:function(){
$('#insert3').val("Inserting");
},
success:function(data){
$('#insert_form7')[0].reset();
$('#add_data_Modal3').modal('hide');
$('#employee_table').html(data);
location.reload("add_data_Modal3");
}
});
}
});
});
</script>
I created a variable with the current date that compares with the date of the record. I created an empty disabled variable. There I put this disabled variable in the link. If the date is different than the current date you put the disabled variable filled.The problem is that the button stays in the same asset.
Firstly your code is vulnerable to sql injection attacks and you should use prepared statements.
Then you have some syntax errors on your code.
The lines $output; are useless, delete them.
Change "$disabled" to '.$disabled'.
and put ?> before your <script> tag.

Get the input value of a specific form with javascript when the submit button is pressed

I have a page with a number of similar forms and would like to get the value of the input fields, when I press the submit button. I tried this on JSFiddle and it seems to be working. When I try this on my website, it returns "undefined".
HTML:
<tr>
<form action="editline.php" method="POST" class="editline">
<input type="hidden" name="editID" class="form-control id" value="123456">
<td data-label="Name"><textarea name="editName" class="form-control name" rows="1" autocomplete="off" required>Name1</textarea></td>
<td data-label="Address"><input type="text" name="editAddress" class="form-control address" value="Address1" autocomplete="off" required></td>
<td data-label="Colour"><input type="text" name="editColour" class="form-control colour" value="Colour1" autocomplete="off" required></td>
<td data-label="Edit"><button type="submit" class="btn btn-info btn-sm">Edit</button></td>
</form>
</tr>
<tr>
<form action="editline.php" method="POST" class="editline">
<input type="hidden" name="editID" class="form-control id" value="987654">
<td data-label="Name"><textarea name="editName" class="form-control name" rows="1" autocomplete="off" required>Name2</textarea></td>
<td data-label="Address"><input type="text" name="editAddress" class="form-control address" value="Address2" autocomplete="off" required></td>
<td data-label="Colour"><input type="text" name="editColour" class="form-control colour" value="Colour2" autocomplete="off" required></td>
<td data-label="Edit"><button type="submit" class="btn btn-info btn-sm">Edit</button></td>
</form>
</tr>
JS:
$('.editline').submit(function(e) {
e.preventDefault();
var id = $(this).find('input.id').val();
var name = $(this).find('textarea.name').val();
var address = $(this).find('input.address').val();
var colour = $(this).find('input.colour').val();
alert(id + ' ' + name + ' ' + address + ' ' + colour);
});
Is it a problem, that the forms are in tables? Is there an other way to just get the input values of the form where the submit button has been pressed?
Thanks in advance.
Edit:// Okay, since the problem is caused by the form being in a table, is there a workaround? I'd like to use a table for this.
Edit2:// This JS is working great, when the forms are in a table (FSFiddle):
$('.editline').submit(function(e) {
e.preventDefault();
var tr = $(this).closest('tr');
var id = tr.find('input.id').val();
var name = tr.find('textarea.name').val();
var address = tr.find('input.id').val();
var colour = tr.find('input.colour').val();
alert(id + ' ' + name + ' ' + address + ' ' + colour);
});
You can use only one form, then set the action to the button and get the closest line with it's inputs. Then ,in the click function you can call an ajax post to the form.
$('.editline button').click(function(e) {
e.preventDefault();
var tr = $(this).closest('tr');
var id = tr.find('input.id').val();
var name = tr.find('textarea.name').val();
var address = tr.find('input.address').val();
var colour = tr.find('input.colour').val();
alert(id + ' ' + name + ' ' + address + ' ' + colour);
});
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="editline.php" method="POST" class="editline">
<table>
<tr>
<td data-label="Name"><input type="hidden" name="editID" class="form-control id" value="123456"><textarea name="editName" class="form-control name" rows="1" autocomplete="off" required>Name1</textarea></td>
<td data-label="Address"><input type="text" name="editAddress" class="form-control address" value="Address1" autocomplete="off" required></td>
<td data-label="Colour"><input type="text" name="editColour" class="form-control colour" value="Colour1" autocomplete="off" required></td>
<td data-label="Edit"><button type="submit" class="btn btn-info btn-sm">Edit</button></td>
</tr>
<tr>
<td data-label="Name">
<input type="hidden" name="editID" class="form-control id" value="987654">
<textarea name="editName" class="form-control name" rows="1" autocomplete="off" required>Name2</textarea>
</td>
<td data-label="Address"><input type="text" name="editAddress" class="form-control address" value="Address2" autocomplete="off" required></td>
<td data-label="Colour"><input type="text" name="editColour" class="form-control colour" value="Colour2" autocomplete="off" required></td>
<td data-label="Edit"><button type="submit" class="btn btn-info btn-sm">Edit</button></td>
</tr>
</table>
</form>
Just wrap the entire table in the form. This would solve the issue of invalid HTML.
$('.editline').submit(function(e) {
e.preventDefault();
var id = $(this).find('input.id').val();
var name = $(this).find('textarea.name').val();
var address = $(this).find('input.address').val();
var colour = $(this).find('input.colour').val();
alert(id + ' ' + name + ' ' + address + ' ' + colour);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="editline.php" method="POST" class="editline">
<table>
<tr>
<td data-label="Name"><textarea name="editName" class="form-control name" rows="1" autocomplete="off" required>Name2</textarea></td>
<td data-label="Address"><input type="text" name="editAddress" class="form-control address" value="Address2" autocomplete="off" required></td>
<td data-label="Colour"><input type="text" name="editColour" class="form-control colour" value="Colour2" autocomplete="off" required></td>
<td data-label="Edit"><button type="submit" class="btn btn-info btn-sm">Edit</button> </td>
</tr>
</table>
<input type="hidden" name="editID" class="form-control id" value="987654">
</form>
For example:
function geti() {
var i = document.getElementById('i').value;
var iv = document.getElementById('iv');
iv.innerHTML = i;
}
<input type="text" id="i">
<button onclick="geti();">Click Me</button>
<p id="iv"></p>

serializeArray is not picking up dynamically created form

I have reviewed many Stack overflow threads on this topic most especially this one
jQuery serializeArray not picking up dynamically created form elements, but none was able to solve the problem
I am searching through firebase database for a match. if there is a match form A is presented but if there is no match, form B is presented.
return CatalogueDB.ref('/FSC/Misc/' + splitinput[index]).once('value').then(function(snapshot) {
console.log(snapshot.val())
var key = snapshot.val().NSN
var Name = snapshot.val().Nomenclature
var resultcard = `
<form id="myform">
<tr class="tr-shadow">
<td style="width: 90px;">
<div>${key}
</div>
<div>
<br>
<button type="button" class="btn btn-secondary mb-1 btn-sm" data-toggle="modal" data-target="#mediumModal">
Add Photos
</button>
</div>
</td><td>
<span class="block ">
${Name}
</span>
</td>
<td class="desc">
<input class="au-input au-input--sm" type="text" name="search" placeholder="i.e. 20 EA" style="width: 100px;" />
</td>
<td>
<span class="status--process">
<input class="au-input au-input--sm" type="text" name="search" placeholder="Search for datas & reports..." style="width: 90px;" />
</span>
</td>
<td>
<button type="button" class="btn btn-primary btn-md" onclick="postitem(this);">Submit</button>
</td>
</tr>
</form>
<tr class="spacer"></tr>
`
container.innerHTML += resultcard;
})
.catch(function(error) {
container.innerHTML += "";
var errorcard = `
<form id="myform">
<tr class="tr-shadow">
<td style="width: 90px;">
<div>${splitinput[index]}
</div>
</td>
<td>
<span class="status--process">
<input class="au-input au-input--sm" type="text" name="search" placeholder="Search for datas & reports..." style="width: 90px;" />
</span>
</td>
<td>
<span class="status--process">
<input class="au-input au-input--sm" type="text" name="search" placeholder="Search for datas & reports..." style="width: 90px;" />
</span>
</td>
<td class="desc">
<input class="au-input au-input--sm" type="text" name="search" placeholder="Search for datas & reports..." style="width: 90px;" />
</td>
<td>
<button type="button" class="btn btn-primary btn-md" onclick="postitem(this)">Submit</button>
</td>
</tr>
</form>
`
container.innerHTML += errorcard;
})
});
I want to get the input value from the form when submit button is clicked, hence this function
function postitem() {
var data = $('#myform').serializeArray();
console.log(data)
}
the problem is that it only shows empty array [] in console log.
The input values are not retrieved and displayed. How do I capture the input value onclick of the submit button
I'm wondering if one of these things might be causing the problem? I could be wrong but might be worth checking:
1.
Isn't the correct syntax this?
document.getElementById('container').innerHTML += resultcard;
.....instead of this?
container.innerHTML += resultcard;
2.
When including html in a JavaScript file, should the quotes around your html be implemented like this? (Also note the use of the 'standard quote' marks as opposed to using `back quote` marks.)
var resultcard =
'<form id="myform">' +
'<tr class="tr-shadow">' +
'<td style="width: 90px;">' +
.
.
.

Categories