Reputation: 3
The issue I'm having is fairly hard for me to explain, but I have replicated it in a jsFiddle http://jsfiddle.net/6ms4T/1/
What I am trying to achieve is by updating the 'Quantity' text box, I want to display the value elsewhere (the line below which I'll refer to as the 'Cost line').
Basically, updating the first input box (qty_item_1
) is updating all the (quant_
) IDs in the 'Cost line', rather than just the one related to that product.
function recalc(){
$("[id^=quant_]").text($("input[id^=qty_item_]").val());
etc...
Full code is here: http://jsfiddle.net/6ms4T/1/
Any help would be appreciated.
Upvotes: 0
Views: 144
Reputation: 2915
You can find the id of the element that is changing and then extract the digits part of it for use in the rest of your calculations. Here is the aspects that I changed and a working version.:
var uniqueOne = $(this).attr("id").match(/\d+/);
$("[id^=quant_][id$="+uniqueOne+"]").text($("input[id^=qty_item_][id$="+uniqueOne+"]").val());
While not the cleanest looking code, what it does is find the ids that start with quant_ and end with uniqueOne. You could probably condense these but it highlights combining two selectors (the starts with and ends with).
Looks like you have lots of great ideas to choose from.
Edit:
If your id's don't start with qty_item_, then you'll need to use a different selector. The lowest-hanging-fruit for this one would be the contains selector: id*=blah
.
Updated version with 'gross' ids to find: http://jsfiddle.net/6ms4T/22/
Edit:
The previous jsfiddle didn't handle updating the total as expected. This updated version should reduce confusion by identifying all the cases where DOM elements are sought by ID; however, there is a high probability that this should be refactored: http://jsfiddle.net/6ms4T/24/.
EDIT:
OP's tags had various numbers and letters generated into his IDs but the final digits were preceded by an underscore. The significant id was thereby found with the regex /\d+$/
. As other posters have shown, there is more than one way to solve this. I personally liked User gabitzish's.
Upvotes: 0
Reputation: 3045
change start of recalc() function as follows;
function recalc(e){
var idx = $(e.target).attr('id').split('_').pop();
$("[id^=quant_" + idx + "]").text($(e.target).val());
... }
Upvotes: 0
Reputation: 253358
You can make things relatively concise, and apply events to only the specific elements by identifying the numeric component of the id
, and then using that number as part of the selector:
var idNum = this.id.match(/\d+/);
$("#quant_" + idNum).text($("#qty_item_" + idNum).val());
References:
Upvotes: 0
Reputation: 9691
Add an attribute that holds an information about your input. I've added an attribute "rel" with value 1 for the first input, and 2 for the second, and then used this rel for building the right id's for the li elements.
Here is an updated working jsFiddle : http://jsfiddle.net/6ms4T/8/
Upvotes: 1