i want to search a string from the json object in javascript - javascript

I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>

You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful

Related

Appending Value to LocalStorage

I want to add new values to localStorage for my Pizza website in which I want the admin to be able to add pizzas. I have this code:
function store() {
var inputName = document.getElementById("name");
localStorage.setItem("name", inputName.value);
var inputDescription = document.getElementById("description");
localStorage.setItem("description", inputDescription.value);
var inputPrice = document.getElementById("price");
localStorage.setItem("price", inputPrice.value);
}
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
How do I add new pizzas for each time? Everytime I try to add a new value it just replaces the existing one.
function store() {
let inputName = document.getElementById("name");
let inputDescription = document.getElementById("description");
let inputPrice = document.getElementById("price");
let pizzas = []
if(localStorage.getItem("pizzas")){
pizzas = JSON.parse(localStorage.getItem("pizzas"));
}
let pizza = {}
pizza.name = inputName.value;
pizza.description = inputDescription.value;
pizza.price = inputPrice.value;
pizzas.push(pizza)
localStorage.setItem("pizzas", JSON.stringify(pizzas))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
</body>
</html>
This should help, first I check the localStorage some pizza is already stored in there or not, if there, then I take that parse it and add one more pizza to it from the form input, if not I create a completely new array and then add the value from the form input then store it in the localStorage.
first it would be better to replace your code to use "objects & arrays" instead of "string variables", like this example i made for you:
function store() {
var inputName = document.getElementById("name");
var inputDescription = document.getElementById("description");
var inputPrice = document.getElementById("price");
return ({
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
});
}
function updateStore(key = 'pizzas'){
let pizzasArray = JSON.parse(localStorage.get(key)) || [];
pizzasArray.push(store());
localStorage.setItem(key, JSON.stringify(pizzasArray));
}
You can keep it as json array in local storage.For Example;
function addStoreForArray(key, value) {
var storeArrayObj = localStorage.getItem(key);
if(storeArrayObj){
storeArrayObj = JSON.parse(storeArrayObj);
storeArrayObj.push(value);
} else {
storeArrayObj = [];
storeArrayObj.push(value);
}
localStorage.setItem(key, JSON.stringify(storeArrayObj));
}
addStoreForArray('pizzas', {name:'pizzaName', description: 'pizzaDescription', price: 10});
You can create an array to store many pizzas and to check if already exists you can call the getStorage() function and if storagePizzas includes your new pizza then update the value
arrayOfPizzas = []
function storeArray() {
let pizzaCreated = {}
pizzaCreated.name = document.getElementById("name").value;
pizzaCreated.description = document.getElementById("description").value;
pizzaCreated.price = document.getElementById("price").value;
let storageItems = getStorage();
// Check ...
arrayOfPizzas.push(pizzaCreated);
setStorage(arrayOfPizzas);
}
function setStorage(arr){
localStorage.setItem('arrayOfPizzas', JSON.stringify(arr));
}
function getStorage(){
return JSON.parse(localStorage.getItem('arrayOfPizzas');
}
You need to store the pizzas the user has created in an array. You can store the array in local storage, you just need to make sure you can serialize and deserialize it properly
Take the values from the input field
Grab your array of pizzas from local storage
If the array doesn't exist yet, getItem will return null, so you can give it an array to start off with.
Add the new pizza to the array
Save the pizzas array in local storage again.
function store() {
var newPizza = {
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
}
var pizzas = localStorage.getItem('pizzas')
if (!pizzas) {
pizzas = []
} else {
pizzas = JSON.parse(pizzas)
}
pizzas.push(newPizza)
localStorage.setItem('pizzas', JSON.stringify(pizzas))
}

javascript input value no update after manual input

If I enter something into t1, t2 is changed.
But if t2 already has manual input, it is not changed any more (and vice versa).
How can I change an input field that has already an manual input with javascript (without reloading the page!)?
<!DOCTYPE html>
<html>
<body>
inputfields are not changed, if they have/had an input already!<br />
<br />
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
<script>
function upd1() {
t2.setAttribute("value", "changed");
return true;
}
function upd2() {
t1.setAttribute("value", "changed");
return true;
}
</script>
</body>
</html>
You can also save an old value of each field to continue editing. Also it will show editing status on another field each time. It will be more comfortable for users.
inputfields are not changed, if they have/had an input already!<br />
<br />
<input type="text" id="t1" value="" onClick="renderFirstEl()" onInput="upd1()"><br /><br />
<input type="text" id="t2" value="" onClick="renderSecondEl()" onInput="upd2()">
<script>
let firstElValue = '';
let secondElValue = '';
function upd1() {
let el = document.querySelector('#t2');
el.value = 'changed';
return true;
}
function upd2() {
let el = document.querySelector('#t1');
el.value = 'changed';
return true;
}
function renderFirstEl() {
let el = document.querySelector('#t1');
secondElValue = document.querySelector('#t2').value;
el.value = firstElValue;
}
function renderSecondEl() {
let el = document.querySelector('#t2');
firstElValue = document.querySelector('#t1').value;
el.value = secondElValue;
}
</script>
The simple answer is use this:
function upd1() {
t2.value = 'changed';
return true;
}
function upd2() {
t1.value = 'changed';
return true;
}
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
Value changes after you type in one of the inputs and press Enter.
Because as said here: https://www.w3schools.com/jsref/met_element_setattribute.asp .
"The setAttribute() method adds the specified attribute to an element, and gives it the specified value.
If the specified attribute already exists, only the value is set/changed."

javascript.i want to fix input of textbox through javascript function

Hello guys I want to fix my textbox input
Here is my HTML code
<marquee behavior="slid" direction="right">Wellcome To Our Medicine Store</marquee>
<div id="inps">
Search Medicine: <input type="text" name="n1" id="n1">
<button onclick="search()" >Search</button>
<br><br>
Quantity Of Medicine:<input type="text" name="n3" id="n3">
<br><br>
Remaining Stock:<input type="text" name="n2" id="n2">
<br><br>
Total Bill:<input type="text" name="n4" id="n4">
</div>
Here is my function
<script>
var database=[];
// var total_quantity=100;
// var counter=0;
var panadol={
medicine_name:"panadol",
price:12,
total_stock:2000
};
var favrine={
medicine_name:"favrine",
price:38,
total_stock:1200
};
var rivotril={
medicine_name:"rivotril",
price:24,
total_stock:1500
};
database.push(panadol);
database.push(favrine);
database.push(rivotril);
console.log(database);
function search()
{
var searchmedi=document.getElementById("n1").value;
var getQuantity=document.getElementById("n3").value;
var medilist=" ";
var result="";
var remaing_stock;
for(var i=0;i<database.length;i++)
{
if(database[i].medicine_name==searchmedi)
{
// medilist +='<li>' + database[i].medicine_name +" ::" + "</li>";
// document.getElementById("result").innerHTML=medilist;
result= getQuantity*database[i].price;
document.getElementById("n4").value=result;
remaing_stock=database[i].total_stock-getQuantity;
document.getElementById("n2").value=remaing_stock;
} else {
console.log("not found");
}
}
}
</script>
I want only one thing when I enter my medicine name if its name exceeded to 10 alphabets it gives me error message.
How can I do this please help. How I check this condition.
I am new in this language and facing very problems please people help me.
Here you go, remember always to break for loop if you found your item.
You can use .length function to get the length of the string and use if statement to check if it is what you expect
var database=[];
// var total_quantity=100;
// var counter=0;
var panadol={
medicine_name:"panadol",
price:12,
total_stock:2000
};
var favrine={
medicine_name:"favrine",
price:38,
total_stock:1200
};
var rivotril={
medicine_name:"rivotril",
price:24,
total_stock:1500
};
database.push(panadol);
database.push(favrine);
database.push(rivotril);
console.log(database);
function search(){
var searchmedi=document.getElementById("n1").value;
if(searchmedi.length<10){
var getQuantity=document.getElementById("n3").value;
var medilist=" ";
var result="";
var remaing_stock;
for(var i=0;i<database.length;i++)
{
if(database[i].medicine_name==searchmedi)
{
result= getQuantity*database[i].price;
document.getElementById("n4").value=result;
remaing_stock=database[i].total_stock-getQuantity;
document.getElementById("n2").value=remaing_stock;
break; // remember to break if you found your item
}
else if(i==database.length-1){
console.log("Medicine not found");
}
}
}
else{
console.log("Name is too long");
}
}
<marquee behavior="slid" direction="right">Wellcome To Our Medicine Store</marquee>
<div id="inps">
Search Medicine: <input type="text" name="n1" id="n1">
<button onclick="search()" >Search</button>
<br><br>
Quantity Of Medicine:<input type="text" name="n3" id="n3">
<br><br>
Remaining Stock:<input type="text" name="n2" id="n2">
<br><br>
Total Bill:<input type="text" name="n4" id="n4">
</div>

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Categories

Resources