0

I have a form where user can enter details and choose an item by selecting checkbox.

On clicking of add button checked item values and user input values stored in array and i am passing these values in url.

User can add multiple items with different name and email. Suppose i have three items so user can choose item1 and fill name1 and email1 and click on add button and similarly if he select item1 and item2 and add name2 and email2, he can add these value.

On each click i want to check item id if its already present in array i don't want to add it, just increase quantity of that item which is already there in array and update array with new quantity

var allVals = []; //array where i am storing selected checkbox value
jQuery("#btnadd").click(function(event) { //on click of this button i am getting all values to construct url and pass this value to multi div from where i will validate my url 
    var qty;
    jQuery(".selectitem:checked").each(function() {
            qty = jQuery(this).next().find('input[name="quantity"]').val()); //getting quantity of selected checkbox its a input field
        if (jQuery.inArray(jQuery(this).val(), allVals) == -1) {
            allVals.push(jQuery(this).val() + ',' + qty); //item id not present in array so adding item id,qty in array
        } else {
            qty = qty + 1;
            //here i would like to increase quantity of those items only which already present in array something like this.qty and update my allVal array with this new quantity
        }
    });
var rslt = allVals.join(';'); jQuery('#multi').val(rslt); //updating multi div value with allVals from here i will make redirect. Just want to pass correct values in that field
});
Uidev123
  • 73
  • 3
  • 13

2 Answers2

1

Problem: Right now you are inserting both the item Name and the quantity into a array like [item1,1,item2,1,...] So technically you have no control on what value your item1 is associated with. Even if you write a logic to take the next index of the item name its not efficient.

Solution: I suggest you to use Object rather than array. Because with object you can access with property Name and assign a value to it. Its more strongly coupled. See the example below

var allVals = {}; // make it a object.

With this structure you can replace the entire if else block with this code.

var key = jQuery(this).val();
allVals[key] =  (allVals[key] || 0 ) + parseInt(qty,10);

Explaining the above syntax.

  • allVals[key] - Here you are adding a new property / accessing exisitng property by name item1, item2 etc...

  • (allVals[key] || 0 ) - if the property already exists use its value. Else use 0 as it will be undefined.

  • parseInt(qty,10); - Since you are doing a Math operation its always recommended to convert your data into numeric types and then perform the math. Here if you don't use parseintyour qty will be string and you will get invalid results.

With the above syntax given your final syntax should be like..

var allVals = {}; 
jQuery("#btnadd").click(function(event) { 
    var qty;
    jQuery(".selectitem:checked").each(function() {
            qty = jQuery(this).next().find('input[name="quantity"]').val(); 
            var key = jQuery(this).val();
            allVals[key] =  (allVals[key] || 0 ) + parseInt(qty,10);
    });
//var rslt = allVals.join(';'); jQuery('#multi').val(rslt); 
// since your data structure has changed I am not sure if you need this.
});

The final data of allVals will be like..

{
 item1 : 2,
 item2 : 3,
 item3 : 1,
 item4 : 1 
}
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • Thanks for the reply....how to pass this value to #multi div....using the same line which you commented? – Uidev123 Dec 27 '16 at 13:05
  • @Uidev123 you want to display it in the div? or is it a text box? what is the final goal of this data? are you passing it to your server back? – Rajshekar Reddy Dec 27 '16 at 13:07
  • its hidden input box where i have to pass the data and based on this need to create a url – Uidev123 Dec 27 '16 at 13:09
  • @Uidev123 to pass the data to server.. the existing `allVals ` is the right format.. I am not sure about the part of creating a URL..but you can anyways loop the keys of the object and format the data in your required way.. what is the final format you expect and reason for it? – Rajshekar Reddy Dec 27 '16 at 13:12
  • allVals.push(jQuery(this).val()+','+qty+','+'custcol_name_of_attendees|'+nameatt); this is the format i need where nameatt is user name. something like this i need to pass to #multi – Uidev123 Dec 27 '16 at 13:15
  • @Uidev123 can you add final result than the code... Also whats the reason.. how are you planning to use that data later – Rajshekar Reddy Dec 27 '16 at 13:19
  • if i want to get quantity value in allVals...how to get that through loop? – Uidev123 Dec 27 '16 at 13:21
  • this is a hidden form field and on clicking of add cart button all the values will reflect in cart through url parameters – Uidev123 Dec 27 '16 at 13:22
  • @Uidev123 if adding them in URL is your goal then you can use `$.param( allVals )` .. check this page http://api.jquery.com/jquery.param/ – Rajshekar Reddy Dec 27 '16 at 13:24
  • No i want to pass these values in above mentioned format to #multi input field just only this – Uidev123 Dec 27 '16 at 13:40
  • @Uidev123 you dint mention a format.. you showed me a code.. can you show me the final output.. – Rajshekar Reddy Dec 27 '16 at 13:41
  • Format:( itemid,qtyvalue,custcol_name_of‌​_attendees|username)...where custcol_name_of‌​_attendees will be hard coded rest of the values need to get from object – Uidev123 Dec 27 '16 at 13:44
  • @Uidev123 this might help.. http://stackoverflow.com/a/36288430/2592042 let me know if you need further help – Rajshekar Reddy Dec 27 '16 at 13:49
0

Loop in array to find key and update qty as value.

    var qty;
     jQuery(".selectitem:checked")
       .each(function() {
           qty = jQuery(this)
             .next()
             .find('input[name="quantity"]')
             .val()); //getting quantity of selected checkbox its a input field
         if (jQuery.inArray(jQuery(this)
             .val(), allVals) == -1) {
           allVals.push(jQuery(this)
             .val() + ',' + qty); //item id not present in array so adding item id,qty in array
         } else {
           qty = qty + 1;

           for (var i = 0; i < allVals.length; i++) {
             if (allVals[i].Key == jQuery(this)
               .val()) {
               allVals[i].Value = qty;
             }
           }
         });
4b0
  • 21,981
  • 30
  • 95
  • 142