I have the following simple Jquery code that takes your input number * price to provide total.
I also need to have it include options with radio buttons, if checked +add to total.
Can anyone help me so that I can be able to add radio button options to make this take the input + radio buttons to get total price?
** It would also be nice if the price was Live as you typed/radio checked rather than clicking submit, but does not have to.
I have this so far:
http://jsfiddle.net/4bitlabs/tpkpd/15/
HTML:
<p class="list">How many "Linear Feet" of boards do you have?</p>
<input id="amount" />
<div class="addon">Add Paint $10.00<input id="amount" type="radio"value="10.00" class="radio"/></div>
<div class="price">$<label for="amount">0.00</label></div>
JQuery:
$(function () {
$('#amount').change(function () {
var $this = $(this);
$('label').text((parseFloat($this.val()) * 20.00).toFixed(2))
});
});
Thanks in advance.
There are some problems with your HTML. IDs should be unique.
I've done a fairly major rewrite, which I think will do what you are looking for. There are other ways to do it as well, but it should get you started
<input id="amount1" class="amount" />
I've made the IDs unique, and given the input boxes a class.
<input id="amount2" type="radio" value="10.00" class="radio addOn" data-for="amount1" />
The radio buttons also have a class of "addOn" and are attached to an label via the "data-for" tag.
$(function () {
$('.amount').change(function () {
changeAmount($(this));
});
$('.addOn').change(function () {
var $original = $('#' + $(this).data('for'));
changeAmount($original);
});
});
There are two ways to change the amount, one via changing the input box with a class of amount, one via changing the radio button with a class of addOn. The only difference is that the radio button function figures out what input box it is associated with.
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
// this handles the case when the val is not filled in.
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
$('label[for=' + id + ']').text(amount.toFixed(2))
}
jsFiddle
Use checked property.
And you better do not use duplicated IDs.
$(function () {
$('#amount').change(function () {
var $this = $(this);
var addPoint = $('input[type="radio"]').prop('checked') ? 10 : 0;
$('label').text((parseFloat($this.val()) * 20.00 + addPoint).toFixed(2))
});
});
Related
I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?
I have a quote form on a page (made using Gravity Forms WP plugin, but that doesn't matter). The form has multiple checkboxes on it - call these options. Each option has a different value 'assigned' to it. What I want to do, is add these values together if that particular checkbox is ticked, and subtract it's value if it's not. I hope that makes sense...?
Here is what I have so far:
jQuery(document).ready( function() {
jQuery('#choice_2_10_4, #choice_2_10_5').change( function() {
var option1 = Number( jQuery('#choice_2_10_4:checked').val() || 0 ); // Add 250 if checked
var option2 = Number( jQuery('#choice_2_10_5:checked').val() || 0 ); // Add 200 if checked
jQuery('#quote-price').val( option1 + option2 );
});
});
#quote-price is the field I'd like to show the total of the calculation in.
Can i give #choice_2_10_4 and #choice_2_10_5 a value by changing them to:
jQuery('#choice_2_10_4:checked').val(250)
jQuery('#choice_2_10_5:checked').val(250)
Or something along those lines?
Thanks
Instead of assigning a value to the checkboxes via #choice_2_10_4:checked').val(250) you can just put the value into the checkbox in the first place e.g. <input type="checkbox" value="250" />
Then just call it via #choice_2_10_4:checked').val()
When you call #choice_2_10_4:checked').val(250) it returns an array of elements.
console.log() it to see it for yourself
Yes, you can set the value but after that you have to trigger the change event like so:
jQuery('#choice_2_10_4:checked').val(250).trigger('change');
jQuery('#choice_2_10_5:checked').val(250).trigger('change');
$(function() {
$('.choice').on('change', function() {
var total = 0;
$('.choice').each(function() {
total += this.checked ? +this.value : -this.value;
});
$('#quote-price').val( total );
})
.change();
$('.add').on('click', function() {
var target = $(this).data('target'),
theval = $(target).is(':checked') ? +$(this).data('value') : +$(target).val();
$(target).val( theval ).trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="choice_2_10_4" class="choice" value="200"> 200
<button type="button" data-target="#choice_2_10_4" data-value="250" class="add">Add 250</button><br>
<input type="checkbox" id="choice_2_10_5" class="choice" value="400"> 400
<button type="button" data-target="#choice_2_10_5" data-value="350" class="add">Add 350</button><br>
<input type="text" readonly="readonly" id="quote-price"/>
Well, I have this text input that gets sum of all the attributes of "price" inside all checkboxes are checked.
now i can't get an attribute value from a checkbox.
here is my function:
function sum_options() {
var options = [];
$("#form-field-1-11-1").attr("price", 500);
$("#form-field-1-11-2").attr("price", 500);
$("#form-field-1-11-3").attr("price", 0);
$("#form-field-1-11-4").attr("price", 300);
$("#form-field-1-11-5").attr("price", 500);
$("#form-field-1-11-6").attr("price", 500);
$("#form-field-1-11-7").attr("price", 1250);
$("#form-field-1-11-8").attr("price", 500);
$("#form-field-1-11-9").attr("price", 700);
options[0] = $("#form-field-1-11-1");
options[1] = $("#form-field-1-11-2");
options[2] = $("#form-field-1-11-3");
options[3] = $("#form-field-1-11-4");
options[4] = $("#form-field-1-11-5");
options[5] = $("#form-field-1-11-6");
options[6] = $("#form-field-1-11-7");
options[7] = $("#form-field-1-11-8");
options[8] = $("#form-field-1-11-9");
var total = 0;
$.each(options, function() {
this.on("change", function() {
total += this.attr("price");
});
});
$("#sum-field").val(total);
}
thanks!!!
Your code is a lot more complex than it needs to be.
Firstly, you should use data-* attributes to assign custom data to an element. Creating your own non-standard attributes will mean your HTML is invalid and can lead to other issues. Also, if your code is relying on the price attribute, then it should be in the DOM when the page loads.
Secondly there's no need to build an array of single elements. You can select them all in to a single jQuery object and set a change() event handler on them in a single call. I grouped them by class in the below example.
Lastly you can get the total of all the prices by looping through the :checked boxes and adding up their prices. Try this:
$('.checkbox').change(function() {
var total = 0;
$('.checkbox:checked').each(function() {
total += parseFloat($(this).data('price'));
});
$("#sum-field").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="form-field-1-11-1" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-2" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-3" class="checkbox" data-price="0" />
<input type="checkbox" id="form-field-1-11-4" class="checkbox" data-price="300" />
<!-- other checkboxes here... -->
<input type="text" id="sum-field" />
To get the value of the Value attribute you can do something like this:
$("input[type='checkbox']").val();
Or if you have set a class or id for it, you can:
$('#check_id').val();
$('.check_class').val();
However this will return the same value whether it is checked or not, this can be confusing as it is differnt to the submitted form behaviour.
To check whether it is checked or not, do:
if ($('#check_id').is(":checked"))
{
// it is checked
}
You just forgot to parse the return value to a number:
parseInt(this.attr("price"));
the attr() function is returning a string value.
I have a function where I'm trying to add the total number of checkboxes ticked to a value that is already displayed in the textbox. The solution I have works but it doesn't update properly if I uncheck the boxes and click total again.
Is there a way I can fix this so that the textbox updates accordingly?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
You are updating the value of the input after every call to function sum().
Instead have the initial sum value.
Then every time use this value.
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}
Keep the original value of the textbox in a variable. Add an event listener to the checkboxes that count the number of checked boxes and adds that number to the original value, then updates the textbox.
Something like this:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
Here's a fiddle.
Here is the working demo of what I want to achieve. Just enter some value in input and you might get what I want to achieve. (Yes, I got it working but stay on..)
But it fails when multiple keys are pressed together.
What I am trying :
I have screen which contains few enabled and few disabled input elements. Whenever user updates any value in editable input element, I want to update disabled input which had same value with user updated value.
HTML :
<input value="foo" /> // When User updates this
<br/>
<input value="bar">
<br/>
<input value="Hello">
<br/>
<input value="World">
<br/>
<input value="foo" disabled> // this should be updated
<br/>
<input value="bar" disabled>
<br/>
<input value="foo" disabled> // and this also
<br/>
<input value="bar" disabled>
<br/>
<input value="Happy Ending!">
<br/>
I tried this which I think will save me from multiple_clicks_at_a_time
JS:
$(":input:not(:disabled)").keyup(function () {
// Get user entered value
var val = this.value;
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings");
$(siblings).each(function () {
// Update each input with new value
this.value = val;
});
});
$(function () {
$(":input:not(:disabled)").each(function () {
// Find inputs which should be updated with this change in this input
siblings = $(":input:disabled[value=" + this.value + "]");
// add them to data attribute
$(this).data("siblings", siblings);
});
});
But I am not able to pass the selectors to keyup function and invoke .each on it.
PS:
My previous completely different try, working with single_click_at_a_time but I felt that I am unnecessarily traversing the DOM again and again so dropped this
$(":input").keypress(function () {
$(this).data("oldVal", this.value);
});
$(":input").keyup(function () {
var oldVal = $(this).data("oldVal");
$(this).data("newVal", this.value);
var newVal = $(this).data("newVal");
$("input:disabled").each(function () {
if (this.value == oldVal) this.value = newVal;
});
});
I would group those inputs first and bind a handler for enabled elements to apply to the group. See below,
var grpInp = {};
$(":input").each(function () {
if (grpInp.hasOwnProperty(this.value)) {
grpInp[this.value] = grpInp[this.value].add($(this));
} else {
grpInp[this.value] = $(this);
}
});
$.each(grpInp, function (i, el) {
el.filter(':enabled').keyup(function () {
el.val(this.value);
});
});
DEMO: http://jsfiddle.net/fjtFA/9/
The above approach basically groups input element with same value, then filters them based on :enabled and bind a handler to apply it to the group.
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings", siblings);
No. The .data method called with two arguments does not get, but set the data (and returns the current selection). Also, you should make your variables local:
var siblings = $(this).data("siblings");
Working demo