I have the following (very incomplete) code that I want to eventually be a shopping cart using jquery.
This is code for loading items remotely from a json file and parsing them into Html using jquery.
$(document).ready(function () {
"use strict";
// Download the content
var head = $("<h1>Aisan Market</h1>");
var dl = $("<dl>");
$("body")
.append(head)
.append(dl)
for (var i = 0; i <shop.length; i++) {
var item = shop[i];
var dt=$("<dt>").text(item.itemId)
var dt1 = $("<dt>").text(item.name)
var dd = $("<dd>").text(item.price)
var button = $("<button>buy</button>");
dl
.append(button)
.append(dt)
.append(dt1)
.append(dd);
}
Here I'd like to have on a button click to walk the dom tree to the correct item id,item name and price and append that to the cart.but it's not doing that.It's writing the id number repeating it and writing 0.
var cart = $("<div>cart<div>");
$("body").append(cart);
var total = 0;
$("button").on("click", function () {
var a = $(this);
var prev = a.next("dt").text();
var b = $(this);
var prev1 = b.next("dt").text();
var c = $(this);
var prev2 = c.next("dd").text();
total += prev2;
cart
.append(prev)
.append(prev1)
.append(total);
});
});
Where am I going wrong.
Thanks a lot.
Related
I am currently working on an excel like behaviour for some task.
All "tr"s are bound to the variable $test
var $test = $('tbody tr');
Now I use the jQuery .each function to run throuhg all trs and collect its relevant contents like this :
$test.each(function(index, element){
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {row_id: $row_id,....};
});
Since the pushObject gets greated and stuffed with content each time the each function gets executed I need a way to "push" this object into a parent object which I can later use with AJAX.
The behaviour I'd wish for would be like this:
var parentObj = {};
$.each(function(){
// in each run the newly created object gets nested into the parentObject which results in the parent object having X-childObjects
});
So after, lets say 5 each runs, the parentObj should contain : [0],[1],...,[4] objects.
Could anyone guide me throuhg that process ?
Try this solution by storing pushObj inside array variable like so :
// add here
var parentObj = [];
$test.each(function (index, element) {
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {
row_id: $row_id,
....
};
// add here
parentObj.push(pushObj);
});
// later on here access parentObj variable
I have follow two functions here which working great!
As you can see these two functions are almost the same, except the code which comes below the last comment in each function.
How do I make that more simple. Could I make a code-"holder" - Where I only include a part of a code from another file? So I don't have too have the "same" code in each functions?
Should I use some kind of classes or? - I have never worked with classes.
/// Function (add_new_field)
$(document).on("click", '.add_new_field', function(e) {
e.preventDefault();
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
/*console.log(
' -> WrapID:'+flex6.attr('id')+
' -> accordionContentID:'+flex5.attr('id')+
' -> acContentBoxID:'+flex4.attr('id')+
' -> acChildBoxID:'+flex3.attr('id')+
' -> acBabyBoxID:'+flex2.attr('id')+
' -> SecondID:'+flex1.attr('id')+
' -> FirstID:'+flex0.attr('id')
);*/
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
// there is a lot more code here...
)};
/// Function (del_field)
$(document).on("click", '.del_field', function(e) {
e.preventDefault();
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
// there is a lot more code her
)};
How could I make something like this.
/// I want to include this code into the functions. So I don't have to write it twice.
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
Thank you.
If you want to do something like classes in javascript, your best bet is to use prototyping, since javascript doesn't have classes.
In this case, I'm not sure what your code does, so prototyping might not be the best answer. Your other option is to encapsulate all of your variable definitions in another function, and call that function in both of your click functions. It would return an object with attributes, rather that a bunch of vars.
var myVarFn = function(){
var returnObject = {};
returnObject.flex0 = $(this);
returnObject.flex1 = $(this).parent().closest('div');
...
returnObject.wrapID = flex6.attr('id'); // wrapID
...
return returnOBject
}
And to use it in click, with this defined the same as in the scope of the click function:
$(document).on("click", '.del_field', function(e) {
var dataObject = myVarFn.call(this);
//Other code
};
And in the other click event,
$(document).on("click", '.add_new_field', function(e) {
var dataObject = myVarFn.call(this);
//Other code
};
You will have to modify your other code to use dataObject.flex0 instead of flex0 and so on.
Create a global object
var allId = new Object();
And a function that can be called whenever needed..
function getAllIDs(el) {
var id = ["wrapID", "accordionContentID", "acContentBoxID", "acChildBoxID", "acBabyBoxID", "SecondID", "FirstID"];
var flex;
for (var i = 0; i <= 6; i++) {
if (i == 0) {
flex = $(el).parent().closest('div');
} else {
flex = $(flex).parent().closest('div');
}
allId.id[i] = $(flex).parent().closest('div').attr('id');
}
}
Further, on jQuery event you can call getAllIDs function
$(document).on("click", '.add_new_field', function (e) {
e.preventDefault();
getAllIDs(this);
});
More details about javascript objects
I am working on a table that I need to be able to move rows up and down.
The problem is that I cannot re-insert the row before the previous or next row, because my application relies on the names of the input fields to stay in the same order.
My solution is to swap the values of the input fields, which works, but my code is very ugly and repetitive.
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
var rowdata1 = row.find('.rowdata1').val();
var rowdata2 = row.find('.rowdata2').val();
var rowdata3 = row.find('.rowdata3').val();
var rowdata4 = row.find('.rowdata4').val();
var rowdata5 = row.find('.rowdata5').val();
if ($(this).is(".up")) {
var tmp1 = row.prev().find('.rowdata1').val();
var tmp2 = row.prev().find('.rowdata2').val();
var tmp3 = row.prev().find('.rowdata3').val();
var tmp4 = row.prev().find('.rowdata4').val();
var tmp5 = row.prev().find('.rowdata5').val();
row.prev().find('.rowdata1').val(rowdata1);
row.prev().find('.rowdata2').val(rowdata2);
row.prev().find('.rowdata3').val(rowdata3);
row.prev().find('.rowdata4').val(rowdata4);
row.prev().find('.rowdata5').val(rowdata5);
row.find('.rowdata1').val(tmp1);
row.find('.rowdata2').val(tmp2);
row.find('.rowdata3').val(tmp3);
row.find('.rowdata4').val(tmp4);
row.find('.rowdata5').val(tmp5);
//row.insertBefore(row.prev());
} else {
var tmp1 = row.next().find('.rowdata1').val();
var tmp2 = row.next().find('.rowdata2').val();
var tmp3 = row.next().find('.rowdata3').val();
var tmp4 = row.next().find('.rowdata4').val();
var tmp5 = row.next().find('.rowdata5').val();
row.next().find('.rowdata1').val(rowdata1);
row.next().find('.rowdata2').val(rowdata2);
row.next().find('.rowdata3').val(rowdata3);
row.next().find('.rowdata4').val(rowdata4);
row.next().find('.rowdata5').val(rowdata5);
row.find('.rowdata1').val(tmp1);
row.find('.rowdata2').val(tmp2);
row.find('.rowdata3').val(tmp3);
row.find('.rowdata4').val(tmp4);
row.find('.rowdata5').val(tmp5);
//row.insertAfter(row.next());
}
});
});
I created a fiddle: http://jsfiddle.net/29T7V/
I would really appreciate any suggestions on how to simplify my code.
Any ideas on how to update my code to handle x amount of inputs in the rows would be absolutly awesome! TIA!
Something like this maybe
$(document).ready(function () {
$(".up, .down").on('click', function () {
var row = $(this).closest('tr').first(),
way = $(this).hasClass('up') ? 'prev' : 'next';
for (var i=1; i<6; i++) {
var sel = '.rowdata'+i,
tmp1 = row.find(sel).val(),
tmp2 = row[way]().find(sel).val();
row.find(sel).val(tmp2);
row[way]().find(sel).val(tmp1);
}
});
});
FIDDLE
Something wich would work with any number of columns:
$(document).ready(function () {
$(".up, .down").click(function () {
var $row = $(this).closest("tr"),
$swap = $row[$(this).is('.up') ? 'prev' : 'next']();
if (!$swap) return;
$row.find('td').each(function() {
var $input = $(this).find('input, select'),
$swapInput, $swapVal;
if ($input.length) {
$swapInput = $swap.children('td:eq(' + this.cellIndex + ')').find('input, select');
$swapVal = $swapInput.val();
$swapInput.val($input.val());
$input.val($swapVal);
}
});
});
});
Demo: http://jsfiddle.net/29T7V/
I have the following working code on greasemonkey:
var qtt = 100;
var filler1 = document.getElementById("s1_0");
var filler2 = document.getElementById("s2_0");
var filler3 = document.getElementById("s3_0");
var filler4 = document.getElementById("s4_0");
var filler5 = document.getElementById("s5_0");
var filler6 = document.getElementById("s6_0");
var filler7 = document.getElementById("s7_0");
filler1.value = qtt;
filler2.value = qtt;
filler3.value = qtt;
filler4.value = qtt;
filler5.value = qtt;
filler6.value = qtt;
filler7.value = qtt;
Where the "sN_0" are the names of inputs, the code works, but I was wondering if there is a better way to do the same, to loop through all the id names or something.
here is a simple loop doing that your code does
var qtt=100;
for (var i =1;i<8;i++){
document.getElementById("s"+i+"_0").value=qtt
}
If you can use jQuery, try the following.
var qtt = 100;
$('[id]').each(function() {
if(/^s\d_0$/.test(this.id)) {
this.value = qtt;
}
});
Demo
I have the following code:
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>
I am basically trying to search the textarea for words. I have to convert the value of the textarea to HTML, then I want to search the HTML for words... but its not working...
any ideas?
var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
should be
var matches = $(this).val().match(/\b/g);
The value of the textarea is aalready a string. The html method doesn't work the way you think it does. It should be a simple matter of removing the bits where you are attempting to use html.
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var text = $(this).val();
var matches = text.match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>