Insert corresponding data into dynamically added rows using "this" - javascript

I am newbie to Angular js.'this' operator will be helpful, but no idea how to use it.
On Each First Column, user will input the data, and corresponding that data should be fetched. Now data is fetched from php to Angular js, but how to push the data from angular js to that text box using "this" operator.
For eg: If 'Y' is entered then, X and Z should be push to textbox
If 'Q' is entered then, P and R should be push to textbox.
HTML:
<tr>
<td><input type="text" ng-model="bot.Wo_Id" /></td>
<td><input type="text" ng-click="acc1()" ng-value="b_code" /</td>
<td><input type="text" ng-value="Pre_req" /></td>
<td><a href ng-click="remove_bottle(bottle)">Remove</a></td>
</tr>
<tr>
<td><a href ng-click="add_bottle()">Add</a></td>
</tr>
Angular Js:
$scope.acc1 = function () {
$http.get("machin.php", {
params: {
"W_id": this.bot.Wo_Id,
"MC": "Machine"
}
})
.success(function (response) {
var values = response.split("#");
$scope.b_code = ?
$scope.Pre_req = ? // what should be code here
});
};
machin.php
echo X."#".Z //for input Y
echo P."#".R //for input Q
I am unable to sort this problem.Please help me.Thanks in advance.

This should do the trick:
Don't use this, use $scope.
Change ng-value to ng-model
HTML
<tr>
<td><input type="text" ng-model="bot.Wo_Id" /></td>
<td><input type="text" ng-click="acc1()" ng-model="b_code" /</td>
<td><input type="text" ng-model="Pre_req" /></td>
<td><a href ng-click="remove_bottle(bottle)">Remove</a></td>
</tr>
<tr>
<td><a href ng-click="add_bottle()">Add</a></td>
</tr>
Angular:
$scope.acc1 = function () {
$http.get("machin.php", {
params: {
"W_id": $scope.bot.Wo_Id,
"MC": "Machine"
}
})
.success(function (response) {
var values = response.split("#");
$scope.b_code = values[0];
$scope.Pre_req = values[1];
});
};
Here's a plunker with example. I can't do the http request so I just resolve the promise.
https://plnkr.co/edit/f6EzxBlaFInJghNwsXaU?p=preview

Related

How to create a function for Onkeyup

I am trying to write a function to analyze the users input before calling Onkeyup. I am not sure where to write this if statement, or if I have the correct syntax. I wrote the if statement inside the asset-tag class. This is my code:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" + assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
};
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input
class="asset-tag" id='asset_tag_no${count}' type='text'
if (input.length >= 4){
console.log('not enough characters to call API endpoint');
}
else{
onkeyup = "getAssetInfo(this.value,${count})";
}
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
I want this error in the console log to only execute when a certain amount of characters are in the box instead of each time a character is inputted.

store input value which is in loop with javascript

I have a column input field in <td> which is in the loop due to this each Row has input field I got a javascript from which it storing local storage for input field but the issue is this javascript is working only for one input For Example :
I have five rows and due to loop input field generated for 5 rows automatically
What I am looking for is to store different values for each row..due to this script its not implementing for each row individually
Code
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
Javascript
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
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);
}
</script>
Image Showing
COde
<table class="table table-hover table-striped table-bordered" id="input-group">
<thead ><tr >
<th class="text-right"><?php echo "Contact No."; ?></th>
<th><?php echo "Followup 1 Date"; ?>
</th></tr></thead>
<tbody>
<?php
if (empty($enquiry_list)) {
?>
<?php
} else {
foreach ($enquiry_list as $key => $value) {
$current_date = date("d/m/Y");
$next_date = $value["next_date"];
if (empty($next_date)) { $next_date = $value["follow_up_date"];
}if ($next_date < $current_date) {
$class = "class='danger'";} else {
$class = ""; } ?>
<td class="mailbox-name"><?php echo $value['contact']; ?> </td>
<td class="mailbox-name" >
<div style="width:200px" style="height:200px" >
<input id="txt_<?= $row[id] ?>" onkeyup='saveValue(this);'
autocomplete="off" type="text" class="form-control" /></div></td>
</tr> </tr>
<?php }}?> </tbody> </table>
var inputGroup = document.getElementById('input-group');
var inputs = inputGroup.getElementsByTagName('input');
for(i=0;i<inputs.length;i++)
{
var id = inputs[i].getAttribute('id');
inputs[i].value = getSavedValue(id);
}
//Save the value function - save it to localStorage as (ID, VALUE)
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);
}
<table id="input-group">
<tr>
<th>Text 1</th>
<th><input type="text" id="txt_1" onkeyup='saveValue(this);'/> </th>
</tr>
<tr>
<th>Text 2</th>
<th><input type="text" id="txt_2" onkeyup='saveValue(this);'/> </th>
</tr>
<tr>
<th>Text 3</th>
<th><input type="text" id="txt_3" onkeyup='saveValue(this);'/> </th>
</tr>
<tr>
<th>Text 4</th>
<th><input type="text" id="txt_4" onkeyup='saveValue(this);'/> </th>
</tr>
<tr>
<th>Text 5</th>
<th><input type="text" id="txt_5" onkeyup='saveValue(this);'/> </th>
</tr>
</table>
First of all you need to pass the event listener to the function that you have implemented, so i've solved it adding the events on the js file.
So instead of this:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
You need to add the event on the js:
<input type="text" id="txt_1"/>
<input type="text" id="txt_2"/>
document.getElementById("txt_1").onkeyup = saveValue;
document.getElementById("txt_2").onkeyup = saveValue;
After this you need to access the id and the value from the event.target like this:
function saveValue(e) {
var id = e.target.id; // get the sender's id to save it .
var val = e.target.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
Look at this codesandbox and see if it helps you out
Html is not reliable. You can use pure javascript code for cleaner way. Here is the working sample. Slackblitz https://stackblitz.com/edit/js-xycijp
function saveValue({ target }, index) {
localStorage.setItem(target.id, target.value); // Every time user writing
// OR
localStorage.setItem("target.id"+index, target.value); // 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);
}
document.querySelectorAll(".textField").forEach((elm, index) => {
elm.addEventListener("input", (e) => saveValue(e, index), false);
});
// Can ignore
window.saveValue = saveValue;
window.getSavedValue = getSavedValue;
<input class='textField' type="text" id="txt_1" />
<input class='textField' type="text" id="txt_2" />

JavaScript not updating value from HTML

I have a small problem. This is my HTML code fragment:
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr th:each="boiler : ${boilers}">
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
<td>
<form>
<input type="text" th:class="boiler_model" th:id="boiler_model"
th:value="${boiler.value[0].model}" style="width:75px;"/>
<input class="form-control" type="number" id="quantity" style="width: 80px"/>
</form>
<td>
<button type="submit" class="btn btn-primary btn_submit" th:text="Add">Add</button>
</td>
</tr>
</tbody>
</table>
this is my jQuery:
$(document).ready(function () {
$('.btn_submit').on("click", function (e) {
e.preventDefault();
var quantity = $("#quantity").val();
// var boilerModel = $(".boiler_model").val();
var boilerModel = document.getElementById('boiler_model').value;
if (quantity === 0) {
alert("You must fill the quantity");
}
else if ($.trim(boilerModel) === "") {
alert("You must choose the model");
}
else {
var productIds = [];
$.ajax({
type: "POST",
url: "/order",
data: {quantity: quantity, model: boilerModel},
success: function (data) {
window.reload();
}
});
}
});
My problem is when I click the button it does read the quantity, but only reads the first model, even though it is printed in input correctly. I even removed the "hidden" type so I could see it for myself.
As you can see - the input is printed correctly, but when I debug this the controller always receives a quantity that is null if clicked on 2nd or 3rd model, but correct for the first one and model that is always the same. It always is "Super Hot Premium".
Could you please help me modify the table so it reads input separately from each row and then sends it to my controller?
Thank you very much.
There are several issues with your code :
you are looping through your boilers collection and generating a row for each loop. Each row contains two input fields with the same ids : quantity and boiler_model
in your click event handler, you are not looping through each row to submit data.
To fix this :
Follow this example to keep track of your loop status
Use the row index to generate unique ids for both your input fields
Store the size of your boilers collection in some hidden field to be able to send data from all rows
In your event handler, retrieve the size of your boilers collection and retrieve/send data for each row.
Here is a suggestion for your template (please note that I haven't tested it) :
<tr th:each="boiler, iterStatus : ${boilers}">
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
<td>
<form>
<input type="text" th:class="boiler_model" id="boiler_model_${iterStatus.index}"
th:value="${boiler.value[0].model}" style="width:75px;"/>
<input class="form-control" type="number" id="quantity_${iterStatus.index}" style="width: 80px"/>
</form>
<td>
<button type="submit" class="btn btn-primary btn_submit" th:text="Add">Add</button>
</td>
</tr>
<input type="hidden" id="boilersLength" th:value="${#lists.size(boilers)}"/>
And your event handler :
$(document).ready(function () {
$('.btn_submit').on("click", function (e) {
var quantity, boilerModel, boilersLength, i;
e.preventDefault();
// retrieving the length of the boilers collection
boilersLength = $("#boilersLength").val();
// looping and sending data for each row :
for (i=0;i<boilersLength;i++) {
// retrieving data from both inputs :
quantity = $("#quantity_" + i).val();
boilerModel = $("#boiler_model_" + i).val();
if (quantity === 0) {
alert("You must fill the quantity");
}
else if ($.trim(boilerModel) === "") {
alert("You must choose the model");
}
else {
var productIds = [];
$.ajax({
type: "POST",
url: "/order",
data: {quantity: quantity, model: boilerModel},
success: function (data) {
// I wouldn't reload the window here, or you may reload before all data is sent
// window.reload();
}
});
}
}
});
}
You need to send a unique-id to identify on which Row the button is clicked so that you could get those values on your controller on the basis of that 'unique-id'
For Example :--
<tr th:each="boiler : ${boilers}">
<td th:text="${boiler.uniqueID}"></td>
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
//Rest of your Code
<td>
<button type="submit" th:onclick="'javascript:addFunction(\'' + ${boiler.uniqueID} +'\');'" >Add</button>
</td>
</tr>

How to get the value from the before selected radio?

In my case I have lines of radioboxes, every radio has a value. This value must be calculated and the result must be placed in a DIV.
My Problem is, I can't find a way to subtract the value of the choosen radion before.
let me show you a sample markup:
<table>
<tr>
<td><input name="tools" value="20" type="radio"></td>
<td><input name="tools" value="300" type="radio"></td>
<td><input name="tools" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" value="5" type="radio"></td>
<td><input name="addons" value="10" type="radio"></td>
</tr>
</table>
<div id="result"></div>
JavaScript :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var price = $(this).val(),
showPrice = $('#result').text(),
endresult = parseFloat(showPrice) + parseFloat(price),
$('#result').text(endResult);
});
With checkboxes it works fine, but in case of radioboyes I don't have a click-event to identify this on I must subtract.
in the first line we see the radios name=tools. here I take at first this one with value 20.
after that the value 20 will be shown in the#result, fine. But when I take now another radio name=tools the new value will add to the 20. and that is my problem. I don't know how to find the before selected radio button to get this value and subtract it.
Try using this:
html code:
<table>
<tr>
<td><input name="tools" class="test1" value="20" type="radio"></td>
<td><input name="tools" class="test1" value="300" type="radio"></td>
<td><input name="tools" class="test1" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" class="test" value="5" type="radio"></td>
<td><input name="addons" class ="test" value="10" type="radio"></td>
</tr>
javascript:
<script>
var testPrice = 0;
var test1Price = 0;
var endprice = 0;
var price ='';
$('.test').click(function(){
price = $(this).val();
testPrice = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
$('.test1').click(function(){
var price = $(this).val();
test1Price = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
</script>
try it's demo on http://jsfiddle.net/rxrzX/
You don't need to substract. You can just find 2 value of 2 diff radio button : tools and addons. Then just add them and write in the div
You can get radio button value by :
$('input[name=radioName]:checked').val();
I think try this :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var toolsprice = $('input[name=tools]:checked').val(),
var addonsprice = $('input[name=addons]:checked').val(),
endresult = parseFloat(toolsPrice) + parseFloat(addonsprice),
$('#result').text(endResult);
});
You could use an object literal that tracks the value, using a closure:
radioClick.on('change', (function()
{
var valTracker = {},
resultDiv = $('#result');//easier on the DOM
return function(evt)
{
valTracker[this.name] = valTracker[this.name] || 0;//get old value
var endResult = parseFloat(resultDiv.text()) + parseFloat($(this).val()) - valTracker[this.name];//subtract old value, too
valTracker[this.name] = parseFloat($(this).val());//set current value
resultDiv.text(endResult);
}
}()));
The valTracker object literal tracks the current radio value (the name of the element is used as property). I've also kept a reference to the $('#result') div in the closure. That way, you don't have to query the DOM every time the callback function is called.
Try using the code below: JSFIDDLE
var radio_groups = []
$(":radio").each(function(){
if (radio_groups.indexOf(this.name) == -1){
radio_groups.push(this.name);
}
});
$('input:radio').change(function(evt){
var resultPrice = 0;
$.each(radio_groups, function(){
curPrice = $(':radio[name="' + this + '"]:checked').val();
if (!(curPrice)){
curPrice = 0;
}
resultPrice = parseInt(resultPrice) + parseInt(curPrice);
});
$('#result').text(resultPrice);
});
This will work, even if you add more radio button groups. If you want this functionality only for specific groups, define the names in the array radio_groups instead of getting them from the document.

jQuery foreach checkbox checked in tr > first td

i want to iterate through the table rows and get the id and name of each checkbox checked in each tr in the first td and save it in a new Object() called values ex: values.id, values.name
Thanks
<table>
<tr>
<td>
<input id="1" type="checkbox" name="name1" checked="checked">
</td>
<td>
Some input control 1
</td>
</tr>
<tr>
<td>
<input id="2" type="checkbox" name="name2">
</td>
<td>
Some input control 2
</td>
</tr>
</table>
Working example
aRecord is an array of objects with each object containing both the name and ID of each checked checkbox found in the table.
$(document).ready(function() {
var aRecord = [];
$('#your_table input:checkbox:checked').each(function() {
var oChkBox = {};
oChkBox.name = $(this).attr('name');
oChkBox.id = $(this).attr('id');
aRecord.push(oChkBox);
});
var i = aRecord.length;
while (i--) {
alert("Name: "+ aRecord[i].name + " ID: "+ aRecord[i].id);
}
});
http://jsfiddle.net/tracyfu/r6RMV/
var values = {};
$('tr input:checked').each(function(i) {
values[i] = [];
values[i].push($(this).attr('id'));
values[i].push($(this).attr('name'));
});
Will produce:
values = { [1, 'name1'] }
I'm leaving this solution as-is, since you specifically said you wanted to store the values in an object named values, but without knowing what you're going to do with the data, I would store the values in an array instead...

Categories

Resources