Remove all items button [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In this JavaScript code is something like you can delete the items by id and it is too long proces I want something shorter. So I wanna delete all items by pressing one button. I tried to edit it but I always fail.
JavaScript code :
var currentFormVisibilityStatus = false;
function SaveNotes() {
var category = document.getElementById("slSearchCategory").value;
var todo = document.getElementById("txtToDo").value;
if (category == "") {
alert("Please select Category.");
return;
}
var storage = JSON.parse(localStorage.getItem('ToDoList'));
var arrayLength = storage.length;
storage[arrayLength] = category;
storage[arrayLength + 1] = todo;
localStorage.setItem('ToDoList', JSON.stringify(storage));
category = "";
loadNotes();
clearNote();
}
function clearNote() {
var todo = document.getElementById("txtToDo");
todo.value = '';
}
function loadNotes() {
var storage = JSON.parse(localStorage.getItem('ToDoList'));
if (!storage) {
storage = [];
localStorage.setItem('ToDoList', JSON.stringify(storage));
}
var displayArea = document.getElementById("displayArea");
var currentFilter = document.getElementById("slSearchCategory").value;
var innerDiv = "";
for (var i = storage.length - 1; i >= 0; i = i - 2) {
if (currentFilter == storage[i - 1] || currentFilter == "") {
var todoColor = 'ffffff';
switch (storage[i - 1]) {
case 'Sales':
todoColor = 'ffffff';
break;
default:
todoColor = 'ffffff';
break;
}
innerDiv += "<div class='displayToDo' style='background:#" + todoColor + "'><input type='image' src='delete.png' width='15px' height='15px' onclick='removeMe(" + i + ")' /> " + storage[i] + "</div>"+ "</br>";
}
}
if (innerDiv != undefined) {
displayArea.innerHTML = innerDiv;
}
else {
displayArea.innerHTML = "";
}
}
function removeMe(itemId) {
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.splice(itemId - 1, 2);
localStorage.setItem('ToDoList', JSON.stringify(storage));
loadNotes();
}
onload = function () {
loadNotes();
ShowHideForm();
}
Html code :
<div class="headerDiv">
<span>Category :</span>
<select id="slSearchCategory" class="textBox" onchange="loadNotes()" style="width: 100px">
<option value="" selected="selected">All ToDo</option>
<option value="Personal">Personal</option>
<option value="HR">HR Query</option>
<option value="Payroll">Payroll</option>
<option id="Sales" value="Sales">Sales</option>
</select>
<span style="padding-left: 20px">Todo : </span>
<textarea id="txtToDo" class="textBox" rows="2" cols="20" style="width: 300px"></textarea>
<input type="button" onclick="SaveNotes()" name="Submit" class="submitButton" title="Submit"
value="Add Todo" />
</div>
<div id="displayArea">
</div>
<input type="button" onclick="removeAll();" value="Remove all"/>

you can create a new function and call it with an onclick event
the HTML code
<input type="button" value="Remove all" onclick="removeAll();"/>
the JavaScript function
function removeAll(){
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.length=0;
localStorage.setItem('ToDoList', JSON.stringify(storage));
loadNotes();
}
also take a look at How do I empty an array in JavaScript? so you know how to empty an array the right way

Related

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>

Javascript function submit not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
function submit() {
var text;
do {
text = "Não Completou o formelario";
}
while (x == "" && y == "");
document.getElementById("Erros").innerHTML = text;
var x = document.getElementById("PNome");
var y = document.getElementById("UNome");
var Person = function Person(first, last) {
this.firstName = first;
this.lastName = last;
};
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
var Pessoa = new Person(x, y);
document.getElementById("demo").innerHTML = Pessoa.name();
}
You return x and y.
x=document.getElementById("a")
That means x is an object. If you want the value of this object use
x=document.getElementById("a").value
This help you :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" name="frm" onsubmit="return s()">
first : <input type="text" id="PNome">
<br><br>
last : <input type="text" id="UNome">
<br><br>
<button type="submit">Submit</button>
</form>
<p id="demo"></p>
<p id="Erros"></p>
<script>
function s() {
var x = document.getElementById("PNome");
var y = document.getElementById("UNome");
var text = "";
if(x.value == "" && y.value == ""){
text = "Não Completou o formelario";
var Errors = document.getElementById("Erros").innerHTML = text;
return false;
}
var Person=function Person(first,last)
{
this.firstName=first;
this.lastName=last;
};
Person.prototype.name=function(){
return this.firstName + " " + this.lastName;
};
var Pessoa=new Person(x.value,y.value);
document.getElementById("demo").innerHTML=Pessoa.name();
return false;
}
</script>
</body>
</html>

Populate texbox value from url parameter using javascript?

I have the following script. After a user clicks submits I want to redirect the user to the same page and populate the drop down and input box with parameter values from the url. Unfortunately they are not populating once the redirect completes. I also need to strip off * from the FilterMultiValue parameter so that the textbox has the orginal value entered?
I've checked the parameter values using an alert function and that works?
<script type="text/javascript">
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
function RedirectUrl() {
var tb = document.getElementById("tbSearch").value;
var cs = document.getElementById("sfield").value;
var url = "";
if (tb != "") {
url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
window.location.href = "mypage.aspx?" + url;
var params = getUrlParams();
alert(params.FilterName);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = params.FilterMultiValue;
}
else {
return false;
}
}
function ClearUrl() {
window.location.href = "mypage.aspx";
document.getElementById("sfield").value = "";
document.getElementById('tbSearch').value = "";
}
</script>
Search Field:
<select id="sfield">
<option selected value="Title" >Title</option>
<option value="Body">Body</option>
</select>
Search Text:
<input type="text" id="tbSearch" />
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Clear" onclick="return ClearUrl();" />
window.location.href = "mypage.aspx?" + url;
reloads the page, which will result in all code after that not beeing executed.
What you want to do is to add code for pageload and check if the parameters are given, then populate the textbox.
Something like:
window.addEventListener('load', function(){
var params = getUrlParams();
if(typeof params.FilterName !== 'undefined'){
// removes the first and the last char from the string
var t = params.FilterMultiValue.substr(1, params.FilterMultiValue.length-2);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = t;
}
});

What is wrong with this Javascript? shopping cart

There is something in this javascript or html which is is allowing the checkboxes to be ticked but for not even half a second. (I need the checks to stay there!) I also need the additems function to work
var computer = new Array();
computer[0] = "10001, Nvidia Geforce GTX 690, 1200";
computer[1] = "10002, Raedon HD 7950, 450";
computer[2] = "20001, Ivy Bridge i7 3770, 400";
computer[3] = "20002, Ivy Bridge i7 3770k, 420";
computer[4] = "20003, Sandy Bridge i7 2700k, 340";
computer[5] = "20004, Bulldozer FX-8150, 270";
computer[6] = "30001, Antec eleven-hundred, 120";
computer[7] = "30002, Coolermaster HAF-X, 170";
computer[8] = "30003, Antec three-hundred, 50";
computer[9] = "30004, Corsair 550D, 160";
computer[10] = "40001, INTEL-ASrock fatal1ty Z77 Professional Motherboard, 250";
computer[11] = "40002, INTEL-ASrock Z77 extreme9 Motherboard, 350";
computer[12] = "40003, AMD-ASrock fatal1ty 990FX Professional Motherboard, 240";
computer[13] = "40004, AMD-ASUS Sabertooth 990FX Motherboard, 260";
Check all checkboxes function
function check() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 1;
} else {
inputs[x].checked = true;
}
}
}
Uncheck all checkboxes function
function uncheck() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 0;
} else {
inputs[x].checked = false;
}
}
}
add checked items to cart
function addItems() {
var leftSide = document.getElementById('table_container_left');
var rightSide = document.getElementById('table_container_right');
var inputs = leftSide.getElementByTagName('input');
var totalPrice = 0;
var basketTable = "<h3>My Basket:</h3><table><thead><tr><th>Item</th><th>Quantity</th><th>price</th><th>Sub-total</th></tr></thead><tbody>";
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].checked == true) {
var quantity = ParseFloat(inputs[x+1).value);
var itemName = computer[x/2].split(",")[1];
var itemPrice = parseFloat(computer[x/2].split(",")[2])
var itemTotal = parseFloat(quantity*itemPrice);
totalPrice += itemTotal;
basketTable += "<tr><td>"+itemName+"</td><td>"+quantity+"</td><td>$"+itemPrice+"</td><td>$"+itemTotal+"</td></tr>";
}
}
basketTable +=" <tr><td> colspan='3'><b>Total:</b></td><td><b>$"+totalPrice+"</b></td></tr></tbody><table>";
rightsSide.innerHTML = basketTable;
}
update quantity to 1 when item is checked
function updateQty(id) {
var targetRow = document.getElementById(id);
var qtyBox = targetRow.getElementsByTagName('input')[1];
if (qtyBox.value == 0) {
qtyBox.value = 1;
} else {
qtyBox.value = 0;
}
}
Here's the HTML as requested
<form name="myForm" action="index.html" method="post">
<div id="table_container_left">
<button onclick="check();">Select All</button>
<button onclick="uncheck();">Unselect All</button>
<button onclick="addItems();">Add Items</button>
<table>
<thead>
<th><u>Item Code</u></th>
<th><u>Item</u></th>
<th><u>Qty</u></th>
<th><u>Price</u></th>
</thead>
<tbody>
<script type="text/javascript">
for(x=0; x<=computer.length-1; x++) {
document.write("<tr id='"+x+"'><td><label><input type='checkbox' name='item' value='"+x+"' onclick='updateQty('"+x+"');'/> "+computer[x].split(",")[0]+"</label></td><td>"+computer[x].split (",")[1]+"</td><td> <input name='qty' id='qty' type='textbox' value='0' onchange='qtychange ('"+x+"');'/></td><td>$"+computer[x].split(",")[2]+"</td></tr>");
}
</script>
</tbody>
</table>
</div>
<div id="table_container_right">
<table id="shoppingBasket">
<input name='selectAll' type='button' value='Select All' onclick="itemSelected();"/>
<input name='clearAll' type='button' value='Clear All' onclick=""/>
<input name='removeItem(s)' type='button' value='Remove Item(s)' />
<input name='sortItemCode' type='button' value='Sort by Item Code' disabled='disabled' />
<input name='sortPrice' type='button' value='Sort by Price' disabled='disabled' />
</tbody>
</table>
</div>
</div>
</form>
Your JS syntax is way off, this is what it should look like
function addItems(field) {
for (i = 0; i <= field.length-1; i++)
{
if (field[i].checked == true)
{
if (computer[i]!=null) {
selected[i] = computer[i];
}
}
}
}
Half of your if statements are missing parentheses, that's some basic wrongfulness.
I don't know what and where should any of the variables be, but here is my best shot:
function addItems(field) {
var i;
for (i = 0; i < field.length; i++) {
if (field[i].checked === true) {
if (computer[i] !== null) {
selected[i] = computer[i];
}
}
}
}
You are using i = 0 rather than var i = 0, which will introduce a global variable. This could be a problem if you're writing similar code elsewhere.
Your if-statements are not statements at all. They look like pseudo-code. You're also comparing with = rather than ==, which will cause an assignment rather than a condition, even if you fix up your syntax.
You are not properly indenting your code, which will make you much more prone to introduce new errors.
These are the general issues I notice immediately. Of course, heaps of things could be wrong with this code. fields might not be an array, computer and selected might not match the size of fields, etc.
If you have any specific problem, please describe that, and we may be able to address it.

Need help in adding selected items from selectbox to div (dynamic addition)

I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}

Categories