I am currently struggling to get the value I return from a checkbox to multiply with the value in the input box with jQuery.
I display a div when a checkbox is ticked to ask it for the quantity, thereafter I must multiply the quantity with the value of the checkbox.
Here is the current code:
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
recalculateQty();
recalculateCheck();
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
if ($('#2').is(':checked')) {
$('#checked-2').show();
} else {
$('#checked-2').hide();
}
if ($('#3').is(':checked')) {
$('#checked-3').show();
} else {
$('#checked-3').hide();
}
});
function recalculateQty() {
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
recalculateCheck();
});
});
}
function recalculateCheck() {
var sum = 0;
$("input[type=checkbox]:checked").each(function () {
sum += parseInt($(this).val());
});
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
});
});
$('#total').val(sum * qty);
}
});
<input type="checkbox" id="1" value="30" name="1" />
<input type="checkbox" id="2" value="60" name="2" />
<input type="checkbox" id="3" value="90" name="3" />
<div style="display:none;" id="checked-1">
<input type="text" name="product_1_qty" id="product_1_qty" placeholder="Quantity" class=" qty" value="0" />
</div>
http://jsfiddle.net/isherwood/9vRtJ/1/
You are trying to set an element value with total ID as a final result, but there is no such element in your html code. Just add this element in your html code (here i put another textbox):
<input type="text" id='total'>
Check out the Live demo for your fix
Or you can use better coding:(Read the comments) - Working DEMO
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
});
$('.qty').keyup(function () { // if user typed anyting in the Quantity
sum = parseInt($('#1').val()); // get checkbox value and change the data type to int
qty = parseInt($(this).val()); // get Quantity value and change the data type to int
//console.log(sum,qty);
if(sum && qty) { // if the values was not empty
$('#total').val(sum * qty); // show the result in the total element
} else { // if the values was empty
$('#total').val(''); // clear the result textbox
}
});
});
Related
I have created a form in which there are 2 input type=number. Both inputs are mandatory to be filled by the numbers below,between or out of the range given in min and max attribute provided which may or may not have decimal numbers. If number will be below the min range then the text color will turn ORANGE, if it is above the max range it will turn RED and if the number in input value matches the range it will turn GREEN, all these validations will be done by jQuery.
ISSUE here is I need to submit myForm but because of min & max attribute I get this tip "Value must be less than or equal to 20" or "Value must be greater than or equal to 10" for the inputs submitted lesser or greater than the range provided in min and max attributes respectively, because of this my form does not get submitted.
Can anyone tell me where I maybe going wrong or is there any solution for the same.
Link to the code :
JSFIDDLE
or
Please check the Snippet Below:
$(document).ready(function()
{
$("#weight").keyup(function()
{
var max = parseInt($('#weight').attr('max'));
var min = parseInt($('#weight').attr('min'));
if ($("#weight").val() >= min)
{
if ($("#weight").val() <= max)
{
$("#weight").css("color", "green");
}
else
{
$("#weight").css("color", "red");
}
}
else
{
$("#weight").css("color", "orange");
}
});
});
$(document).ready(function()
{
$("#bmi").keyup(function()
{
var max = parseInt($('#bmi').attr('max'));
var min = parseInt($('#bmi').attr('min'));
if ($("#bmi").val() >= min)
{
if ($("#bmi").val() <= max)
{
$("#bmi").css("color", "green");
}
else
{
$("#bmi").css("color", "red");
}
}
else
{
$("#bmi").css("color", "orange");
}
});
});
$(document).ready(function()
{
$('input').on('keypress', function(e)
{
if (e.which == 13)
{
switch ($(this).attr('id'))
{
case 'weight':
$('#bmi').focus();
e.preventDefault();
break;
case 'bmi':
$('#body_fat').focus();
e.preventDefault();
break;
case 'body_fat':
$('#submit').focus();
e.preventDefault();
break;
}
}
});
});
input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button
{
-webkit-appearance: none;
margin: 0;
}
.newdatatext
{
height:60px;
width:100%;
text-align:center;
font-weight:bold;
font-size:300%;
}
#usernewdetailsform
{
margin-top:6%;
width:100%;
}
#usernewdetailsform label
{
font-weight:bold;
font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form name="myForm" action="" method="POST">
<label for="weight">Weight :</label>
<input type="number" name="weight" id="weight" class="newdatatext" placeholder="Weight" min="10" max="20" step=".01" autofocus required>
<label for="bmi">BMI</label>
<input type="number" name="bmi" placeholder="BMI" min="10" max="20" id="bmi" step=".01" class="newdatatext" required>
<input type="submit" name="submit" id="submit">
</form>
The min and max attributes are used by the browsers to perform form validation. If you want to use them to determine jQuery behavior but want to skip browser blocking of form submission due to invalid values, store them as data- attributes and read them using the .attr() or .data() methods of jQuery, e.g.:
var max = parseInt($('#weight').attr('data-max'));
...or:
var max = parseInt($('#weight').data('max'));
Also, looking at your code I realized that you are:
using multiple DOM ready callbacks. You only need one, and you can put all your logic in it.
repeating the same logic repeatedly for multiple input elements. You can always take advantage of the context of a event, using $(this) to refer to the jQuery object that has triggered it.
containing nested conditional statements that are difficult to read. You can use guard clauses to assign the colors respectively, e.g.:
An example of a guard clause based on your logic:
var val = $(this).val();
if (val < min) {
$(this).css('color', 'orange');
return;
}
if (val > max) {
$(this).css('color', 'red');
return;
}
$(this).css('color', 'green');
Here is an updated example:
$(document).ready(function()
{
$("#weight, #bmi").keyup(function()
{
// Cache DOM node, min/max values, and input value
var $t = $(this);
var max = parseInt($t.attr('data-max'));
var min = parseInt($t.attr('data-min'));
var val = $t.val();
// Use guard clauses
if (val < min) {
$t.css('color', 'orange');
return;
}
if (val > max) {
$t.css('color', 'red');
return;
}
$t.css('color', 'green');
});
$('input').on('keypress', function(e)
{
if (e.which == 13)
{
switch ($(this).attr('id'))
{
case 'weight':
$('#bmi').focus();
e.preventDefault();
break;
case 'bmi':
$('#body_fat').focus();
e.preventDefault();
break;
case 'body_fat':
$('#submit').focus();
e.preventDefault();
break;
}
}
});
});
input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button
{
-webkit-appearance: none;
margin: 0;
}
.newdatatext
{
height:60px;
width:100%;
text-align:center;
font-weight:bold;
font-size:300%;
}
#usernewdetailsform
{
margin-top:6%;
width:100%;
}
#usernewdetailsform label
{
font-weight:bold;
font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form name="myForm" action="" method="POST">
<label for="weight">Weight :</label>
<input type="number" name="weight" id="weight" class="newdatatext" placeholder="Weight" data-min="10" data-max="20" step=".01" autofocus required>
<label for="bmi">BMI</label>
<input type="number" name="bmi" placeholder="BMI" data-min="10" data-max="20" id="bmi" step=".01" class="newdatatext" required>
<input type="submit" name="submit" id="submit">
</form>
You can not submit form if values in input fields will be not in the range.
In your case, you can change in HTML
min="10"
to
data-min="10"
and so on. And in JS:
var max = parseInt($('#weight').attr('data-min'));
You can use the data-min and data-max attributes to skip the validation errors and also action URL is not specified in the above code. So may be bcoz of that form is not submitted.
I'm making a form with checkboxes and radiobuttons
I use the value as price, which I calculate with a script so I get the total price of the selected checkboxes and radiobuttons.
<script>
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val());
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
</script>
<input type="radio" id="1" value="40" class= "calc" name = "780143050"> Gezichtsbehandeling (incl.)<br>
<input type="radio" id="2" value="40" class = "calc" name = "780143050"> Massage<br>
<input type="radio" id="3" value="75" class = "calc" name = "780143050"> beide
<span id="output"></span><input type="hidden" name="sum" id="sum" value="0">
<p>Totaal extra's : € <span id="price">0</span>
I have the following PHP
test.php
<?php
echo("keuze : " . $_POST['780143050'] . "<br />\n");
?>
I in my php script the value and the ID. How can I echo the ID of the selected radiobutton?
There are 2 ways to do this:
change the value of value to the value of the id
add the value of the id to the value
html:
<input type="radio" id="2" value="40|2" class = "calc" name = "780143050"> Massage<br>
js:
<script>
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val().split('|')[0]);
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
php
<?php
echo("keuze : " . split('|',$_POST['780143050'])[1] . "<br />\n");
?>
See below code. Selected radio button ID will be received as $_POST['selID']:
$('form').submit(function(){
var selID = $('form input[type=radio]:selected').attr('id');
$(this).append('<input type="hidden" name="selID" value="'+selID+'" />');
});
I got a code where you can add field inputs to a list, and then echo it out. What I'm looking for is a way of having a total of 3 fields. I not sure how to do it with the loop and so on, since the name of the field is the loop itself.
<?php
if(isset($_REQUEST['submit'])){
$field_values_array = $_REQUEST['field_name'];
foreach($field_values_array as $value){
echo $value;
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
<img src="add-icon.png"/>
</div>
</div>
Edit: 3 inputs instead of one being echoed out at the same row, and will be looped out as one. Something like an array $array[0],$array[1],$array[2]
I tried this solution, but doesn't work:
<?php
if(isset($_REQUEST['submit'])){
$field_values_array = $_REQUEST['field_name']." - ".$_REQUEST['field_name2']." - ".$_REQUEST['field_name3'];
foreach($field_values_array as $value){
echo $value;
}
}
?>
This is how you loop through each value in a $_REQUEST and get all values where the name is equal to field_name.
<?php
if(isset($_REQUEST['submit'])){
foreach ($_REQUEST as $parent => $value) { //Loop over $_REQUEST
if($parent == "field_name")
{
foreach ($_REQUEST[$parent] as $key=> $item){
//You can check if $item is empty
if(!empty($item))
{
echo "field_name[".$key ."] => ".$item."<br/>";
}
}
}
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10;
//Input fields increment limitation
var addButton = $('.add_button');
//Add button selector
var wrapper = $('.field_wrapper');
//Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/>X</div>';
//New input field html
var x = 1;
//Initial field counter is 1
$(addButton).click(function(){
//Once add button is clicked
if(x < maxField){
//Check maximum number of input fields
x++;
//Increment field counter
$(wrapper).append(fieldHTML);
// Add field html
}
}
);
$(wrapper).on('click', '.remove_button', function(e){
//Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove();
//Remove field html
x--;
//Decrement field counter
}
);
}
);
</script>
<form>
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
Add
<button name="submit" type="submit">
Send values
</button>
</div>
</div>
</form>
New full source demo
how can i one to one change the value of the next input?
this code doing check all or unchec all, but i want to check or uncheck one to one,
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).attr('checked')) {
jQuery('input:checkbox').attr('checked',true);
jQuery('input:text').attr('value','E');
} else {
jQuery('input:checkbox').attr('checked',false);
jQuery('input:text').attr('value','H');
}
});
});
Sample code:
<form>
<? for($i=1;$i<=5;$i++) { ?>
<input type="checkbox" id="pgun[]" name="pgun[]">
<input size="1" type="text" name="degerler[]" id="degerler[]" value="H">
<br />
<? } ?>
<label class="checkbox">
<input type="checkbox" value="E" name="topluekle" id="topluekle">
Check / Uncheck All *
</label>
</form>
Try
jQuery(function ($) {
$('#topluekle').click(function () {
$('input[name="pgun[]"]').prop('checked', this.checked);
$('input[name="degerler[]"]').val(this.checked ? 'E' : 'H');
});
});
Use val() like,
jQuery('input:text').val('H');
and use prop() in place of attr() like
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).prop('checked')) {
jQuery('input:checkbox').prop('checked',true);
jQuery('input:text').val('E');
} else {
jQuery('input:checkbox').prop('checked',false);
jQuery('input:text').val('H');
}
});
});
If you want to change value for each checkbox click then you can try,
jQuery(document).ready(function() {
jQuery('input[name="pgun[]"]').click(function() {
var newVal=$(this).next('input:text').val()=='E' ? 'H' : 'E';
$(this).next('input:text').val(newVal);
});
});
It will change corresponding text box's value of checkbox
jQuery(document).ready(function() {
var txtObj = $('input:text');
jQuery('input:checkbox').each(function(i){
jQuery(this).click(function(){
if(jQuery(this).attr('checked')) {
$(txtObj[i]).val("E");
} else {
$(txtObj[i]).val("H");
}
});
});
});
I have a form that allows the user to enter a weight, in either pounds or kilograms.
I'd like to store all of the data in kilograms, and using jQuery, would like the form to convert the weight_value to kilograms and change the weight_units option to "kg".
1 pound = 0.45359237 kilograms
The function should round the weight_value to the nearest kilogram (no decimals).
Any help you could provide would be appreciated!
<label> Weight:</label>
<input type="text" id="weight_value" />
<select id="weight_unit" />
<option value="lbs">lbs</option>
<option value="kg">kg</option>
</select>
Try this
function KtoLbs(pK) {
var nearExact = pK/0.45359237;
var lbs = Math.floor(nearExact);
return {
pounds: lbs,
};
}
var imperial = KtoLbs(10);
alert("10 kg = " + imperial.pounds + " lbs " );
My solution is here: http://jsfiddle.net/mVNDk/
$('#weight_unit').change(function(){
var v = $('input').val();
if($('#weight_unit').val() == 'lbs') {
$('input').val(v * 0.4535923);
} else {
$('input').val(v / 0.4535923);
}
});
try this
$(document).ready( function() {
$("#weight_value").keyup(function(){
var weight = parseFloat($("#weight_value").val());
if($("#weight_unit").val()=='lbs'){
//lbs value;
weight = (weight/0.45359237);
}else{
}
$("#weight_value_kg").val(Math.round(weight*100)/100);
});
});
<label> Weight:</label>
<input type="text" id="weight_value" />
<select id="weight_unit" />
<option value="lbs">lbs</option>
<option value="kg">kg</option>
</select>
<label> value:in kg</label>
<input type="text" id="weight_value_kg" />
Here is a try:
var kg = 0.45359237
$(document).ready(function() {
$("#weight_unit").change(function() {
if ($(this).val() == "kg") {
$("#weight_value").val(Math.round( $("#weight_value").val()*kg))
} else {
$("#weight_value").val(Math.round( $("#weight_value").val()/kg))
}
});
});
See it live on: http://jsfiddle.net/zeByX/
[EDIT] With the Math.floor(), you can get some weird results by switching from kg to pounds (try with 12 pounds and switch).
here's some code
$("#weight_unit").change(function() {
var result = 0;
if($(this).val() == "kg") {
result = Math.round($("#weight_value").val() * 0.45359237);
alert( result + " kg");
}
else {
result = Math.round($("#weight_value").val() / 0.45359237);
alert( result + " lbs");
}
});
you should replace the alert() functions for something you want to do with it
Checkout this fiddle buddy.
<label for='weight'>Weight</label>
<input type='text' id='weight' />
<select id='units'>
<option value='p'>Pound</option>
<option value='k'>Killogram</optoin>
</select>
<input type='text' id='result' />
with this script:
var weight = $('#weight'),
units = $('#units'),
result = $('#result');
// 1 pound = 0.45359237 kilograms
$(function() {
units.change(function() {
if ($(this).val() == 'p') {
// Weight is in Pound
result.val(weight.val() * 0.45359237);
}
else {
// Wiehgt is in Killogram
result.val(weight.val() / 0.45359237);
}
});
});