Issue with Prototype in JS - javascript

For my class I needed to create a constructor, object, and prototype. Unfortunately I cannot get the prototype to work and was wondering if someone could help me understand how to make a prototype to correctly calculate the price of my pizza object. Before I had to add an object and prototype it was working fine, but to meet the assignment guidelines I was asked to go back and make a prototype, which is confusing me greatly. Any help would be appreciated.
//business logic
function Pizza(size, sauce, cheese, meat1, meat2, veggie1, veggie2) {
this.size = size;
this.sauce = sauce;
this.cheese = cheese;
this.meat1 = meat1;
this.meat2 = meat2;
this.veggie1 = veggie1;
this.veggie2 = veggie2;
}
Pizza.prototype.pizzaPrice = function() {
return pizzaPrice = inputtedSize + inputtedSauce + inputtedCheese + inputtedMeatOne + inputtedMeattwo + inputtedVeggieOne + inputtedVeggieTwo + 0;
}
//user interface logic
$(document).ready(function(){
$("form").submit(function(event) {
event.preventDefault();
$("form").fadeOut();
var inputtedSize = parseInt($("#size").val());
var inputtedSauce = parseInt($("#sauce").val());
var inputtedCheese = parseInt($("#cheese").val());
var inputtedMeatOne = parseInt($("#meat1").val());
var inputtedMeattwo = parseInt($("#meat2").val());
var inputtedVeggieOne = parseInt($("#veggie1").val());
var inputtedVeggieTwo = parseInt($("#veggie2").val());
var sizeChoice = $( "#size option:selected" ).text();
var sauceChoice = $( "#sauce option:selected" ).text();
var cheeseChoice = $( "#cheese option:selected" ).text();
var meatChoiceOne = $( "#meat1 option:selected" ).text();
var meatChoiceTwo = $( "#meat2 option:selected" ).text();
var veggieChoiceOne = $( "#veggie1 option:selected" ).text();
var veggieChoiceTwo = $( "#veggie2 option:selected" ).text();
var pizza = Pizza();
var newPizza = (inputtedSize + inputtedSauce + inputtedCheese + inputtedMeatOne + inputtedMeattwo + inputtedVeggieOne + inputtedVeggieTwo);
Pizza.pizzaPrice(newPizza);
$("#total").fadeIn();
$(".total").text(" " + "$" + newPizza);
$(".size").text(" " + sizeChoice);
$(".sauce").text(" " + sauceChoice);
$(".cheese").text(" " + cheeseChoice);
$(".meat1").text(" " + meatChoiceOne);
$(".meat2").text(" " + meatChoiceTwo);
$(".veggie1").text(" " + veggieChoiceOne);
$(".veggie2").text(" " + veggieChoiceTwo);
});
});

var pizza = Pizza(); //undefined
var pizza = new Pizza() //your obj
i am new, but try this.

First of all, you're instantiating your object incorrectly. You must prefix new object instances with the self explanatory new operator.
Secondly, you reference instance values with this. In an prototype function, you can access instance variables by prefixing the variable with this. Doing this.size = size in the constructor will yield the value you passed to the constructor anytime you call this.size. Therefore your functions should reference those values like so instead of the variable which you're setting the input val from.
Here's how your code should look:
function Pizza(size, sauce, cheese, meat1, meat2, veggie1, veggie2) {
this.size = size;
this.sauce = sauce;
this.cheese = cheese;
this.meat1 = meat1;
this.meat2 = meat2;
this.veggie1 = veggie1;
this.veggie2 = veggie2;
}
Pizza.prototype.price = function() {
return this.size +
this.sauce +
this.cheese +
this.meat1 +
this.meat2 +
this.veggie1 +
this.veggie2 + 0;
}
var pizza = new Pizza(1, 1, 2, 1, 2, 3, 1);
console.log(pizza) // Pizza instance
console.log(pizza.price()) // returns computed instance values
console.log(pizza.sauce) // access instance value
In your case, you would use the above example like so:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
$("form").fadeOut();
var inputtedSize = parseInt($("#size").val());
var inputtedSauce = parseInt($("#sauce").val());
var inputtedCheese = parseInt($("#cheese").val());
var inputtedMeatOne = parseInt($("#meat1").val());
var inputtedMeattwo = parseInt($("#meat2").val());
var inputtedVeggieOne = parseInt($("#veggie1").val());
var inputtedVeggieTwo = parseInt($("#veggie2").val());
var sizeChoice = $("#size option:selected").text();
var sauceChoice = $("#sauce option:selected").text();
var cheeseChoice = $("#cheese option:selected").text();
var meatChoiceOne = $("#meat1 option:selected").text();
var meatChoiceTwo = $("#meat2 option:selected").text();
var veggieChoiceOne = $("#veggie1 option:selected").text();
var veggieChoiceTwo = $("#veggie2 option:selected").text();
var pizza = new Pizza(inputtedSize, inputtedSauce, inputtedCheese, inputtedMeatOne, inputtedMeattwo, inputtedVeggieOne, inputtedVeggieTwo);
$("#total").fadeIn();
$(".total").text(" " + "$" + pizza.price());
$(".size").text(" " + pizza.size);
$(".sauce").text(" " + pizza.sauce);
$(".cheese").text(" " + pizza.cheese);
$(".meat1").text(" " + pizza.meat1);
$(".meat2").text(" " + pizza.meat2);
$(".veggie1").text(" " + pizza.veggie1);
$(".veggie2").text(" " + pizza.veggie1);
});
});

Related

jQuery: Adding objects to arrays in each loops not working

I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);

How to assign value to a specific attribute in Javascript

I'm implementing an extend form function, in which I need to increment certain attributes including ones like data-display="#display_student_1_gender".
There is no problem in finding the attribute but it fails (marked below) when I am trying to rename it. What gives?
The Javascript:
<script>
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for], [data-display]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
var theNames4 = newFields[i].attr('data-display'); //line 14 Error
if (theNames4)
newFields[i].attr('data-display') = theNames4 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
</script>
You are dealing with dom element(newFields[i]) references which does not hae method like attr()(I think you got in from some jQuery references - but since you have not tagged the question with jQuery, I'm assuming you are not using it).
You need to use getAttribute() and setAttribute() to get/set attribute values
var theNames4 = newFields[i].getAttribute('data-display');
newFields[i].setAttribute('data-display', theNames4 + counter)
or if you are using data api
var theNames4 = newFields[i].dataset.display;
newFields[i].dataset.display = theNames4 + counter

Access parent element by variable using jquery

var _div = $("<div id='ds-tree-expand'/>").appendTo( "#ds-subject-tree" );
var _cur_token = "susmita";
var _next_token = "sudipta";
for(var i=0; i<5; i++){
var _1st_level = $( "<p id='acc_trigger' class='active collapsed'>" + _cur_token + "</p>" ).appendTo(_div);
var _2nd_level = $( "<p id='2nd_trigger' class='active collapsed'>" + _next_token + "</p>" ).appendTo(_1st_level);
}
var _2nd_ch = _div.children().children();
Now I want to access the parent of each _2nd_ch element.
I have tried:
$(_2nd_ch[1]).parent();
This isn't working. How can I access the parent of each item of the _2nd_ch array?
See this might helpful to you. http://jsfiddle.net/z8a0234b/ You can access any node using _nth.
var _div = $("<div id='ds-tree-expand'/>").appendTo( "#ds-subject-tree" );
var _cur_token = "Parent";
var _next_token = "Child";
for(var i=0; i<5; i++){
var _1st_level = $( "<p id='acc_trigger' class='active collapsed'>" + _cur_token + " "+ i +"</p>" ).appendTo(_div);
var _2nd_level = $( "<p id='2nd_trigger' class='active collapsed'>" + _next_token + " "+ i +"</p>" ).appendTo(_1st_level);
}
var _nth = 2;/*2dn node, for Parent 1*/
var _nth_parent = $("#ds-tree-expand > #acc_trigger:nth-child("+_nth+")").html();
_nth_parent = _nth_parent.split("<p"); _nth_parent = _nth_parent[0]; /*filter to trace only words no tag*/
var _nth_child = $("#ds-tree-expand > #acc_trigger:nth-child("+_nth+") > p").html();
alert(_nth_parent +" "+ _nth_child);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="ds-subject-tree"></div>

shorthand javascript ? for making vars?

Is there a bether way to do this ?
i try serval things, but this one is the only that works for me
var naam = $("#resvNaam").val();
var aantal = $("#resvAantal").val();
var uur = $("#resvUur").val();
var datum = $("#resvDatum").val();
var telefoon = $("#resvTelefoon").val();
var opmerking = $("#resvOpmerking").val();
var alles = "?naam=" + naam + "&aantal=" + aantal + "&uur=" + uur + "&datum=" + datum + "&telefoon=" + telefoon + "&opmerking=" + opmerking;
You can put all the ids in an array, then use map:
var ids = [
'naam',
'aantal',
...
]
var ucfirst = function(x) {
return x[0].toUpperCase() + x.slice(1)
}
var alles = '?'+ ids
.map(function(id) {
var value = encodeURIComponent($('#resv'+ ucfirst(id)).val())
return id +'='+ value
})
.join('&')
I would suggest using the same id or name for the field and the query, so it is easier to manipulate, and write less code.
As suggested in the comments, if you use names it would be easier to serialize the form with jQuery using http://api.jquery.com/serialize/

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

Categories