How to change values in a JSON array in Ajax - javascript

I have a json array as below in a hidden input. I am trying to update charge value using ajax on a button click.
[{"2018-06-19":{"charge":55000,"xcharge":15000}},
{"2018-06-20":{"charge":55000,"xcharge":15000}},
{"2018-06-21":{"charge":55000,"xcharge":15000}},
{"2018-06-22":{"charge":55000,"xcharge":15000}},
{"2018-06-23":{"charge":55000,"xcharge":15000}},
{"2018-06-24":{"charge":55000,"xcharge":15000}}]
My hidden input and Button
<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />
<button class="btn btn-default" type="button" onclick="change_room_charge();"><span class="glyphicon glyphicon-edit"></span></button>
I have tried it with this, but it is failing. charge value is not changing to new value.
function change_room_charge(){
var chargeArray = JSON.parse($('#chargeArray').val());
$.each(chargeArray, function (index, item) {
item[0].charge = item[0].charge.replace(666);
});
$('#chargeArray').val(JSON.stringify(chargeArray));
}
What i want is to change all existing charge values in hidden input to new value.

Whatever you are doing is very strange, but I'm going with it. You have your objects keyed by a date so you need to go get that key first. So in the code below, I get the key by finding all the keys for the item and taking the first one. From there you can set the value to whatever you want and then put it back into the input.
function change_room_charge() {
var chargeArray = JSON.parse($('#chargeArray').val());
$.each(chargeArray, function(index, item) {
var key = Object.keys(item)[0];
item[key].charge = 666;
});
$('#chargeArray').val(JSON.stringify(chargeArray));
console.log($('#chargeArray').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />
<button class="btn btn-default" type="button" onclick="change_room_charge();">
<span class="glyphicon glyphicon-edit"></span>
</button>

Related

Append to value attribute on button click

I am trying to make an input modify each time I click on a button. Kind of like a calculator. The will start at 0. When I click on the button "7" it will change its value to 7, when I click on "4" it will change to 74. Basically like a calculator.
I made this code that does modify the value of the input, however I can't seem to find how I can append more values to that values. Here is my code. Could someone help me?
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
$(".normal-input").attr("value", $(this).attr('value'));
}); <!-- The actual function. -->
As you can see the function completely replaces the previous value for the new one. I want it to append the values like in a calculator.
I would suggest you to try doing this:
Initialize value to zero
whenever click is called, multiply the current value by 10, and add the button value to it.
and you can remove the step attribute as per the use case.
In this function:
$(".normal-input").attr("value", $(this).attr('value'));
The second parameter is the value to set:
$(this).attr('value')
You need to have this as a combination of the previous value and the new value:
$(".normal-input").attr('value') + '' + $(this).attr('value')
The blank string is to make sure the final result is a string, not the addition of 2 numbers.
If you would like to convert it to a number, you can use parseInt():
const combinedNumber = $(".normal-input").attr('value') + '' + $(this).attr('value')
const intNumber = parseInt(combinedNumber)
The final code could look something like:
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
const existingValue = $(".normal-input").attr('value')
const newValue = $(this).attr('value'
const combinedValue = parseInt(existingValue + '' + newValue)
$(".normal-input").attr("value", combinedValue);
}); <!-- The actual function. -->
You just need to concat both the actual value and the value of button which is clicked to get required values .
Demo Code :
$('.my-buttons').click(function() {
var value = $(".normal-input").val()
var clicked_button = $(this).attr('value')
//use val and combined both value
$(".normal-input").val(value + "" + clicked_button);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="normal-input" type="number">
<button value="7" class="my-buttons" type="button"> 7 </button>
<button value="10" class="my-buttons" type="button"> 10 </button>
<button value="6" class="my-buttons" type="button"> 6 </button>

I want to know the value of the button I pressed in a table

I have an array of buttons arranged in each row of a table. When I click on a certain button, I want to know the row number the clicked button is positioned.
I add each time a row to existing table, where in each row there is a button. I tried to put each button in an array, so when I click on one of them, I will get the index number from the array. Didn't succeed
var btns[];
var btn=document.createElement("BUTTON");
btn.innerHTML="Edit";
btns.push(btn);
cell1.appendChild(btns[btn_num]);
btn_num=btn_num+1;
I expect to get the row number, so I can edit a specific row in a table.
You don't need to store button in memory var btns. I see a couple of practical ways to do this:
Create button with a class name
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<script>
function BtnEditClick(clickedElement){
var btns = document.getElementsByClassName("btn-edit")
var result = -1
for(var i=0;i<btns.length; i++) {
if(clickedElement == btns[i]){
result = i
}
}
if(result != -1)
alert("found " + result)
else
alert("not found")
}
</script>
Reference to the value using data-attr in html5
<button class="btn-edit" data-index="0" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" data-index="1" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" data-index="2" onclick="BtnEditClick(this)">Edit</button>
<script>
function BtnEditClick(clickedElement){
var index = clickedElement.getAttribute("data-index")
alert("click index: " + index)
}
</script>
Pass index directly to the function
<button class="btn-edit" data-index="0" onclick="BtnEditClick(0)">Edit</button>
<button class="btn-edit" data-index="1" onclick="BtnEditClick(1)">Edit</button>
<button class="btn-edit" data-index="2" onclick="BtnEditClick(2)">Edit</button>
<script>
function BtnEditClick(index){
alert("clicked on item:" + index)
}
</script>
Yes there are still a few other ways. For myself most of the time I use the second approach that get the element ( the button object that get clicked ) and then read the data that I want from data-attr ( you can define any data-attr you want e.g data-index, data-id ). This is very convenient, you will find it useful because sometimes you might need more data than just an index of the element inside the list. I hope it helps
One possible approach is: for each added button you can add an the HTML attribute id equal table row. Besides that, you can add the HTML attribute onclick="onClickButton(this.id)" to the created button. So you can use the folowing script to get the id value when the button gets clicked:
<script>
function onClickButton(e) {
console.log(e);
}
</script>

Not able to reset input field in laravel

I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}

Can't store todos to local storage

I'm learning JavaScript right now and one of the practice application I am doing is to make a to-do list to learn the basics. Right now I'm having a hard time saving my inputs onto the local storage. I look into the console and local storage of my browser and only see that a key "todos" is being created but no values are stored in it.
I was wondering if anyone can help. Please ignore the way I structured my coding. I am still learning. (I know there are better and more efficient ways to make a to-do list.)
My code:
<body>
<header class = "centerAlign ">to-do list </header>
<div class = "divA centerAlign input-group container" style = "list-style-type:none">
<input class = "form-inline input-lg" id="itemInput" "type="text" placeholder="add things to do"/>
<button class = "addButt btn btn-lg">
<span class="glyphicon glyphicon-plus"></span>
</button>
<ul class = "ulist1 container">
<!--List items gets inserted here-->
</ul>
</div>
<button class = "clearAll btn">Clear localStroage</button>
<script>
getTodos();
//press enter to submit
$("input").on('keydown',function(e){
if(e.keyCode ==13){
$("<li>").attr("class","apples").html(itemInput.value).fadeIn().appendTo(".ulist1");
$("<button>").attr("class","doneButt btn pull-left glyphicon glyphicon-ok").appendTo($(".apples").last());
$("<button>").attr("class","delButt btn pull-right glyphicon glyphicon-trash").appendTo($(".apples").last());
clearInput();
saveTodos();
}
});
//click the submit button
$(".addButt").click(function(){
$("<li>").attr("class","apples ").html(itemInput.value).fadeIn().appendTo(".ulist1");
$("<button>").attr("class","doneButt btn pull-left glyphicon glyphicon-ok").appendTo($(".apples").last());
$("<button>").attr("class","delButt btn pull-right glyphicon glyphicon-trash").appendTo($(".apples").last());
clearInput();
saveTodos()
});
//clears the input box for new text
function clearInput(){
itemInput.value = "";
}
//button to delete
$(".ulist1").on("click", ".delButt", function(e) {
e.preventDefault();
$(this).parent().fadeOut(function(){
$(this).remove();});
});
//put a line through the text and undo that line
$(".ulist1").on("click", ".doneButt", function(e) {
$(this).parents("li").toggleClass('withline');
});
//save data localStorage
$(".addButt").click(function(){
saveTodos();
});
function saveTodos(){
localStorage.setItem("todos", itemInput.value);
}
//get data from localStorage
function getTodos(){
localStorage.getItem("todos");
}
</script>
<script>//delete localstroage
$(".clearAll").click(function() {
window.localStorage.clear();
location.reload();
return false;
});
</script>
You call your own clearInput() function before you call saveTodos(). This means you first clear your input field and then save the value of the (now empty) input field to your local storage.
Therefore, you will always have the key 'todos' with an empty String as its value.
To be able to save your last entered input in your desired localStorage variable you'd just need to move the saveTodos() call before the clearInput() call.
However your use case suggests that you surely want to save more than just the last entered input but several todos. To achieve that, you will have to either use a seperate key for every entry or story all entries as an array. As LocalStorage only supports String values, you would have to use something like JSON.stringify
Perhaps commenting out clearInput(); before calling saveTodos(); will solve your problem. :)

Insert Textbox values in Array in Jquery / Javascript

I have a textbox in which user can add some values one by one. Now, when user click on add button I want to insert value that user enter into array one by one. I am doing this but I am getting the wrong result. The length of array is not increasing. Say If I entered 2 values then the length of array remain 1. I don't know what's the error. Below is my code:-
HTML
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />
<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>
Javascript
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
var newArray = [];
newArray.push('Ungrouped');
$( "input[name='input_add_prod_grp']" ).each(function() {
newArray.push($( this ).val());
});
console.log(newArray.length);
});
Now, If I enter more than 1 value then length of array remain 1. I don't know why.. Please help me out.. Thanks in advance..
Take you array outside:
var newArray = [];
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push(add_input_grp);
console.log(newArray.length);
});
JSFIDDLE:https://jsfiddle.net/c19u6fa2/1/
var newArray = [];
$(".btn_add_input_prod_grp").click(function() {
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push('Ungrouped');
$("input[name='input_add_prod_grp']").each(function() {
newArray.push($(this).val());
});
console.log(newArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />
<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>
Put the initialization outside of click event. Inside click event it is always reinitialize over and over.
You are making newArray empty when you click on button so the old values are deleting from that array to avoid this you have to move that to outside of your function along with default values you have only one input box you no need to write each you can get directly that value from your variable
var newArray = ['Ungrouped'];
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push(add_input_grp);
console.log(newArray.length);
});

Categories

Resources