in my SPRING project, I have an index.html file that has two forms. When you write a name in the first one and click submit the name is transferred to another one. The other form is connected with DB and displays it in a fieldset.
I have two buttons:
1)ADD to DB - when I ADD an item I can see it right away
2)DELETE an item from DB by ID - it works and deletes from DB, but the view isn't refreshed/reloaded. I need to refresh the whole page to see the results of DELETED item.
When I refresh the page it is going back to the first form with the name...
I wonder how to solve it.
I know something must be written inside the DELETE function.
PLEASE HELP.
<!DOCTYPE html>
<html lang="en" xmlns:https="http://www.w3.org/1999/xhtml" xmlns:http="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>SHOPPING LIST</title>
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css"
integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous">
</head>
<body>
<main style="width: 40%; margin: 0 auto">
<div id="welcome" style="text-align: center">
<h1>Introduce yourself</h1>
</div>
<form id="welcomeForm" class="pure-form pure-g pure-form-aligned">
<input class="pure-input-rounded pure-u-1" name="name" placeholder="name" id="text_name">
<button id="welcomeFormBtn" class="pure-button pure-button-primary pure-u-1">Submit</button>
</form>
<form id="AddForm" class="pure-form" style="text-align: center; display: none">
<fieldset>
<input id="name" class="pure-input-rounded pure-input-2-3" style="width: available" placeholder="name">
<input id="amount" class="pure-input-rounded pure-input-2-3" style="width: available" placeholder="amount">
<input id="uom" class="pure-input-rounded pure-input-2-3" style="width: available" placeholder="unit of measure">
<input id="idToDel" type="number" class="pure-input-rounded pure-input-2-3" style="width: available" placeholder="Please provide an id to delete">
</fieldset>
<fieldset>
<button id="addProduct" class="pure-button pure-button-primary">POST</button>
<button id="delProduct" class="pure-button pure-button-primary">DELETE</button>
<br>
<button id="print-btn" style="width: 50px; height: 50px; border-radius: 50%"><img style="width: 40px; height: 40px" src="https://cdn-icons-png.flaticon.com/512/3233/3233446.png" alt="PRINT"></button>
</fieldset>
<fieldset id="allProducts" >
</fieldset>
</form >
</main>
<script>
const API_URL = 'http://localhost:8080';
const API_URL_ADD = `${API_URL}/api`;
const API_URL_ALL = `${API_URL_ADD}/list`;
const pName = document.getElementById('name');
const pUom = document.getElementById('uom');
const pAmount = document.getElementById('amount');
AddFunction();
fetch(API_URL_ALL)
.then(processOkResponse)
.then(list => list.forEach(createNewProduct))
document.getElementById('addProduct').addEventListener('click', (event) => {
event.preventDefault();
fetch(API_URL_ALL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: pName.value, type : pUom.value, amount: pAmount.value })
})
.then(processOkResponse)
.then(createNewProduct)
.then(() => pName.value = '')
.then(() => pAmount.value = '')
.then(() => pUom.value = '')
.catch(console.warn);
});
function createNewProduct(product) {
const label = document.createElement('label');
const l1 = document.createElement('label');
const l2 = document.createElement('label');
const l3 = document.createElement('label');
const l4 = document.createElement('label');
label.classList.add('label');
l1.appendChild(document.createTextNode(` ID:${product.id}. `));
l2.appendChild(document.createTextNode(` ${product.name} `));
l3.appendChild(document.createTextNode(` ${product.amount} `));
l4.appendChild(document.createTextNode(` ${product.type} `));
label.appendChild(l1).appendChild(l2).appendChild(l3).appendChild(l4)
document.getElementById('allProducts').appendChild(label);
label.style.display= 'table';
label.style.paddingLeft='40%';
label.style.wordSpacing='30%';
}
document.getElementById('delProduct').addEventListener('click', (event) => {
event.preventDefault();
removeTodo();
});
function removeTodo() {
const d = document.getElementById('idToDel').value;
fetch(`${API_URL_ALL}/${d}`, { method: 'DELETE' })
.then(processOkResponse)
.catch(console.info)
}
function AddFunction(){
const welcomeForm = document.getElementById('welcomeForm');
document.getElementById('welcomeFormBtn').addEventListener('click', (event) => {
event.preventDefault();
const formObj = {
name: welcomeForm.elements.name.value,
};
fetch(`${API_URL_ADD}?${new URLSearchParams(formObj)}`)
.then(response => response.text())
.then((text) => {
document.getElementById('welcome').innerHTML = `
<h1>${text}</h1>
`;
welcomeForm.remove();
document.getElementById('AddForm').style.display = 'block';
});
});
}
document.getElementById('print-btn').addEventListener('click', (event) => {
event.preventDefault();
const f = document.getElementById("allProducts").innerHTML;
const a = window.open();
a.document.write(document.getElementById('welcome').innerHTML);
a.document.write(f);
a.print();
})
function processOkResponse(response = {}) {
if (response.ok) {
return response.json();
}
throw new Error(`Status not 200 (${response.status})`);
}
</script>
</body>
</html>
just like you've done .then(processOkResponse).then(createNewProduct) for adding a product, you should do the same for deletion as well.
.then(processOkResponse).then(deleteProduct) in your removeToDo function as well.
You should add a specific id to the label you're creating in createNewProduct(product) function like this
function createNewProduct(product) {
const label = document.createElement('label');
label.setAttribute('id', `pid-${product.id}`); // just this line to be added
//.... rest of your code
function deleteProduct(deleteApiResponse) {
// make sure to send id value of the deleted product
const {id} = deleteApiResponse;
const idToDel = `pid-${id}`;
// this does remove from HTML. just sets display: none
document.getElementById(idToDel).style.display = 'none';
// or remove from HTML like this. but for this you need the parentId
// to effectively remove the style(if any) on the id to be delete
//document.getElementById(idToDelParent).innerHTML = '';
}
So I wrote this multi-step form and it worked with the current code I have listed below until I changed it to send/receive data from php. The only thing that works is updating the progress bar but other then that it doesn't work. I have an idea why its not working cause of the actual button event isn't targeting the correct $(this).parent(); when I changed it from nextSection() to onSubmit(). I would possibly like to write it where it just selects the div class from an object then remove the current section but I wanna keep it the way I have for now.
$(".btn").on("click", nextSection);
function nextSection() {
if (typeof sections[current] !== "undefined") {
if(valid) {
current_section = $(this).parent();
next_section = $(this).parent().next();
console.log(current_section)
next_section.fadeIn();
current_section.remove();
current++;
updateProgressbar();
if (current === 1) {
let username = $(".username").val();
updatePenguinObj("username", username);
} else if (current === 2) {
let password = $(".password").val();
let email = $(".email").val();
updatePenguinObj("password", password);
updatePenguinObj("email", email);
} else if (current === 3) {
let name = $(".done");
name.text(name.text().replace(/%.+?%/, userData.username));
}
}
}
}
Then I changed it to the onSubmit() function w/ the validation responses.
$(".btn").on("click", onSubmit);
function onSubmit(event) {
event.preventDefault()
let request = new XMLHttpRequest()
request.onreadystatechange = () => handleResponse(request)
let formData = new FormData()
formData.append('username', userData.username);
formData.append('color', userData.colorId);
formData.append('password', userData.password);
formData.append('email', userData.email);
request.open('POST', 'scripts/php/create.php')
request.send(formData)
}
function handleResponse(request) {
if (request.readyState !== XMLHttpRequest.DONE || request.status !== 200) {
return
}
let response = JSON.parse(request.responseText);
if (!response) {
return
}
sectionValidation(response);
}
function sectionValidation(response) {
valid = true;
let section = $(sections[current]);
let input = section.find("input");
input.each(function() {
let inputs = $(this).attr('type') === "checkbox" ? !$(this).is(':checked') : input;
if(inputs) {
if (!response.valid) {
showError(response.message);
return valid = response.valid;
}
}
});
if(valid) {
nextSection(); //This is where nextSection is excuted to go to next page but doesnt.
}
}
I pastebin the entire code for each file type that way im not spamming this thread with just code. Overall i'm just trying to figure out how to fix it where I can go to the next section.
HTML - https://pastebin.com/eF8eXBfN
JS - https://pastebin.com/LuvYtYFc
PHP -
Basically just returns a JSON Object {message: "Test", valid: false} for the message responses and validation for it to go to next section.
if this isn't helpful I apologise in advance ....
because nextSection(); uses $(this) it won't have refrance to the button as it would have done when you used $(".btn").on("click", nextSection);
so you could add a reference of $(this) though to that function from the onSubmit
I create an example using your code, I dummy the response from the php but the rest is the same: https://jsfiddle.net/PatrickHume/8x6rodpn/
I don't know if this is better but it's another approach, I hope its helpful
let valid = true;
let sections = {
0: ".rules-section",
1: ".color-section",
2: ".info-section",
3: ".done-section"
};
let userData;
let current = 0,
current_section, next_section;
let currPalleteId = 0;
let penguinColors = {
"Blue": "003366",
"Green": "009900",
"Pink": "FF3399",
"Black": "333333",
"Red": "CC0000",
"Orange": "FF6600",
"Yellow": "FFCC00",
"Purple": "660099",
"Brown": "996600",
"Peach": "FF6666",
"Dark Green": "006600",
"Light Blue": "0099CC",
"Lime Green": "8AE302",
"Sensei Gray": "93A0A4",
"Aqua": "02A797",
"Arctic White": "F0F0D8",
};
window.onload = function() {
initalizeCreate();
};
function initalizeCreate() {
loadPalletes();
createPenguinObj();
$(".btn").on("click", onSubmit);
$(".show-password").on("click", togglePassword);
$("#startAgain").on("click", resetForm);
$(".random-username").on("click", randomUsername);
$(".username").keyup(function() {
let username = this.value;
updateDollName(username);
});
}
async function randomUsername() {
let url = "https://randomuser.me/api/";
let obj = await (await fetch(url)).json();
obj = obj.results[0];
let randuser = obj.login.username
$(".username").val(randuser);
updateDollName(randuser);
}
function updateDollName(username) {
username === "" ? $(".penguinName").text("Penguin Name") : $(".penguinName").text(username);
}
function togglePassword() {
$(this).toggleClass("fa-eye fa-eye-slash");
let input = $(this).prev('.info-section input');
input.attr('type', input.attr('type') === 'password' ? 'text' : 'password');
}
function resetForm() {
location.reload()
}
function nextSection($this) {
if (typeof sections[current] !== "undefined") {
if (valid) {
current_section = $($this).parent();
next_section = $($this).parent().next();
// console.log(current_section)
next_section.fadeIn();
current_section.remove();
current++;
updateProgressbar();
if (current === 1) {
let username = $(".username").val();
updatePenguinObj("username", username);
} else if (current === 2) {
let password = $(".password").val();
let email = $(".email").val();
updatePenguinObj("password", password);
updatePenguinObj("email", email);
} else if (current === 3) {
let name = $(".done");
name.text(name.text().replace(/%.+?%/, userData.username));
}
}
}
}
function onSubmit(event) {
event.preventDefault()
let request = new XMLHttpRequest()
request.onreadystatechange = () => handleResponse(request, $(this))
let formData = new FormData()
formData.append('username', userData.username);
formData.append('color', userData.colorId);
formData.append('password', userData.password);
formData.append('email', userData.email);
request.open('POST', 'https://reqbin.com/sample/post/json')
request.send(formData)
}
function handleResponse(request, $this) {
if (request.readyState !== XMLHttpRequest.DONE || request.status !== 200) {
return
}
var resp = `{
"message": "Test",
"valid": true
}`
let response = JSON.parse(resp);
if (!response) {
return
}
sectionValidation(response, $this);
}
function sectionValidation(response, $this) {
valid = true;
let section = $(sections[current]);
let input = section.find("input");
input.each(function() {
let inputs = $(this).attr('type') === "checkbox" ? !$(this).is(':checked') : input;
if (inputs) {
if (!response.valid) {
showError(response.message);
return valid = response.valid;
}
}
});
if (valid) {
nextSection($this);
}
}
function showError(text) {
$("#c_container").append(`<div class="error-block-container"><div class="error-container"><div id="error-content"><div id="error-msg-txt"> %text% </div><div id="error-btn"><div id="error-txt">Ok</div></div></div></div></div>`);
$("#error-btn").on("click", () => {
closeError();
});
let message = $("#error-msg-txt").html(text);
message.text(message.text().replace(/%.+?%/, message));
$(".error-block-container").fadeIn();
}
function closeError() {
$(".error-block-container").remove();
}
function updateProgressbar() {
let progressSteps = document.querySelectorAll(".progress-step");
progressSteps.forEach((progressStep, id) => {
if (id < current + 1) {
progressStep.classList.add("progress-step-active");
progressStep.classList.add("step");
} else {
progressStep.classList.remove("progress-step-active");
progressStep.classList.remove("step");
}
});
progressSteps.forEach((progressStep, id) => {
if (id < current) {
progressStep.classList.add("progress-step-check");
progressStep.classList.remove("progress-step-active");
} else {
progressStep.classList.remove("progress-step-check");
}
});
let progressActive = document.querySelectorAll(".step");
$(".progress").css("width", ((progressActive.length - 1) / (progressSteps.length - 1)) * 100 + "%");
}
function loadPalletes() {
let colorIndexNum = 0;
for (let palletes in penguinColors) {
let colorHex = penguinColors[palletes],
colorIndex = palletes,
colorIndexCurrNum = ++colorIndexNum;
$("#palletes").append(`<div data-id="${colorIndexCurrNum}" class="tinyPallete" style="background: #${colorHex}"></div> `);
}
$("#palletes").on("click", function(e) {
currPalleteId = $(e.target).attr("data-id");
e.currentTarget.querySelector(".active").classList.remove("active");
if (e.target.classList.contains("tinyPallete")) {
e.target.classList.add("active");
}
$(".doll").css("background-color", "#" + penguinColorByIndex(currPalleteId, false));
});
}
function penguinColorByIndex(index, keys) {
if (keys) {
return Object.keys(penguinColors)[--index];
}
return Object.values(penguinColors)[--index];
}
function updatePenguinObj(key, value) {
userData[key] = value;
return userData;
}
function createPenguinObj() {
userData = new Object();
userData.username = "";
userData.colorId = Number(currPalleteId);
userData.password = "";
userData.email = "";
return userData;
}
<html>
<head>
<title>Create Account</title>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<link type="text/css" rel="stylesheet" href="styles/fonts.css" />
<link type="text/css" rel="stylesheet" href="styles/create.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
</head>
<body>
<div id="c_header">
<h2>Create a Free Account</h2>
<div id="startAgain">Start Again</div>
<div class="c_progressBar">
<div class="progress" id="progress"></div>
<div class="progress-step progress-step-active"></div>
<div class="progress-step"></div>
<div class="progress-step"></div>
<div class="progress-step"></div>
</div>
</div>
<div id="c_container">
<div id="c_content">
<img id="logo" src="images/logo.png" /><img id="safety" src="images/safety.png" />
<form method="POST">
<div class="rules-section">
<div class="grid-rules">
<div class="item">
<div>
<div id="rule-title">Respect other penguins</div>
Club Penguin does not tolerate any swearing, bullying or mean behavior toward other penguins. Disciplinary action will be taken should any one of these occur while playing.
</div>
<img id="rule-image" src="images/respect.png" />
</div>
<div class="item">
<div>
<div id="rule-title">No inappropriate talk</div>
References to drugs and alcohol related activities, and sexual, racial or otherwise inappropriate talk are not permitted.
</div>
<img id="rule-image" src="images/inapp.png" />
</div>
<div class="item">
<div>
<div id="rule-title">Never reveal personal information</div>
The best way to stay safe online is to NEVER share your real name, phone number, address, email or passwords.
</div>
<img id="rule-image" src="images/personal.png" />
</div>
<div class="item">
<div>
<div id="rule-title">No cheating</div>
Use of third party programs to cheat is prohibited. Players who use any third party programs while playing risk being permanently banned.
</div>
<img id="rule-image" src="images/cheating.png" />
</div>
</div>
<hr />
<div id="agree"> <span class="toggle">
<input type="checkbox" id="agree" name="agree" /><label>I agree to the Club Penguin Rules.</label>
</span>
</div>
<div id="terms"> <span class="toggle">
<input type="checkbox" id="terms" name="terms" /><label>I agree to the <a id="hyper" href="#">Terms of Use</a></label>
</span>
</div>
<button class="btn" name="submit">Continue</button>
</div>
<div class="color-section">
<div id="color-form">
<p id="epname">Enter Your Penguin Name:</p>
<!--<span class="bubble">
<div id="bubble-msg"></div>
</span>-->
<input type="text" name="username" class="username" id="inputaligncenter" maxlength="16" /> <span toggle="#random_username" class="fa fa-fw fa-refresh random-username" title="Random Username"></span>
<div id="cpsmall">Minimum 4 characters: use only numbers, letters and spaces.</div>
<p id="cpname">Click on a Color:</p>
<div id="palletes"></div>
<img id="paintbucket" src="images/paintbucket.png" />
</div>
<div class="doll-container"> <img class="doll" src="images/doll.png" /> <span class="penguinName">Penguin Name</span> </div>
<button class="btn" name="submit">Continue</button>
</div>
<div class="info-section">
<div id="info-form">
<div id="ppname-wrapper">
Penguin Password:
<div id="ppsmall">This is the password you will use to login to Club Penguin. </div>
<input type="password" name="password" class="password" placeholder="Password"><span toggle="#password" class="fa fa-fw fa-eye field_icon show-password"></span>
<input type="password" name="cpassword" class="cpassword" placeholder="Confirm Password"><span toggle="#c_password" class="fa fa-fw fa-eye field_icon show-password"></span>
<p id="activatedTxt">your penguin must be activated before you will be able to play at club penguin</p>
Parent's Email Address:
<div id="ppsmall">Please enter your parent's valid email address. Club Penguin will send your parent an e-mail with an activation code.</div>
<div class="env"> <img src="images/envelope.png">
<input type="text" class="email" name="email">
</div>
</div>
<div class="doll-container fixed"> <img class="doll" src="images/doll.png" /> <span class="penguinName">Penguin Name</span> </div>
</div>
<button type="submit" class="btn" name="submit">Continue</button>
</div>
<div class="done-section">
<h2 class="done">%username%, your Account Has Been Successfully Created!</h2>
</div>
</form>
</div>
</div>
</body>
</html>
Solved my problem lol. I just wrote another function that just selects the classes from a div, removes the current, then adds 1 to the current section to show the next. If anyone has a better method feel free to correct me.
function gotoNextSection() {
current_section = $(sections[current]);
current_section.remove();
current++;
next_section = $(sections[current]);
next_section.fadeIn();
updateProgressbar();
}
I am working on a very basic task application with vanilla javascript. I have an array and from that, I am rendering the todos dynamically. I want to delete a todo when the checkbox is clicked.
I tried to create a form with the id of the todo in the hidden input and on change event submit the form and delete the todo but I'm generating all of them dynamically. Don't you think it will be a lot of code?
Is there a better way to do this?
Thank you
const todos = ['Complete the todo app', 'Write a script', 'Record a video', 'Publish the video']
const renderTodos = function (todos) {
document.querySelector('#todos').innerHTML = ''
todos.forEach(function (todo, index) {
const divElem = document.createElement('div')
divElem.classList.add(`item`, `item-${index}`)
document.querySelector('#todos').appendChild(divElem)
const checkboxElem = document.createElement('input')
checkboxElem.type = 'checkbox'
checkboxElem.name = 'deleteTodo'
document.querySelector(`.item-${index}`).appendChild(checkboxElem)
const titleElem = document.createElement('p')
titleElem.textContent = todo
document.querySelector(`.item-${index}`).appendChild(titleElem)
})
}
renderTodos(todos)
document.querySelector('#add-todo').addEventListener('submit', function (e) {
e.preventDefault()
if (e.target.elements.newItem.value === '') {
return
}
todos.push(e.target.elements.newItem.value)
e.target.elements.newItem.value = ''
renderTodos(todos)
})
<div id="todos"></div>
<form class="item" id="add-todo" action="">
<input
type="text"
name="newItem"
placeholder="New Item"
autocomplete="off"
/>
<button type="submit" name="list">+</button>
</form>
use remove method :
const DomParser = new DOMParser()
, todoAll = document.getElementById('todos')
, todoForm = document.getElementById('add-todo')
, todos = ['Complete the todo app', 'Write a script', 'Record a video', 'Publish the video']
;
function todoAdding(todo, index)
{
let elmZ = `<div class="item item-${index}"><input type="checkbox" name="deleteTodo"><p>${todo}</p></div>`;
let inZ = DomParser.parseFromString( elmZ, 'text/html');
todoAll.appendChild( inZ.body.firstChild )
}
function renderTodos(todos)
{
document.querySelector('#todos').innerHTML = ''
todos.forEach( todoAdding )
}
todoForm.onclick = e =>
{
e.preventDefault()
if (todoForm.newItem.value === '') return
todos.push(todoForm.newItem.value)
todoForm.newItem.value = ''
renderTodos(todos)
}
todoAll.onclick = e =>
{
if (!e.target.matches('input[type=checkbox]')) return
let suppIndex = todos.findIndex(todo=>todo===e.target.parentNode.querySelector('p').textContent)
todos.splice(suppIndex,1)
e.target.parentNode.remove()
}
renderTodos(todos) // initial case
<div id="todos"></div>
<form class="item" id="add-todo" action="">
<input
type="text"
name="newItem"
placeholder="New Item"
autocomplete="off"
/>
<button type="submit" name="list">+</button>
</form>
I have a number of textareas and when I click on a paragraph outside the text is supposed to be added to the textarea, it works but the text is also getting added to the textareas above.
I'm a bit stumped on why this is happening and as I have 10 textaraes so clicking a paragraph at the bottom of the page adds the text to all the other textareas above.
Javascript
$(document).ready(function () {
$("#PollutionPreventionDivScrollDisplay").hide();
$("#PollutionPreventionDivScroll").on("click", function () {
$("#PollutionPreventionDivScrollDisplay").toggle();
});
var cartlist = document.querySelector("#EnvironmentalActionPollutionPreventionIdeasForAction");
var items = document.querySelectorAll("[data-item]");
[].forEach.call(items, function (item) {
item.addEventListener("click", function (e) {
e.preventDefault();
cartlist.value += `\n${item.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#WasteDivScrollDisplay").hide();
$("#WasteDivScrollDisplayScroll").on("click", function () {
$("#WasteDivScrollDisplay").toggle();
});
var cartlistOne = document.querySelector("#EnvironmentalActionWasteManagementIdeasForAction");
var itemsOne = document.querySelectorAll("[data-item]");
[].forEach.call(itemsOne,
function (itemOne) {
itemOne.addEventListener("click", function (e) {
e.preventDefault();
cartlistOne.value += `\n${itemOne.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#EnergyDivScrollDisplay").hide();
$("#EnergyDivScrollDisplayScroll").on("click", function () {
$("#EnergyDivScrollDisplay").toggle();
});
var cartlistTwo = document.querySelector("#EnvironmentalActionEnergyIdeasForAction");
var itemsTwo = document.querySelectorAll("[data-item]");
[].forEach.call(itemsTwo,
function (itemTwo) {
itemTwo.addEventListener("click", function (c) {
c.preventDefault();
cartlistTwo.value += `\n${itemTwo.innerHTML}`;
});
});
});
Example of html
<div class="row">
<div id="PollutionPreventionDivScrollDisplay" class="col-md-12 border-colour fixed-height">
#foreach (var info in Model.EnvironmentalActionPollutionPreventionExtraInfo)
{
var countItems = counter++;
<p><a data-item="#countItems" href="#">#info</a></p>
}
</div>
</div>
<div class="col-md-4 border-colour-right">
<div class="form-group">
<span class="mouse-pointer text-danger" id="PollutionPreventionDivScroll">Click to add options</span>
<label class="sr-only" for="EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder">Environmental Action Pollution Prevention Ideas For Action</label>
#Html.TextAreaFor(x => x.EnvironmentalActionPollutionPreventionIdeasForAction, new { Class = "form-control", Placeholder = Model.EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder, rows = "8" })
</div>
</div>
All other code is the same except the sames are different
Ok silly mistake, I had all 'data-item' the same should have been 'data-item-one', 'data-item-two' etc
I want to select object from ng-repeat list and insert it in a array, then display each attribute of the selected object in a form. My problem is that I can not insert the object in array, but able to select it. I have narrowed down error. The checkList array is always empty no matter how frontend interface interacts with it(click on checkbox). I have no idea what cause this issue?
My code:
In product.view.html:
<h1>Welcome!</h1>
<p>You're in Product profolio!!</p>
<h3>All Products:</h3>
<ul>
<li ng-repeat="product in vm.allProducts track by $index">
{{product.id}} -- {{product.product_name}} -- {{product.product_image}} -- {{product.category}} -- {{product.published_time}} -- {{product.store_id}}
<input type="checkbox" ng-model="bool" ng-change = "vm.sync(bool,product)"> {{bool}}
</li>
</ul>
{{vm.checkList}}
<form novalidate class="simple-form">
Product Name: <input type="text" ng-model="vm.checkList[0].product_name" /><br />
product_image: <input type="text" ng-model="vm.checkList[0].product_image" /><br />
Category: <input type="text" ng-model="vm.checkList[0].category" /><br />
publish time: <input type="text" ng-model="vm.checkList[0].published_time" /><br />
store ID: <input type="number" ng-model="vm.checkList[0].store_id" /><br />
</form>
- <button ng-click="vm.createProduct(vm.checkList)">Create</button>
- <button ng-click="vm.updateProduct(vm.checkList)">Update</button>
- <button ng-click="vm.deleteProduct(vm.checkList.id)">Delete</button>
<p> </p>
<p>Logout</p>
In productController.js:
(function () {
'use strict';
angular
.module('app')
.controller('ProductController', ProductController);
ProductController.$inject = ['UserService', '$rootScope'];
function ProductController(UserService, $rootScope) {
var vm = this;
vm.allProducts = [];
vm.checkList = [];
vm.deleteProduct = deleteProduct;
vm.createProduct = createProduct;
vm.updateProduct = updateProduct;
vm.isChecked = isChecked;
vm.sync = sync;
initController();
function initController() {
loadAllProduct();
}
function loadCurrentProduct(productname) {
UserService.GetByUsername(username)
.then(function (product) {
vm.product = product;
});
}
function loadAllProduct() {
var url = 'http://127.0.0.1:8000/products';
UserService.GetAll(url)
.then(function (products) {
vm.allProducts = products;
});
}
function deleteProduct(id) {
var url = 'http://127.0.0.1:8000/products/';
UserService.Delete(url,id)
.then(function () {
console.log('flash page!')
loadAllProduct();
console.log('done!')
});
}
function createProduct(product){
var url = 'http://127.0.0.1:8000/products';
UserService.Create(url,product)
.then(function(){
console.log('has creaet product!')
loadAllProduct();
console.log('done!')
});
}
function updateProduct(product){
var url = 'http://127.0.0.1:8000/products/';
UserService.Update(url,product)
.then(function(){
console.log('has upadte product!')
loadAllProduct();
console.log('done!')
});
}
function sync(bool,product){
console.log("get into sync!");
console.log(bool);
if(bool)
{
vm.checkList.push[product];
console.log(vm.checkList);
console.log(product);
}
else
{
for(var i=0; i < vm.checkList.length; i++)
{
if(vm.checkList[i].id == product.id)
{
vm.checkList.splice(i,1);
}
}
}
}
}
})();
My page:
My error shows in console: