shorthand javascript ? for making vars? - javascript

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/

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);

Issue with Prototype in JS

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);
});
});

JavaScript : Split string using function and returning it

I don't know what I'm doing wrong here. Tried several thinks but the function doesn't work/return properly (The html code is okay)
var divResult = document.getElementById("divResult");
var naam;
function splitsen(naam){
var res = naam.split(" ");
document.write(res[0]);
var voornaam = res[0];
var achternaam = res[1];
var tnaam = [voornaam, achternaam];
return tnaam;
}
naam = parseInt(prompt("Geef je voornaam en achternaam in gescheiden met een spatie"));
var voornaam = splitsen(naam)[0];
var achternaam = splitsen(naam)[1];
divResult.innerHTML = "oefening 8";
divResult.innerHTML += "Voornaam: " + voornaam;
divResult.innerHTML += "Achternaam" + achternaam;
divResult.innerHTML += "Email: " + voornaam + "." + achternaam + "#student.arteveldehs.be";
parseInt('My Name'); returns NaN.
Remove the parseInt(), and just keep it as:
var naam = prompt('Input your name seperated by a space.');
I could spot 2 problems in your code:
1-The parameter name to your function is the same name as that of a global variable. It is probable that any references to 'naam' in your function use the global variable instead of what you pass. Regardless, don't do that.
2-parseInt will take a string and extract an integer out of it and returns a number. number types doesn't have the split() method and you probably wanted a string containing the name.

generate varname in jquery

In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data

Add random class to an Appended div ? (jquery)

This is all of my code for the object I'm working with, but I'm thinking it's only the "create building in screen" part you really need to help me with.
My goal is to have it where instead of saying class="House houseRed", it says something like class="House +'randomClass'" etc, and that variable holds my other class names(i have 5 total).
It's for a mini-game I'm working on, and I need the buildings that spawn to have different looks, based on their class names.
//CREATE BUILDING IN MEMOMORY
function CreateHouseInMemory() {
//GET VALUES
var sAddress = $("#HouseAddress").val();
var sUniqueId = getUniqueId();
var iMaxResidents = $('input[name=housemaxresidents]').val();
var oHouse = {
sType: "House",
sAddress: sAddress,
sId: sUniqueId,
iMaxResidents: iMaxResidents,
Residents: aResidents = [],
babyInHouse: false
};
oCity.aBuildings.push(oHouse);
console.dir(oCity.aBuildings);
return oHouse;
}
//CREATE BUILDING IN SCREEN
function CreateHouseInScreen(oHouse)
{
$("#City").append('<div id="' + oHouse.sId + '" class="House houseRed" title="' + oHouse.sAddress + '"></div>');
$(".House").draggable();
$(".House").droppable();
}
;
//SPAWN BUILDING
$("#BtnCreateHouse").click(function() {
var oHouse = CreateHouseInMemory();
CreateHouseInScreen(oHouse);
});
Something like this
var classesnames = ['toto', 'titi', 'tata', 'tutu'],
classrandom = classesnames[Math.floor(Math.random() * classesnames.length)];
$("#City").append('<div id="' + oHouse.sId + '" class="House '+ classrandom +'" title="' + oHouse.sAddress + '"></div>');
Create an array of the target class names
var array = ['one', 'two','three','four', 'five'];
//then
var random = array[Math.floor(Math.random() * array.length)]
You can add a class randomly in a way like this:
function CreateHouseInScreen(oHouse)
{
var classes = ['houseRed', 'houseBlue', 'houseGreen'];
var randomIndex = Math.floor(Math.random() * classes.length);
var div = $('<div id="' + oHouse.sId + '" class="House" title="' + oHouse.sAddress + '"></div>');
div.addClass(classes[randomIndex]);
$("#City").append(div);
$(".House").draggable();
$(".House").droppable();
}
You could use something like
i = parseInt(Math.random() * 4)
to either generate an array index for an array of classes, e.g
classArray = ['class1', 'class2', 'class3', 'class4', 'class5']
obj.className = classArray[i]
or convert the integer to a string and append it to a constant string, e.g
obj.className = "myClass" + i.toString().

Categories