I was trying to update my quantity inside a table where list of rows are there. But i want to get the specific row with the quantity.
<td class="qty">
<div class="quantity-spinner">
<input type="number" name="product" class="prod_qty" value="{{$food->quantity}}" data-id="{{$food->id}}" />
</div>
</td>
// This is inside a loop so multiple row can be created.
javascript i have used :
$(":input").bind('keyup mouseup', function () {
var qty = $('.prod_qty').val()
var food_id = $('.prod_qty').attr("data-id")
});
But the problem is I got always first row food_id & qty not the specific one i wanted to update. How can i that specific row value?
Well take the value of the current element:
$(":input").bind('keyup mouseup', function () {
var qty = $(this).val()
var food_id = $(this).attr("data-id")
});
Related
I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?
I have a bit of HTML here:
<tr taskId="(#=obj.task.id#)" assigId="(#=obj.assig.id#)" class="assigEditRow" >
<td><select name="resourceId" class="get-resources formElements"></select></td>
<td><span class="resources-units"></span></td>
<td><span class="resources-quantity"></span></td>
<td><input type="text" placeholder="Required Q"></td>
<td align="center"><span class="teamworkIcon delAssig" style="cursor: pointer">d</span></td>
</tr>
And a bit of JS here:
'use strict';
function addResourceFunction(){
let ResourcesJSON = (json) => {
let Resources = json;
console.log(Resources);
let contactsLength = json.length;
let arrayCounter = -1;
let resID;
let resName;
let resUnit;
let resQuantity;
let Option = $('<option />');
let assignedID = $('tr.assigEditRow:last').attr("assigId");
while(arrayCounter <= contactsLength) {
arrayCounter++;
resID = Resources[arrayCounter].ID;
resName = Resources[arrayCounter].name;
resUnit = Resources[arrayCounter].unit;
resQuantity = Resources[arrayCounter].quantity;
$('.assigEditRow').last().find('select').append($('<option>', {
value: resName.toString(),
text: resName.toString(),
resourceID: resID.toString(),
resourceUnit: resUnit.toString(),
resourceQuantity: resQuantity.toString()
}));
}
}
$.getJSON("MY JSON URL IS HERE", function(json) {
ResourcesJSON(json);
});
};
So what's actually going on here: I get my data from the URL (JSON array), trigger the addResourceFunction() on click to create a new table row and to add a new select with options passed from the array. As you see from my HTML markup, the select input is placed in td.get-resources, and all that works good. I get my date set, I populate the select field and all works good. I can add as many rows/select dropdowns as I want.
Also, every option has a few custom attributes (you can see it in my JS code above), and I want to add the values of those attributes to the second and third column of the row (in HTML those are span.resources-units and span.resources-quantity). The thing is, I have no clue how to make it work 1:1, meaning that one select dropdown "alters" only units and quantity of its own row. Below is the code for that:
let idCounter = 1;
$(document).on('change', '.get-resources', function() {
$('.assigEditRow').last().find('.resources-units').attr('id', 'units-' + idCounter);
$('.assigEditRow').last().find('.resources-quantity').attr('id', 'quantity-' + idCounter);
this.resourceUn = $( ".get-resources option:selected" ).attr( "resourceUnit" );
this.resourceQuant = $( ".get-resources option:selected" ).attr( "resourceQuantity" );
$('#units-' + idCounter).append(this.resourceUn);
$('#quantity-' + idCounter).append(this.resourceQuant);
idCounter++;
});
What happens is that if I add one select input, and change options, the thing works. When I add another one and change its options, it gets attributes of the first one. Adding more - same thing. Whatever I change, it takes the attribute value of the first item added.
Try getting the id from the element instead of from the variable, since you always update the element with the id of the counter, instead of the element with the id of the row that was clicked.
Hmm, what does the counter do exactly? The more I look at it, the less I understand. What I do know is that you're not selecting the correct elements by using the idCounter to reference the correct row.
You want to do something like
$(document).on('change', '.get-resources', function() {
//var row = this;
this.find(/* Some path to the second column */).att(/* some att to change */);
this.find(/* Some path to the third column */).att(/* some att to change */);
});
where you always use the row as the root again, instead of finding a certain id, so you only update that row.
Native:
<table>
<tr>
<td>
<select>
<option data-text="resName1" data-resourceID="resID1" data-resourceUnit="resUnit1" data-resourceQuantity="resQuantity1">1</option>
<option data-text="resName2" data-resourceID="resID2" data-resourceUnit="resUnit2" data-resourceQuantity="resQuantity2">2</option>
<option data-text="resName3" data-resourceID="resID3" data-resourceUnit="resUnit3" data-resourceQuantity="resQuantity3">3</option>
</select>
</td>
<td>
<div class="column2"></div>
</td>
<td>
<div class="column3"></div>
</td>
</tr>
</table>
<script>
document.addEventListener('change', function ( event ) {
var select = event.target,
option = select.options[select.selectedIndex],
values = {
'text' : option.getAttribute('data-text'),
'resourceID' : option.getAttribute('data-resourceID'),
'resourceUnit' : option.getAttribute('data-resourceUnit'),
'resourceQuantity' : option.getAttribute('data-resourceQuantity')
},
row = select.parentNode.parentNode,/* depending on how deep the select is nested into the tr element */
column2 = row.querySelector('.column2'),
column3 = row.querySelector('.column3');
column2.textContent = 'some string with the values you want';
column3.textContent = 'some string with the other values you want';
});
</script>
Basically you start with the select that was changed, from there you get the option node that was clicked. Then you get the attributes you need from that option. Then you go up a few nodes to the row parent and find the two columns inside that row. Then you can set the content of these two columns.
I have setup a function to add rows to a table and sets values to input fields. My code to add rows is as follows:
$('#addItem').click(function() {
$('#itemData tbody:last-child').append('<tr><td align="left"><input id="ItemName[]" name="ItemName[]" type="hidden" value="'+$('#itemName').val()+'">'+$('#itemName').val()+'</td><td align="left"><input id="ItemNombre[]" name="ItemNombre[]" type="hidden" value="'+$('#itemNombre').val()+'">'+$('#itemNombre').val()+'</td><td><div id="editItem" onClick="editItem(this);">edit</div> / delete</td></tr>');
var row = $(this).parent().parent().children().index($(this).parent()) - 1;
$('#itemName').val('');
$('#itemNombre').val('');
})
I would like to be able to click on "edit" for a particular row and retrieve the values of ItemName[] and ItemNombre[]. Here is a JSFiddle example
First remove the onClick="editItem(this);" call.
Then, add a function like this :
$(document).on('click', '#editItem', function(){
// Get your datas
var $this = $(this),
ItemNombre = $this.parent().parent().find('#ItemNombre').val(),
...;
// Do your stuff
// ...
});
I have a function where I'm trying to add the total number of checkboxes ticked to a value that is already displayed in the textbox. The solution I have works but it doesn't update properly if I uncheck the boxes and click total again.
Is there a way I can fix this so that the textbox updates accordingly?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
You are updating the value of the input after every call to function sum().
Instead have the initial sum value.
Then every time use this value.
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}
Keep the original value of the textbox in a variable. Add an event listener to the checkboxes that count the number of checked boxes and adds that number to the original value, then updates the textbox.
Something like this:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
Here's a fiddle.
I have the following simple Jquery code that takes your input number * price to provide total.
I also need to have it include options with radio buttons, if checked +add to total.
Can anyone help me so that I can be able to add radio button options to make this take the input + radio buttons to get total price?
** It would also be nice if the price was Live as you typed/radio checked rather than clicking submit, but does not have to.
I have this so far:
http://jsfiddle.net/4bitlabs/tpkpd/15/
HTML:
<p class="list">How many "Linear Feet" of boards do you have?</p>
<input id="amount" />
<div class="addon">Add Paint $10.00<input id="amount" type="radio"value="10.00" class="radio"/></div>
<div class="price">$<label for="amount">0.00</label></div>
JQuery:
$(function () {
$('#amount').change(function () {
var $this = $(this);
$('label').text((parseFloat($this.val()) * 20.00).toFixed(2))
});
});
Thanks in advance.
There are some problems with your HTML. IDs should be unique.
I've done a fairly major rewrite, which I think will do what you are looking for. There are other ways to do it as well, but it should get you started
<input id="amount1" class="amount" />
I've made the IDs unique, and given the input boxes a class.
<input id="amount2" type="radio" value="10.00" class="radio addOn" data-for="amount1" />
The radio buttons also have a class of "addOn" and are attached to an label via the "data-for" tag.
$(function () {
$('.amount').change(function () {
changeAmount($(this));
});
$('.addOn').change(function () {
var $original = $('#' + $(this).data('for'));
changeAmount($original);
});
});
There are two ways to change the amount, one via changing the input box with a class of amount, one via changing the radio button with a class of addOn. The only difference is that the radio button function figures out what input box it is associated with.
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
// this handles the case when the val is not filled in.
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
$('label[for=' + id + ']').text(amount.toFixed(2))
}
jsFiddle
Use checked property.
And you better do not use duplicated IDs.
$(function () {
$('#amount').change(function () {
var $this = $(this);
var addPoint = $('input[type="radio"]').prop('checked') ? 10 : 0;
$('label').text((parseFloat($this.val()) * 20.00 + addPoint).toFixed(2))
});
});