converting javascript function to jquery - javascript

I've been struggling to convert a JavaScript function...
Original code:
function calcTotal(){
//get value of select(tickets)
var ticketCost = 0;
if(document.moaflevent.moaflmember.value=="Yes") {
var ticketPrice = 35;
}else {
var ticketPrice = 40;
}
ticketCost = (document.moaflevent.tickets.options[document.moaflevent.tickets.selectedIndex].value)*ticketPrice;
document.moaflevent.displaytotal.value= formatCurrency(ticketCost);
document.moaflevent.total.value=ticketCost;
}
my jquery syntax:
function calcTotal() {
//get value of select(tickets)
//var ticketCost = 0;
var ticketCost = 0;
if ($('#moaflmember').val() == "Yes") {
var ticketPrice = 10;
} else {
$ticketPrice = 10;
}
$('#eachTicket').text($ticketPrice);
$ticketCost = $('#tickets').val() * $ticketPrice;
$('#displaytotal').val().toUSD($ticketCost);
$('#total').val().toUSD($ticketCost);
}
it's not working, the total is not updating when selecting membership or number of tickets...
jsfiddle says my js is good but I'm not sure what I'm doing wrong here...
http://jsfiddle.net/kv7L0c5d/5/

You are using an inconsistent mixture of $ticketPrice and ticketPrice. These are not the same thing.
You have not declared the $ticketCost variable.
toUSD is not a method on the string datatype, so you cannot call $('#displaytotal').val().toUSD($ticketCost);
The following works:
function calcTotal() {
var ticketPrice = 0,
ticketCost;
if ($('#moaflmember').val() == "Yes") {
ticketPrice = 10;
} else {
ticketPrice = 10;
}
$('#eachTicket').text(ticketPrice);
ticketCost = $('#tickets').val() * ticketPrice;
$('#displaytotal').val(toUSD(ticketCost));
$('#total').val(toUSD(ticketCost));
}
http://jsfiddle.net/kv7L0c5d/10/

Related

How do I create an if statement inside another if statement with javascript?

I am making a poker game with HTML CSS and Javascript. Right now, I am making the part of the program that actually deals the cards. I need to have an if statement inside another if statement. When it runs through, it generates a random number, then I have a list of if statements that see first if the card has been chosen, then I have another if statement inside of the first if statement to see if the card has been dealt. I don't know why it won't work. Can anyone help? Here is the code:
var yourchipsvar = 500;
var alchipsvar = 500;
var potvar = 0;
var whotodealto = 0;
yourchipsvar = Number(yourchipsvar);
alchips = Number(alchipsvar);
potvar = Number(potvar);
document.getElementById("yourchips").innerHTML = Number(yourchipsvar);
document.getElementById("alchips").innerHTML = Number(alchipsvar);
document.getElementById("pot").innerHTML = Number(potvar);
function bet() {
yourchipsvar = yourchipsvar - 5;
potvar = potvar + 5;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet15() {
yourchipsvar = yourchipsvar - 15;
potvar = potvar + 15;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet25() {
yourchipsvar = yourchipsvar - 25;
potvar = potvar + 25;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet50() {
yourchipsvar = yourchipsvar - 50;
potvar = potvar + 50;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
var aceofspades = 0;
var twoofspades = 0;
var threeofspades = 0;
var fourofspades = 0;
var fiveofspades = 0;
var cardinhand = 0;
function deal() {
if (whotodealto == 0) {
dealuser();
} else {
alert("dealtotheAI");
}
}
function dealuser() {
var cardinhand = Math.floor(Math.random() * 6);
if (cardinhand == 0) {
if (aceofspades == 0) {
alert("You got an ace of spades");
var aceofspades = 1;
}
}
if (cardinhand == 1) {
if (twoofspades == 0) {
alert("You got a two of spades");
var twoofspades = 1;
}
}
if (cardinhand == 2) {
if (threeofspades == 0) {
alert("You got a three of spades");
var threeofspades = 1;
}
}
if (cardinhand == 3) {
if (fourofspades == 0) {
alert("You got a four of spades");
var fourofspades = 1;
}
}
if (cardinhand == 4) {
if (fiveofspades == 0) {
alert("You got a five of spades");
var fiveofspades = 1;
}
}
}
You are creating two different local variables for each aceofspades, twoofspades, etc. This is because var means to create a local variable in the scope you are in. So the variables defined here:
var aceofspades = 0;
var twoofspades = 0;
var threeofspades = 0;
var fourofspades = 0;
var fiveofspades = 0;
var cardinhand = 0;
function deal() {
if(whotodealto==0){dealuser();} else{alert("dealtotheAI");}}
function dealuser() {
var cardinhand = Math.floor(Math.random()*6);
...
}
Are different from the ones you create here:
function dealuser() {
...
if(aceofspades==0){
alert("You got an ace of spades");
var aceofspades = 1;
}
In that case var aceofspades means you are creating a local variable in the dealuser() function. Simply set the value of your already created variable, this way you are not making a new one:
if(aceofspades==0) {
alert("You got an ace of spades");
aceofspades = 1;
}

How to make a simple typewriter with pure javascript?

I know I could do it with jQuery, but I want to use only javascript.
I am currently using this code (demo)
<body onload="typeEffect();">
<span id="typeArea"></span>
<script>
var textSpan = document.getElementById("typeArea");
var letterPrint = 0;
function effectOne()
{
textSpan.innerHTML = "H";
}
function effectTwo()
{
textSpan.innerHTML = "He";
}
function effectThree()
{
textSpan.innerHTML = "Hel";
}
function effectFour()
{
textSpan.innerHTML = "Hell";
}
function effectFive()
{
textSpan.innerHTML = "Hello";
}
</script>
</body>
But the result doesn't be like I wanted, it doesn't type each letter but it type a word simultaneously.
I have also tried this javascript code
var letterPrint = 0;
function playEffect()
{
if (letterPrint == 0)
{
textSpan.innerHTML = "H";
var letterPrint = 1;
}
else if (letterPrint == 1)
{
textSpan.innerHTML = "He";
var letterPrint = 2;
}
else if (letterPrint == 2)
{
textSpan.innerHTML = "Hel";
var letterPrint = 3;
}
else if (letterPrint == 3)
{
textSpan.innerHTML = "Hell";
var letterPrint = 4;
}
else if (letterPrint == 4)
{
textSpan.innerHTML = "Hello";
var letterPrint = 5;
}
else
{
textSpan.innerHTML = "Hello";
}
}
setInterval("playEffect()","1000");
But it gives me the same result.
How can I make typewriter effect with javascript? Or it is impossible?
Here you go (considering you have, for example, span or div with id "tr"):
var word = "Hello, world!";
var i = 0;
var timer = setInterval(function(){
document.getElementById("tr").innerHTML+=word[i];i++;if(i>word.length-1){clearInterval(timer)}
},100)
fiddle
You can also split the message into each characters and then use setTimeout with an increasing timeout in a Array.forEach callback.
function type(message, id) {
var output = document.getElementById(id), i = 0;
message.split("").forEach(function(letter){
setTimeout(function(){
output.innerHTML += letter;
}, i++ * 1000);
});
}
type("Hello Word", "output");
DEMO
Here's something to get you started. I've used recursion to save you having to manually type your big if/else and it shows you how to do the timeouts, too.
var message = "Hello World"
function printChar(i) {
var output = document.getElementById("output")
var char = message.charAt(i);
output.innerHTML = output.innerHTML + char;
if (i < message.length) {
window.setTimeout(function() {
i = i + 1;
printChar(i);
}, 1000)
}
}
printChar(0);
Demo here:
http://jsfiddle.net/4c6msk8L/
Short version, out of interest (see comments):
var m = "Hello World"
function p(i) {
document.getElementById("output").innerHTML += m.charAt(i);
if (i<m.length) {window.setTimeout(function() {p(++i);}, 100)}
}
p(0);
Pay attention to var, which creates a local variable (hiding a variable with the same name in the outer scope).
Consider using substring instead of copy&pasting the same code. Now you have the same error in 5 places to fix.

less than or equal to condition is not working in my script

<script type="text/javascript">
function ValidateAddOnModule(source, args) {
var gdv = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules');
var j = 0;
var k = 0;
for (var i = 1; i <= gdv.rows.length - 1; i++) {
var img = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_ImgLanUserError_' + j);
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
// alert(MinLANUser);
// alert(LANUser);
if (MinLANUser != " ")
{
if (MinLANUser <= LANUser) {
alert("true");
img.style.visibility = "hidden";
}
else {
alert("false");
img.style.visibility = "visible";
k = 1;
}
j++;
}
}
if (k = 1) {
return false;
} else
{
return true;
}
}
</script>
frist try to change the numbers you grab from thext fields with parseInt() function
element.innerText will give you the output in string format. You have to first convert that value to integer using parseInt. Then only you can operate arithmetic operators on them.
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
convert these to integer type.
var LANUser = parseInt(document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value);
var MinLANUser = parseInt(gdv.rows(i).cells(2).innerText);

img losing id when changing src

I am trying to build a webpage where you can oreder a ticket to a cinema movie.I have used an algorithm to change the cinema ticked price based on spot's id. The problem is that when I change the src of the image I get an undefined id. Why do I get that, and how to fix it?. Here is the code:
window.onload = main;
var initialPrice = 0;
var dayMultiplier = 1;
var price = 0;
function main()
{
addButtonLsn();
}
function addButtonLsn()
{
$("#setDate").click(addSeats);
}
function addSeats()
{
if($("#zi").val() === "--*--")
{
alert("Day select missing");
return;
}
if($("#movies").val() ==="--*--")
{
alert("Movie select missing");
return;
}
setInitialPrice();
setDayMutliplier();
$("#sala").empty();
$("#price").html("Pret : 0");
var myId = 1;
for(var i = 0; i < 20; i++)
{
for (var j = 0; j < 12; j++)
{
var s = document.createElement("img");
s.setAttribute("src", "liber.jpg");
s.setAttribute("id", myId);
myId ++;
s.addEventListener("click", changeSeat);
s.addEventListener("mouseover", getSeatTicket);
var d = document.getElementById("sala");
d.appendChild(s);
}
}
}
function getSeatTicket()
{
var spotPrice = initialPrice;
spotPrice = initialPrice * dayMultiplier;
var spotMultiplyer = 1;
var ct = 1;
if($(this).attr("id") < 130)
{
spotMultiplyer = 1;
ct = 3;
}
else if ($(this).attr("id") < 180)
{
spotMultiplyer = 1.1;
ct = 2;
}
else
{
spotMultiplyer = 1.2;
ct = 1;
}
spotPrice *= spotMultiplyer;
console.log($(this).attr("id"));//undefined
$(this).attr("title","Categorie: " + ct + " ,pret " + spotPrice);
return spotPrice;
}
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket();
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket();
$("#price").html("Price: " + price);
}
}
function setInitialPrice()
{
if($("#movies").val() === "The Gold Rush")
{
initialPrice = 10;
return;
}
if($("#movies").val() === "The Kid")
{
initialPrice = 11;
return;
}
if($("#movies").val() === "Modern Times")
{
initialPrice = 12;
return;
}
}
function setDayMutliplier()
{
if($("#zi").val() === "Luni-Joi")
{
dayMultiplier = 1;
return;
}
if($("#zi").val() === "Vineri")
{
dayMultiplier = 1.1;
return;
}
if($("#zi").val() === "Sambata")
{
dayMultiplier = 1.2;
return;
}
if($("#zi").val() === "Duminica")
{
dayMultiplier = 1.3;
return;
}
}
The function getSeatTicket is referring to this as the current element, which works fine when the function is used as a callback for the mouseover listener, but it will not work when you are calling it as you are in changeSeat.
Perhaps you should be using .call(this) to run the function using the same scope as changeSeat;
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
}
After code inspection, my guess is that when you try to access the element's id within the getSeatTicket() function, you are calling a function where $(this) is not actually refering to the DOM element to which the event is attached to.
To overcome this, my recommendation would be to pass the id to the getSeatTicket() function, and getting the reference to the element inside it. Something like (conceptual):
function getSeatTicket(id){
var element = $(id);
...
}
and call it like:
...
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket($(this).attr("id"));
...
Best.

iterating through texbox values using for loop in javascript

I have a little procedure to prevent server side action if all texboxes do not have values.
I want to assign a color to the texbox for in case a value was not added.
This is not working the way I expected.
var txtName = document.getElementById("MainContent_txtName").value;
var txtSurname = document.getElementById("MainContent_txtSurname").value;
var txtContact = document.getElementById("MainContent_txtContactNumber").value;
var txtEmail = document.getElementById("MainContent_txtEmail").value;
var txtMessage = document.getElementById("MainContent_txtMessage").value;
var fields = new Array(txtName, txtSurname, txtContact, txtEmail, txtMessage);
var tot = 0;
for (var i = 0; i < fields.length; i++) {
if (fields[i] == "") {
fields[i].style.backgroundcolor = '#FEF5CA';
tot++;
}
else {
fields[i].style.backgroundcolor = "white";
}
}
if (tot > 0) {
return false;
}
return true;
regards
The problem is you are creating an array of values, you need the elements themselves:
var txtName = document.getElementById("MainContent_txtName");
var txtSurname = document.getElementById("MainContent_txtSurname");
var txtContact = document.getElementById("MainContent_txtContactNumber");
var txtEmail = document.getElementById("MainContent_txtEmail");
var txtMessage = document.getElementById("MainContent_txtMessage");
var fields = [txtName, txtSurname, txtContact, txtEmail, txtMessage];
var tot = 0;
for (var i = 0; i < fields.length; i++) {
if (fields[i].value == "") {
fields[i].style.backgroundColor = '#FEF5CA';
tot++;
}
else {
fields[i].style.backgroundColor = "white";
}
}
if (tot > 0) {
return false;
}
return true;
You have to change backgroundcolor to backgroundColor and add .value to your if check.
try style.backgroundColor instead of style.backgroundcolor (note the capital "C") Javascript is case sensitive.

Categories