I have this code from #Snowmonkey
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
At the moment the code add new rows when the add row button is clicked. I want to add a similar function to the button 'remove row'. If it were clicked I want the last row to be removed, without affecting the content in the other textboxes. I have tried this, but it did not work:
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").remove(createNewRow());
})
How can I do this?
Thanks.
You could index the last element and remove it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container div").eq($(".container div").length - 1).remove();
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
Related
let currencySymbol = '$';
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let amount = document.querySelector('.received').value;
amount *= 1;
// Set cashReturn to return value of pay()
let cashReturn = pay(amount);
let paymentSummary = document.querySelector('.pay-summary');
let div = document.createElement('div');
// If total cash received is greater than cart total thank customer
// Else request additional funds
if (cashReturn >= 0) {
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Cash Returned: ${currencySymbol}${cashReturn}</p>
<p>Thank you!</p>
`;
} else {
// reset cash field for next entry
document.querySelector('.received').value = '';
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Remaining Balance: ${cashReturn}$</p>
<p>Please pay additional amount.</p>
<hr/>
`;
}
paymentSummary.append(div);
});
let totalPaid = 0;
function pay(totalPaid) {
let cartSum = 50; //using a dummy value for snippet
return totalPaid - cartSum;
}
.checkout-container {
max-width: 34em;
padding: 2em;
background: #efefef;
}
<div class="checkout-container">
<h2>Checkout</h2>
<div class="checkout">
<div class="cart-total"></div>
<form>
<label>Enter Cash Received:</label>
<input class="received" type="text">
<button class="pay">Submit</button>
</form>
<h3>Receipt</h3>
<div class="pay-summary"></div>
</div>
</div>
I'm implementing a simple cash register where user enters how much they paid into an input field, and it will subtract it from the total cost of the items. If the number returned is positive, it shows that the customer wil be given back the remaining change. If it's a negative value, the customer needs to add more money into the input field, which should be summed with their previous input.
Right now, the previous value is not being added to the new value:
After I input the remaining $15, there should be 0 remaining balance.
If you mean to type an amount of cash received more than once, you need to keep track of the amount of money received so far.
There are multiple ways to achieve that, here I opted for keeping track of it inside the value of an added input element.
In my demo the function cartTotal() always returns 78.45 as the amount to pay, and to reset the amount of money received so far, you just need to click the reset button so that the corresponding input value will be set back to zero.
function pay(totalPaid){
let cartSum = cartTotal();
return totalPaid - cartSum;
}
//Arbitrary number
function cartTotal(){
return 78.45;
}
function resetGame(){
document.getElementById('sofar').value = 0;
document.getElementById('received').value = 0;
document.getElementById('cashreturn').value = 0;
}
document.querySelector('.pay')
.addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
const amount = parseFloat( document.getElementById('received').value );
//**Here updates the amount received so far
const receivedSoFar = parseFloat( document.getElementById('sofar').value );
document.getElementById('sofar').value = receivedSoFar + amount;
// Set cashReturn to return value of pay()
const cashReturn = pay(amount + receivedSoFar);
document.getElementById('cashreturn').value = cashReturn.toFixed(2);
});
body{
font-family: sans-serif;
}
input, button{
padding: .2rem;
width: 5rem;
font-size: 15px;
}
input[disabled]{
outline: none;
border: none;
font-size: 20px;
}
button{
cursor: pointer;
}
<label>Enter cash:</label>
<input type="text" id="received">
<button class="pay">PAY</button>
<hr>
<label>Received so far:</label>
<input type="text" id="sofar" readonly disabled value="0">
<br>
<label>Cash return:</label>
<input type="text" id="cashreturn" readonly disabled value="0">
<br>
<button onclick="resetGame();">RESET</button>
Your amount variable only represents the last input. Any previous submitted amounts are lost. To fix this, define amount as a global variable, and add to that what the user has entered.
So change this part:
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let amount = document.querySelector('.received').value;
amount *= 1;
to:
let amount = 0; // <--- define here so to accumulate paid amounts
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let paid = document.querySelector('.received').value;
amount += +paid; // <--- accumulate
Your adapted snippet:
let currencySymbol = '$';
let amount = 0; // <--- define here so to accumulate paid amounts
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let paid = document.querySelector('.received').value;
amount += +paid; // <--- accumulate
// Set cashReturn to return value of pay()
let cashReturn = pay(amount);
let paymentSummary = document.querySelector('.pay-summary');
let div = document.createElement('div');
// If total cash received is greater than cart total thank customer
// Else request additional funds
if (cashReturn >= 0) {
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Cash Returned: ${currencySymbol}${cashReturn}</p>
<p>Thank you!</p>
`;
} else {
// reset cash field for next entry
document.querySelector('.received').value = '';
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Remaining Balance: ${cashReturn}$</p>
<p>Please pay additional amount.</p>
<hr/>
`;
}
paymentSummary.append(div);
});
let totalPaid = 0;
function pay(totalPaid) {
let cartSum = 50; //using a dummy value for snippet
return totalPaid - cartSum;
}
.checkout-container {
max-width: 34em;
padding: 2em;
background: #efefef;
}
<div class="checkout-container">
<h2>Checkout</h2>
<div class="checkout">
<div class="cart-total"></div>
<form>
<label>Enter Cash Received:</label>
<input class="received" type="text">
<button class="pay">Submit</button>
</form>
<h3>Receipt</h3>
<div class="pay-summary"></div>
</div>
</div>
Goal: Show a label, and input value from a different div and display it in a different section
I have a div that dynamically generates a set of input fields, and I am trying to then display that input fields value and their corresponding labels in a different section.
For example:
Step 1 - User enters in the number 5 into an input field.
Step 2 - There are 5 input fields created (based on value entered from step 1). Those input fields are labeled #1, #2, #3, etc... all the way to #5 or whatever number the user entered in Step 1.
Step 3 - User is presented with a new HTML section that lists off the labels (#1, #2, #3, etc.) and next to the labels is the value the user entered for those corresponding input fields.
Here is the code created for Step 2:
<label>#' + count + '</label>
<input type="number" name="length_field" value="" class="form-control length_field" />
Then, I need some javascript/jquery to take the labels and their corresponding input values and display then something like this:
<p>[LABEL #1] <span>[LABEL #1 INPUT VALUE]</span></p>
<p>[LABEL #2] <span>[LABEL #2 INPUT VALUE]</span></p>
<p>[LABEL #3] <span>[LABEL #3 INPUT VALUE]</span></p>
Etc...
For step 2 you need to check the value of your length_field input and create that many inputs by JavaScript. Set some helper ID and CLASS attributes so you can get values later.
For step 3 use that attributes to get input field values and set them as result div's html.
$(document).on('change', '#length_field', function() {
var inputsCount = parseInt($(this).val());
$('#inputsWrapper').html('');
$('#result').html('');
for (var i = 1; i <= inputsCount; i++) {
// Create custom input with label
var tempInput = document.createElement('input');
tempInput.setAttribute('name', i);
tempInput.setAttribute('id', i);
tempInput.setAttribute('class', 'customInputs');
var tempInputLabel = document.createElement('label');
tempInputLabel.setAttribute("for", i);
tempInputLabel.innerHTML = 'Input #' + i + ": ";
$('#inputsWrapper').append(tempInputLabel);
$('#inputsWrapper').append(tempInput);
// Create corresponding value presenter in result div
var resultRow = document.createElement('p');
resultRow.setAttribute('id', 'result-' + i);
resultRow.innerHTML = 'Label #' + i + ':';
$('#result').append(resultRow);
}
});
$(document).on('keyup', '.customInputs', function() {
var id = $(this).attr('id');
var inputValue = $(this).val();
$('#result-' + id).html('Label #' + id + ': <span> ' + inputValue + '</span>');
});
#inputsWrapper input {
display: block;
margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="length_field">Enter the number of inputs you want:</label>
<input type="number" name="length_field" id="length_field" />
<br/>
<div id="inputsWrapper">
</div>
<hr>
<div id="result">
</div>
This is really quick'n'dirty but it works.
I'm using a for-loop in both steps, in the first step the for-loop is generating the input fields and outputting them after.
In the second step I'm saving the html of the resulting paragraphs in a variable, because I can't override the document, because my wanted values are in the input fields.
The on keypress listener is optional and ensures that you don't have to press the Submit button with your mouse ;)
If I could help you i would appreciate if you could mark this answer as accepted.
let number = 0;
$(document).on("click", "#step1", function() {
number = $("input").val();
if (number > 0) {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<label for='input_" + i + "'>#" + i + "</label>: <input type='text' id='input_" + i + "'><br>";
}
html += "<button id='step2'>Submit</button>"
$("body").html(html);
}
})
$(document).on("click", "#step2", function() {
let html = "", i;
for (i = 1; i <= number; i++) {
html += "<p>Label #" + i + ": <span>" + $("#input_" + i).val() + "</span></p>";
}
$("body").html(html);
})
$(document).on('keypress', function(e) {
if (e.which == 13) {
$("button").trigger("click");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" placeholder="Number of fields">
<button id="step1">Submit</button>
I am trying to add jquery validation in text area field for min 250 word and max 1000 words. And also display word count in span tag next to text area. Also I also how can I validation of if user copy paste into text area then also this validation should works. Any help and suggestion should be appreciated.
var maxWords = 1000;
var minWords = 250;
$(document).on('keypress', 'textarea[name="writ"]', function(e) {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
$('.writing_erorr').text("You've reached the maximum allowed words 1000.");
return false;
} else {
return $('#writing span').text('Total words: ' + wordcount);
}
});
$("textarea[name='writ']").bind('paste', function(e) {
// access the clipboard using the api
var pastedData = e.originalEvent.clipboardData.getData('text');
alert(pastedData);
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
$('.writing_erorr').text("You've reached the maximum allowed words 1000.");
return false;
} else {
return $('#writing span').text('Total words: ' + wordcount);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=writing class=cond>
<label class="required">Writing Entry</label>
<textarea name=writ placeholder="Writing Entries: 100 words min, 600 words max"></textarea>
<span></span>
<div class="writing_erorr"></div>
</div>
The code below works as requested, I've added some attributes to the text areas so that you can have multiple text areas on a single page, all with different limits.
You need to add the following attributes word-limit="true", max-words='n', min-words='n'. No placeholder is needed anymore because the code automatically generates one after page load.
It is a little more involved that your example, but allows you to do more (not sure what your overall project is).
Word Count
The basic code to do a word count is as follows:
wordCount = $.trim( $("#writing").val() ).split(/\s+/).filter(Boolean).length;
Explaination of the code:
$("#writing").val() - gets the value of the textarea (i.e. the string)
.trim() removes any whitespace at the start or end of the string
.split(/\s+/) divides the string around every space and puts them into an array
.filter(Boolean) skips any blank values in the array - i.e. those created by double spacing
.length gets the length of the array (i.e. how many words there are)
Demo
// Cycle through each textarea and add placeholder with individual word limits
$("textarea[word-limit=true]").each(function() {
$(this).attr("placeholder", "Writing entries: " + $(this).attr("min-words") + " words min, " + $(this).attr("max-words") + " words max");
});
// Add event trigger for change to textareas with limit
$(document).on("input", "textarea[word-limit=true]", function() {
// Get individual limits
thisMin = parseInt($(this).attr("min-words"));
thisMax = parseInt($(this).attr("max-words"));
// Create array of words, skipping the blanks
var removedBlanks = [];
removedBlanks = $(this).val().split(/\s+/).filter(Boolean);
// Get word count
var wordCount = removedBlanks.length;
// Remove extra words from string if over word limit
if (wordCount > thisMax) {
// Trim string, use slice to get the first 'n' values
var trimmed = removedBlanks.slice(0, thisMax ).join(" ");
// Add space to ensure further typing attempts to add a new word (rather than adding to penultimate word)
$(this).val(trimmed + " ");
}
// Compare word count to limits and print message as appropriate
if ( wordCount < thisMin) {
$(this).parent().children(".writing_error").text("Word count under " + thisMin + ".");
} else if (wordCount > thisMax) {
$(this).parent().children(".writing_error").text("Word count over " + thisMax + ".");
} else {
// No issues, remove warning message
$(this).parent().children(".writing_error").text("");
}
});
.writing_error {
color: red;
}
[id^=writing] {
border-bottom: 1px solid grey;
margin-bottom: 20px;
padding-bottom: 20px;
}
label {
width: 100%;
}
textarea {
width: 100%;
margin-top: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=writing1 class=cond>
<label class="required">Writing Entry 1</label>
<textarea name=writ word-limit="true" max-words="600" min-words="100"></textarea>
<span></span>
<div class="writing_error"></div>
</div>
<div id=writing2 class=cond>
<label class="required">Writing Entry 2</label>
<textarea name=writ></textarea>
<span></span>
<div class="writing_error"></div>
</div>
<div id=writing3 class=cond>
<label class="required">Writing Entry 3</label>
<textarea name=writ word-limit="true" max-words="10" min-words="4"></textarea>
<span></span>
<div class="writing_error"></div>
</div>
in your javascript:
$('textarea#message_area').on('keyup',function()
{
var maxlen = $(this).attr('maxlength');
var length = $(this).val().length;
if(length > (maxlen-10) ){
$('#textarea_message').text('max length '+maxlen+' characters only!')
}
else
{
$('#textarea_message').text('');
}
});
element:
<form>
<label for="message_area">No more than 100 characters</label>
<p>
<textarea id="message_area" maxlength="100" rows="6" cols="70"></textarea>
</p>
<span class="hint" id="textarea_message"></span>
</form>
Hi Guys I have been working on this script for some time and I just cant make it work well I may be missing an important argument to get it to work properly..
I need to calculate the values from inside of a tag and add up the total to a heres the HTML:
<div class="catProdAttributeItem">
<input type="radio" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="radio" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br><br>
<span style="display:none;" class="original_price">£0.00</span>
<div class="updated_price" id="show-price">£0.00</div>
And here is my Script:
$('.catProdAttributeItem img').on("click", function() {
$(this).siblings('input[type=radio]').attr('checked', true);
var original_price = $('.original_price').text().replace(/[^0-9\.]/g, '');
parseFloat(this.original_price);
var warehouse_price = $(this).siblings('.catProdAttributeItem span').text().replace(/[^0-9\.]/g, '');
warehouse_price = parseFloat(warehouse_price);
var total_price = parseFloat(original_price) + parseFloat(warehouse_price);
$('.updated_price').html('£' + total_price.toFixed(2));
})
I can only get the result of the clicked siblings, please some help is much appreciated..
I was expecting to add up the values displayed on the .updated_price when the input is selected but it will work on a wider set of inputs where you can check more inputs and you would get the result from all the inputs checked
DEMO FIDDLE
You need the checkbox for each car (not radio). See below:
$(document).ready(function() {
$('.catProdAttributeItem img').on("click", function() {
// Make checkbox adjustment
$(this).siblings('input:checkbox').click();
});
$(document).on('click', 'input:checkbox', calcTotal);
});
function calcTotal() {
var total_price = 0;
// find all .catProdAttributeItem divs
$(document).find('.catProdAttributeItem').each(function() {
// see if the checkbox is checked to add to the total_price
var $checkbox = $(this).find('input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
// finally display the price
$('.updated_price').html('£' + total_price.toFixed(2));
}
.catProdAttributeItem {
width: 300px;
float: left;
display: inline-block;
text-align: center;
}
img {
width: 100px;
height: auto;
}
.updated_price {
clear: both;
margin: 20px 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="catProdAttributeItem">
<input type="checkbox" id="5583116" name="752526">
<span>Ford £19.99</span>
<img src="http://www.breakerlink.com/blog/wp-content/uploads/2014/01/Ford.png">
</div>
<div class="catProdAttributeItem">
<input type="checkbox" id="5971554" name="752526">
<span>Ferrary £19.99</span>
<img src="http://www.assettocorsa.net/wp-content/uploads/2013/09/logo2.png">
</div>
<br>
<br>
<div class="updated_price" id="show-price">£0.00</div>
From my understanding of what you're trying to do, you will want to simply iterate over all .catProdAttributeItem elements and add the price only if the radio button is checked:
var warehouse_price = 0;
$('.catProdAttributeItem')
.filter(function() {
// only interested in checked radio boxes
return $('input:checked', this).length > 0;
})
.each(function() {
var price = parseFloat($('span', this).text().replace(/[^\d.]/, ''));
warehouse_price += price;
});
$('.updated_price').html('£' + total_price.toFixed(2));
This answer is a combination of Sigismundus answer + A bit of twicks to be able to grab the results from both either the radio buttons and check boxes the img click didn't work quite well, but now if added a new function to get the images as radio buttons it would work.
var priceSelect = parseFloat(document.getElementById("totalprice").value);
$('.catProdAttributeItem input[type=radio], .catProdAttributeItem input[type=checkbox] ').on("click", function() {
var total_price = 0;
$(document).find('.catProdAttributeItem').each(function() {
var $checkbox = $(this).find('input:radio, input:checkbox');
if ($checkbox.is(':checked')) {
var text = $(this).find('span').html();
total_price += parseFloat(text.replace(/[^0-9\.]/g, ''))
}
});
$('#totalprice').html('£' + total_price.toFixed(2));
document.getElementById('totalprice').value = total_price+priceSelect;
});
Right now I am learning some Javascript but got many problems right now since my skills are low. I need some help with several problems in this code.
I am trying to write a game called "hit the fish". It has a timer, score and onclick.
Onlclick the fish should disappear and 1 point will be added in the score. There is a timer limit of 60 seconds.
Here is the whole code.
<html>
<head>
<title>
Hit the fish!
</title>
<style>
table{
margin-left: auto;
margin-right: auto;
width: 70%;
height: 90%;
background-color:#66ff00;
}
#playground input{
position: inherit;
height: 100px;
width: 100px;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
}
#input {
height:40px;
}
#area {
background-color:#888;
position:absolute;
left:0px;
right:0px;
top:50px;
bottom:0px;
}
#area button {
width:150px;
height:30px;
position:absolute;
}
.red {
color:red;
}
</style>
<script language="Javascript">
function one () {
document.play.one.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function two () {
document.play.two.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function three () {
document.play.three.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function four () {
document.play.four.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function five () {
document.play.five.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function six () {
document.play.six.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function seven () {
document.play.seven.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function eight () {
document.play.eight.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function nine () {
document.play.nine.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function count()
{
stop();
// get the counter element
var counter = document.getElementById("counter");
// get it's value
var value = parseInt(counter.innerHTML);
// increase it
value = value + 1;
// write the new value back
counter.innerHTML=value;
// limitation
if(value===60){
alert("Time Out!");
clearInterval(countTimer);
document.getElementById("counter").innerHTML="0";
document.getElementById("score").innerHTML="0";
}
}
function start () {
stop();
var countTimer = setInterval("count()",1000);
document.play.four.value=">( °3°)";
document.play.three.value=">( °3°)";
setTimeout("nextone ()");
var score = document.getElementById("score");
}
function score(){
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function nextone () {
document.play.four.value="";
document.play.five.value=">( °3°)";
setTimeout("nexttwo ()",400);
}
function nexttwo () {
document.play.three.value="";
setTimeout("nextthree()",400);
}
function nextthree () {
document.play.seven.value=">( °3°)";
document.play.one.value=">( °3°)";
document.play.six.value=">( °3°)";
setTimeout("nextfour ()",700);
}
function nextfour () {
document.play.one.value="";
document.play.six.value="";
document.play.two.value=">( °3°)";
setTimeout("nextfive ()",700);
}
function nextfive () {
document.play.seven.value="";
document.play.two.value="";
document.play.four.value=">( °3°)";
setTimeout("nextsix ()",800);
}
function nextsix () {
document.play.eight.value=">( °3°)";
document.play.two.value=">( °3°)";
setTimeout("nextseven ()",700);
}
function nextseven () {
document.play.eight.value="";
document.play.five.value=">( °3°)";
setTimeout("nexteight ()",400);
}
function nexteight () {
document.play.nine.value=">( °3°)"
document.play.four.value=">( °3°)";
setTimeout("nextnine ()",500);
}
function nextnine () {
document.play.five.value="";
document.play.four.value="";
document.play.one.value=">( °3°)";
setTimeout("nextten ()",200);
}
function nextten () {
document.play.three.value=">( °3°)";
document.play.six.value=">( °3°)";
setTimeout("nexteleven ()",600);
}
function nexteleven () {
document.play.one.value="";
document.play.seven.value=">( °3°)";
setTimeout("nexttwelve ()",500);
}
function nexttwelve () {
document.play.two.value=">( °3°)";
document.play.nine.value=">( °3°)";
setTimeout("nextthirteen ()",700);
}
function nextthirteen () {
document.play.one.value=">( °3°)";
document.play.nine.value="";
document.play.seven.value="";
setTimeout("start ()",600);
}
function stop () {
clearInterval(countTimer);
document.play.one.value="";
document.play.two.value="";
document.play.three.value="";
document.play.four.value="";
document.play.five.value="";
document.play.six.value="";
document.play.seven.value="";
document.play.eight.value="";
document.play.nine.value="";
}
function reset()
{
document.getElementById("counter").innerHTML="0";
document.getElementById("score").innerHTML="0";
}
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
</script>
</head>
<body>
<div id="input">
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
<button onclick="reset()">reset</button>
<div style="font-size:10em" id="counter">0</div><br>
<p>Your score:</p><div style="font-size:5em" id="score">0</div>
<script>
var countTimer = setInterval('count()',1000);
</script>
</div>
<div id="playground">
<table border=100 cellpadding=0 cellspacing=0>
<tr>
<td>
<form name="play">
<center>
<INPUT TYPE="button" NAME="one" OnClick="one ()" id="one" value=" ">
<INPUT TYPE="button" NAME="two" OnClick="two ()" id="two" value=" ">
<INPUT TYPE="button" NAME="three" OnClick="three ()" id="three" value=" ">
<br>
<INPUT TYPE="button" NAME="four" OnClick="four ()" id="four" value=" ">
<INPUT TYPE="button" NAME="five" OnClick="five ()" id="five" value=" ">
<INPUT TYPE="button" NAME="six" OnClick="six ()" id="six" value=" ">
<br>
<INPUT TYPE="button" NAME="seven" OnClick="seven ()" id="seven" value=" ">
<INPUT TYPE="button" NAME="eight" OnClick="eight ()" id="eight" value=" ">
<INPUT TYPE="button" NAME="nine" OnClick="nine ()" id="ten" value=" ">
<br>
</td>
</tr>
</table>
</div>
</body>
</html>
The problem is the counter goes too fast after 20 - 30, after click the button the fish doesn't disappear and no points are added on score.
In no particular order...
(1) The problems with the counter are due to the way you call it and where you store the countTimer variable. Because you want several functions to be able to access countTimer, you should declare it in a way they can all access it; the simplest way is for it to be a global variable, which you can do just by having
var countTimer;
at the top of the script, and not using var when referring to countTimer elsewhere. You call the function start from the function nextThirteen, and start sets the timer again. What this does is actually set a new timer on top of the old one, which is why the count appears to speed up.
(2) Your html is also not valid which may cause some problems; make sure you close the form and center tags. (You are not supposed to use the center tag any more, anyway).
(3) Your code is in the head but most of it runs straight away, before the page has loaded. So the following line:
var score = document.getElementById("score");
(outside of any of the functions) causes an error because the element score has not been written yet. The simplest way to avoid this is to put your script at the end of the body of the page.
(4) The functions one, two, three need to have different names from the inputs in the form. That is why none of the buttons work.
Some general points as you learn more:
avoid repetition. There's no need for all the one, two, three functions etc. You could use a loop or a single event handler that finds out which button has been pressed.
use your browser's console to check for errors that are being produced. Your code was causing the error object is not a function, and searching for that is how I found out why the buttons were not working.
read about variable scope