Save array of data - javascript

I have use jquery in adding new input type as long as the user want it.
#using (Html.BeginForm("addBatch_CARF", "CARF", FormMethod.Post, new { #name = "register" }))
{
#Html.ValidationSummary(true)
<div id="formAlert" class="alert alert-danger">
<a class="close">×</a>
<strong>Warning!</strong> Make sure all fields are filled and try again.
</div>
var catName = "";
var displayCan = "";
var candidates = "";
for (int i = 0; i < Model.Count; i++)
{
if (catName != Model[i].request_category)
{
<li class="list-group-item list-group-item-success">
#Html.DisplayFor(modelItem => Model[i].request_category)
<span class="pull-right" style="margin-right:60px;">Special Instructions</span>
</li>
catName = Model[i].request_category;
displayCan = catName;
}
if (displayCan == Model[i].request_category)
{
candidates = Model[i].request_name;
<div class="checkbox_request">
#Html.CheckBoxFor(model => model[i].isSelected, new { #class = "is_selected" })
#Html.DisplayFor(model => model[i].request_name)
#if(Model[i].request_name == "Folder Access")
{
<span class="label label-danger">Pls specify all the drive path. Note: For accessing of drives outside PETC please proceed to Online CARF</span>
}
<span class="pull-right">
#Html.EditorFor(model => model[i].special_instruction)
</span>
#Html.HiddenFor(model => model[i].request_type_id)
#Html.HiddenFor(model => model[i].system_roles_id)
</div>
}
}
<li class="list-group-item list-group-item-success">
Access to:
</li>
<div class="input_fields_wrap">
<button class="add_field_button btn btn-primary">Add More Fields</button>
<div>
<input type="text" name="fname[]" placeholder="First Name">
<input type="text" name="lname[]" placeholder="Last Name">
<input type="text" name="email_add[]" placeholder="Email Address">
<input type="text" name="user_id[]" placeholder="User ID">
</div>
</div>
<p class="request_btn">
<button type="submit" class="btn btn-primary" id="addbtn">Save</button>
</p>
}
Javascript
<script type="text/javascript">
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="fname[]" placeholder="First Name"/> <input type="text" name="lname[]" placeholder="Last Name"/> <input type="text" name="email_add[]" placeholder="Email Add"/> <input type="text" name="user_id[]" placeholder="User ID"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
</script>
How will I add this data to my database? I've tried this code in my controller but these following parameters have no values string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null.
[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list = null, string[] fname= null, string[] lname= null, string[] email_add= null, string[] user_id = null)
{
var data = db.Employees_All_vw.Where(x => x.NT_Name == #User.Identity.Name.Remove(0, 9).ToLower() && x.active_flag == true).FirstOrDefault();
//add data into CARF table
CARF carf = new CARF();
carf.requestor = data.Emp_Badge_No;
carf.carf_type = "BATCH CARF";
carf.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
carf.created_date = System.DateTime.Now;
carf.active_flag = true;
db.CARves.Add(carf);
db.SaveChanges();
int id = carf.carf_id;
//add data into Request Access Table
foreach (var i in list)
{
int val = 1;
bool y = Convert.ToBoolean(val);
if (i.isSelected == y)
{
Request_Access ra = new Request_Access();
ra.request_access_id = 1;
ra.carf_id = id;
ra.request_type_id = i.request_type_id;
ra.special_instruction = i.special_instruction;
ra.ra_assignee = i.system_roles_id;
ra.dept_approval = null;
ra.dept_approval_date = null;
ra.dept_remarks = null;
ra.final_approval = null;
ra.final_approval_date = null;
ra.final_remarks = null;
ra.acknowledge_by = null;
ra.acknowledge_date = null;
ra.journal = null;
ra.closed_by = null;
ra.closed_date = null;
ra.verified_by = null;
ra.verified_date = null;
db.Request_Access.Add(ra);
}
db.SaveChanges();
}
//add all list of names to the Batch CARF table
for (var x = 1; x < fname.Count(); x++)
{
//foreach(var x in fname)
Batch_CARF batch = new Batch_CARF();
batch.carf_id = id;
batch.fname = fname[x];
batch.lname = lname[x];
batch.email_add = email_add[x];
batch.user_id = user_id[x];
batch.active_flag = true;
db.Batch_CARF.Add(batch);
}
db.SaveChanges();
//send email notification to the data owner or final approver by batch
TempData["MessageAlert"] = "Successfully created!";
return RedirectToAction("Batch_CARF");
}

Related

Getting an Uncaught TypeError: Cannot set property 'onclick' of null with <script> at the end

I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>

need to append user data to array

my original question got answered but I realize that every time I try to push user data in the arrays it wouldn't allow me to do is there any another to append data to arrays or is the push method the only way. or should i create a new array................................................................
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
}
$("#name").focus();
};
// display scores
const displayScores = () => {
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea id="scores_display"></textarea>
</div>
</main>
All my previous notes were incorrect. Your adhoc $ const threw me off! My apologies.
The issue was you weren't calling displayScores() after updating the array. Plus, I added a line to that function to clear the existing text before looping through your data.
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
// add to the textarea
displayScores()
}
$("#name").focus();
};
// display scores
const displayScores = () => {
document.getElementById("scores_display").textContent = "";
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea rows="6" id="scores_display"></textarea>
</div>
</main>

Keep html that is generated with javascript after laravel POST with old data

There are 2 fields that belong together price and size. Some products have more then 1 size, so the html offers a button to generate more fields. However if some validation fails the fields are gone and not populated anymore.
Here are the non generated html fields
<div class="col-md-6">
<label for="price" class="form-label">Prijs* </label>
<input type="text"
name="priceAndSize[price][0]"
class="form-control #if($errors->has('priceAndSize.price.*')) border-danger #endif"
id="price"
value="{{ old('priceAndSize.price[0]') }}">
</div>
<div class="col-md-6">
<label for="stock" class="form-label">Inhoud in ml</label>
<input type="text"
name="priceAndSize[size][0]"
class="form-control"
id="size"
value="{{ old('priceAndSize.size[0]') }}">
</div>
With a button to generate more fields
<input type="button" class="btn btn-info mt-3 text-white" onclick="addInput()"
value="Meerdere prijzen & inhoud"/>
the javascript to generate the fields:
counter = 1;
function addInput() {
// Input
const newInputPrice = document.createElement('input');
newInputPrice.id = 'price' + counter;
newInputPrice.name = 'priceAndSize[price][' + counter + ']';
newInputPrice.type = 'text';
newInputPrice.className = 'form-control';
const newInputSize = document.createElement('input');
newInputSize.id = 'size' + counter;
newInputSize.name = 'priceAndSize[size][' + counter + ']';
newInputSize.type = 'text';
newInputSize.className = 'form-control';
// Label
const labelPrice = document.createElement('label');
labelPrice.htmlFor = 'price' + counter;
labelPrice.innerHTML = 'Prijs* ';
labelPrice.className = 'form-label';
const labelSize = document.createElement('label');
labelSize.htmlFor = 'size' + counter;
labelSize.innerHTML = 'Inhoud* ';
labelSize.className = 'form-label';
// New boostrap div
const newDivPrice = document.createElement('div');
newDivPrice.className = 'col-md-6';
const newDivSize = document.createElement('div');
newDivSize.className = 'col-md-6';
// Add label and input to div
newDivPrice.appendChild(labelPrice);
newDivPrice.appendChild(newInputPrice);
newDivSize.appendChild(labelSize);
newDivSize.appendChild(newInputSize);
const currentDiv = document.getElementById("test");
currentDiv.appendChild(newDivPrice);
currentDiv.appendChild(newDivSize);
counter++;
}
You can try this in your blade.
$priceAndSize = Request::old('priceAndSize');
#if(count($priceAndSize[price]) > 0)
for (var i = 1; i <= {{count($priceAndSize[price])}}; i++) {
addInput();
}
#elseif(count($priceAndSize[size]) > 0)
for (var i = 1; i <= {{count($priceAndSize[size])}}; i++) {
addInput();
}
#endif

Why does not work method of deleting items by name?

The method of removing products by their name does not work. I'm trying to delete using buttDelete.addEventListener but the deletion does not happen.
The logic of the deleteProductByName method is that when the name of product is received from input nameDelete it is checked the same products in shop.products array, then when the button delete is press (buttDelete), the product is deleted from the array and correspondingly from the table too, if the field is empty, then output alert that you need to fill out the field.
Help please fix that
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
// method to draw the table with product property (
// name, count, price)
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr id="total-price"><td colspan="3">Total price:
${shop.totalProductsPrice}</td></tr></tfoot>`;
}
}
// add new product by click
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value, parseInt(inputsAdd[2].value),
parseInt(inputsAdd[1].value)));
shop.show();
}, false);
// delete product by name after click
const formDelete = document.forms[1];
const nameDelete = formDelete.elements[0];
const buttDelete = formDelete.elements[1];
buttDelete.addEventListener('click', (e) => {
e.preventDefault();
shop.deleteProductByName(nameDelete.value);
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
Then I would use a console.log() or a debugger on
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
console.log("productName " + productName + "this.products[i].name" + this.products[i].name);
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
to see if you comparing the same names. To make sure your if statement is working as expected.

A black modal fade prevents me from typing in the text field

I've tried to create a modal that pops up when you click a link. I want the background to get faded but it seems like the whole page is getting blocked by the fade which prevents me from typing into the text field.
This is how it looks like: https://gyazo.com/d87f5beae17209d912169fde18bcdeb9
This is my code:
<div class="modal fade" id="new-item-modal" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4>Submit a New Item Ticket</h4>
</div>
<div class="modal-body">
<form id="new-item-form">
<div class="form-group">
<label for="new-item-name">Item Name</label>
<input class="form-control" id="new-item-name" placeholder="item name">
</div>
<div class="form-group">
<label for="new-item-price">Item Price</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input class="form-control" id="new-item-price" placeholder="item price">
</div>
</div>
<div class="form-group">
<label for="new-item-link">Item Link</label>
<input class="form-control" id="new-item-link" placeholder="item link">
</div>
<input type="submit" value="Submit" class="btn btn-lg btn-success">
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS:
<script>
$(function () {
var mAllItems = [];
$('#search').on('keypress', function (e) {
if (e.which === 13) {
var query = this.value;
var str = '<tr><th>Item Name</th><th>Item Price</th></tr>';
if (query.length > 0) {
$.getJSON('php/search-items.php', {query: query}, function (jsonObj) {
$('#results').html(str);
handleJsonResponse(jsonObj, function (data) {
var allItems = data['allItems'];
allItems.sort(function (a, b) {
var keyA = a['price'], keyB = b['price'];
return keyB - keyA;
});
mAllItems = [];
for (var i1 = 0; i1 < allItems.length; i1++) {
var item = allItems[i1];
var name = item['name'], price = getFormattedPrice(item['price']);
mAllItems.push({id: i1, name: name});
str += '<tr><td>' + name + '</td><td>' + price + ' <span class="item-price-change-btn" id="' + i1 + '">?</span></td></tr>';
}
$('#results').html(str);
$('.item-price-change-btn').on('click', itemPriceChangeHandler);
});
});
}
}
});
$('#new-item-form').on('submit', function () {
var itemName = $('#new-item-name').val(),
itemPrice = $('#new-item-price').val(),
itemLink = $('#new-item-link').val();
if (itemName.length === 0 || itemPrice.length === 0 || itemLink.length === 0) {
return false;
}
$.post('php/new-item-ticket.php', {name: itemName, price: itemPrice, link: itemLink}, function (jsonObj) {
handleJsonResponse(jsonObj, function (data) {
var message = data['message'];
successMsg(message);
$('#new-item-modal').modal('hide');
});
}, 'json');
return false;
});
function itemPriceChangeHandler () {
var id = parseInt(this.id);
var item = null;
for (var i1 = 0; i1 < mAllItems.length; i1++) {
var i = mAllItems[i1];
if (i['id'] === id) {
item = i;
}
}
$('#item-price-change-modal').modal('show');
$('#item-price-change-name').val(item['name']);
}
$('#item-price-change-form').on('submit', function () {
var name = $('#item-price-change-name').val(),
price = $('#item-price-change-price').val();
if (name.length === 0 || price.length === 0) {
return false;
}
$.post('php/item-price-change-ticket.php', {name: name, price: price}, function (jsonObj) {
handleJsonResponse(jsonObj, function (data) {
var message = data['message'];
successMsg(message);
$('#item-price-change-modal').modal('hide');
});
}, 'json');
return false;
});
});
</script>
try giving the inner element a higher z-index than the outer element.
Try applying
pointer-events: none;
To your overlay.

Categories