jQuery adding a numerical value to a span element - javascript

I have a HTML span element as shown below.
<span id="total_cost">4.99</span>
Then two following input elements as shown below (one radio field and one checkbox).
<!-- radio field -->
<input type="radio" name="delivery_method" value="standard" checked> standard (FREE)
<input type="radio" name="delivery_method" value="signed"> Signed (2.00)
<input type="radio" name="delivery_method" value="guaranteed"> Guaranteed (6.22)
<!-- checkbox -->
<input type="checkbox" value="digital" name="digital"> Digital copy (2.00)
On selection I would like what the user pressed for the radio field and checkbox field to be added to the value in the span element #total_cost. I would like to use jQuery for this solution.
I have got the radio fields working using javascript but I would like to use jQuery and I also can't get the checkboxes to work as well. Code for javascript shown below.
<script type="text/javascript">
$('input[name="delivery_method"]').on('change', function(){
if ($(this).val()=='signed') {
$("#delivery_price").html("£2.00");
$("#delivery_method").html("Royal Mail Signed For First Class");
$("#total_cost").html("£<?php echo ($item)*4.99 + 2.00; ?>");
} else if($(this).val()=='guaranteed') {
$("#delivery_price").html("£6.22");
$("#delivery_method").html("Royal Mail Special Delivery Guaranteed by 1PM");
$("#total_cost").html("£<?php echo ($item)*4.99 + 6.22; ?>");
} else {
$("#delivery_price").html("£0.00");
$("#delivery_method").html("Royal Mail First Class");
$("#total_cost").html("£<?php echo ($item)*4.99; ?>");
}
});
</script>
Any help would be greatly appreciated.
Many thanks in advance!

Try
<span id="total_cost">4.99</span>
<!-- radio field -->
<input type="radio" name="delivery_method" value="standard" data-price="0.00" data-method="Royal Mail First Class" checked />standard (FREE)
<input type="radio" name="delivery_method" value="signed" data-price="2.00" data-method="Royal Mail Signed For First Class" />Signed (2.00)
<input type="radio" name="delivery_method" value="guaranteed" data-price="6.22" data-method="Royal Mail Special Delivery Guaranteed by 1PM" />Guaranteed (6.22)
<!-- checkbox -->
<input type="checkbox" value="digital" name="digital" />Digital copy (2.00)
then
$('input[name="delivery_method"], input[name="digital"]').on('change', function () {
var $del = $('input[name="delivery_method"]:checked');
var $dig = $('input[name="digital"]');
$("#delivery_price").html('£' + $del.data('price'));
$("#delivery_method").html($del.data('method'));
var price = (parseFloat($del.data('price')) || 0) + ($dig.is(':checked') ? 2 : 0);
$("#total_cost").html('£' + price.toFixed(2));
})
Demo: Fiddle

You didn't show any code for the checkbox, so i am unsure what you have tried or why it is failing or what exactly you are trying to do with it, but if you just need the value of the checkbox
Give the checkbox an ID
<input type="checkbox" ID='digital' value="digital" name="digital"> Digital copy (2.00)
here is a sample jsfiddle

hope that's will help you: fiddle
var item = 0; //<?php echo ($item) ?>;
$('input[name="delivery_method"]').on('change', function(){
var total = 0;
if ($(this).val()=='signed') {
$("#delivery_price").html("£2.00");
$("#delivery_method").html("Royal Mail Signed For First Class");
total = item * 4.99 + 2.00;
$("#total_cost").text(total);
} else if($(this).val()=='guaranteed') {
$("#delivery_price").html("£6.22");
$("#delivery_method").html("Royal Mail Special Delivery Guaranteed by 1PM");
total = item * 4.99 + 6.22;
$("#total_cost").html(total);
} else {
$("#delivery_price").html("£0.00");
$("#delivery_method").html("Royal Mail First Class");
total = item * 4.99;
$("#total_cost").html(total);
}
});

Related

Validating form in JavaScript

My code is needs to validate all questions and submit only when each input has been selected. I think this is a logical issue as my code was working before hand, but I can't seem to find where I went wrong.
What is currently happening is that the user is only alerted when there has not been a selection in the first question, even if the rest of the inputs are left empty. I am really unsure why that is and have tried rewriting this several times. I've tried rewriting this a few times, but any help is really appreciated.
<li><input type="button" value="Click" onclick="calcDate()"></li>
<br/><br/>
<li><label id="web">Do you ever think about how you would design a web page?</label></li>
<li><input type="radio" value="no" name="rad1" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad2" /><span>Yes</span></li>
<li><label for="prior">Which the following are your main priorities? If none, select N/A</label></li>
<li>
<select name="prior">
<option selected="" value="Default">**Please select one of the following**</option>
<option value="ux">Ease of Use</option>
<option value="inter">Graphics & Content</option>
<option value="data">The Data Collected</option>
<option value="secure">Securing the site from possible attacks</option>
<option value="pm">Overseeing the creation of software</option>
<option value="none">None</option>
</select>
</li>
<li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
<li><input type="radio" value="no" name="rad3" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad4" /><span>Yes</span></li>
<li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
<li><textarea name="text1" id="text1" maxlength="3"></textarea></li>
<li><input type="submit" value="Finished!" onsubmit="return validateForm()"></li>
<li><input type="reset" id="reset"></li>
<script>
//form validation
function validateForm() {
//creating variables
var radio1 = document.quiz.rad1;
var radio2 = document.quiz.rad2;
var valOps = document.quiz.prior;
var radio3 = document.quiz.rad3;
var radio4 = document.quiz.rad4;
var tx1 = document.quiz.text1;
//calling functions
vWebRes(radio1, radio2, radio3, radio4);
valOps(prior);
vData(radio3, radio4);
vLength(tx1);
vCheck2(Text);
if (vWebRes(radio1, radio2, radio3, radio4)) {
if (valOps(prior)) {
if (vData(radio3, radio4)) {
if (vLength(tx1)) {
if (vCheck2(tx1)) {
return false;
}
}
}
}
}
//validating radio buttons
function vWebRes(radio1, radio2) {
x = 0;
if ((radio1.checked) || (radio2.checked)) {
x++;
}
if (x == 0) {
alert('You forgot a question!')
radio1.focus();
return false;
} else {
return true;
}
}
//validating checkbox options
function valOps(prior) {
if (prior.value == "Default") {
alert('Select an option from the drop-down menu');
prior.focus();
return false;
} else {
return true;
}
}
//validation question 3
function vData(radio3, radio4) {
z = 0;
if ((radio3.checked) || (radio4.checked)) {
z++;
}
if (z == 0) {
alert('You forgot a question!')
radio3.focus();
return false;
} else {
return true;
}
}
//validating text length
function vLength(tx1) {
var txLength = tx1.value.length;
if (txLength > 3) {
alert("That is an incorrect entry, try again.");
tx1.focus();
return false;
} else {
return true;
}
}
//validating text entry
function vCheck2(tx1) {
if ((tx1 == "Yes" || tx1 == "yes") || (tx1 == "No" || tx1 == "no")) {
tx1.focus();
return true;
} else {
alert('You entered an incorrect value, try again')
tx1.focus();
return false;
}
}
}
</script>
You might want to add the input fields (the values, .val) into an array like this, and the corresponding IDs without the .val as another array:
var arrayName = [a, b, c]; //just a mock example
var arrayNameInputs = [x, y, z]; //just a mock example, these should contain inputs with .val
And then loop through the results and check for empty indexes:
if(arrayNameInputs.indexOf("") !== -1){ //checks if there are any empty fields at all
for(i=0; i < arrayName.length; i++){
if(arrayName[i].val() == ""){
//do something, red outline, alert, w/e
}
}
}
Just make sure all your default values are " ", not "Default".
This is a bit different from how you tried to do it, but it worked for me so you might want to take a look.
I think you need to group your radio input into question.
Just rename your radio input.
See also : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
Edited: New working code. I write the comment in the code, read and try run the code.
Code:
//form validation
function validateForm() {
// you can use form
// see here: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
var quiz = document.forms[0];
// get those input
var radio1 = quiz.elements['radio1'];
var radio2 = quiz.elements['radio2'];
var selectedPrior = quiz.elements['prior'];
var textArea1 = quiz.elements['textArea1'];
// and get your answer
var formData = {
radio1: radio1.value,
selectedPrior: selectedPrior.value,
radio2: radio2.value,
textArea1: textArea1.value,
}
// you can see your answer in console [f12] developer mode
console.log("Data", formData);
// do your validation
//suggest not to nest your if clause because it will hard to read
// do it one by one and by your questions order
//if radio1 is blank
if (formData.radio1 == "") {
alert('You forgot a question!')
// in order to focus on radio input , you must specific which one you need to focus
// so I give each of them unique id
// choose one to focus
document.getElementById("radio1Yes").focus();
// document.getElementById("radio1No").focus();
// just for information, radio input focus is not visible
// if you want to stop when this is blank you just call return, it will end the function
// so the other validation will carry on when the radio1 is filled up
return;
}
//if selectedPrior is blank
if (formData.selectedPrior == "") {
alert('You forgot a question!')
selectedPrior.focus();
return;
}
//if radio2 is blank
if (formData.radio2 == "") {
alert('You forgot a question!')
document.getElementById("radio2No").focus();
return;
}
//if textArea1 is blank
if (formData.textArea1 == "") {
alert('You forgot a question!')
textArea1.focus();
return;
}
// after all value validate then you can go on submit the form
quiz.submit();
}
<!-- give your question into a form and give it a name -->
<form name="quiz">
<ol>
<li><input type="button" value="Click" onclick="calcDate()"></li>
<!-- You [must] group your radio input in order to get the value correctly-->
<li>
<label id="web">Do you ever think about how you would design a web page?
<div>
<input type="radio" id="radio1No" value="no" name="radio1" /><span>No</span>
</div>
<div>
<input type="radio" id="radio1Yes" value="yes" name="radio1" /><span>Yes</span>
</div>
</label>
</li>
<li>
<label for="prior">Which the following are your main priorities? If none, select N/A</label>
<div>
<select name="prior">
<!-- give the place holder option empty value [ just like this -> value="" ] -->
<option value="">**Please select one of the following**</option>
<option value="ux">Ease of Use</option>
<option value="inter">Graphics & Content</option>
<option value="data">The Data Collected</option>
<option value="secure">Securing the site from possible attacks</option>
<option value="pm">Overseeing the creation of software</option>
<option value="none">None</option>
</select>
</div>
</li>
<li>
<!-- remember to group your radio input -->
<label id="res">Do you enjoy conducting research, asking questions, and building reports?</label>
<div>
<input type="radio" value="no" id="radio2No" name="radio2" /><span>No</span>
</div>
<div>
<input type="radio" value="yes" id="radio2Yes" name="radio2" /><span>Yes</span>
</div>
</li>
<li>
<!-- just for suggestion: you still can use radio input on this -->
<label for="textArea1">Does hacking a system or stopping a system from being hacked sound interesting to you?
Type Yes or No:</label>
<div>
<textarea name="textArea1" id="textArea1" maxlength="3"></textarea>
</div>
</li>
<li>
<!-- I suggest to use onclick and do submition of form in javascript -->
<input type="button" value="Finished!" onclick="validateForm()">
<!-- you need to put this reset into a form to get it function correctly -->
<input type="reset" id="reset">
</li>
</ol>
</form>

JQuery: Checkbox won't stay Checked when toggling between buttons

I admit, still a noobie at jquery and I have a page with a total of 12 buttons / toggles (only 3 is shown as example) , which when clicked each one will pull up a php page with it set of checkboxes listed with products within a div on the advance search page. Since there are alot of information between each checkbox list, it slows the system down so I had to create an event when clicked it pulls that checkbox information when needed from another php page. Problem is... the checkboxes won't stay check when I toggle between the buttons. I have tried to a fuction where it sets the localstorage item when checked but doesn't seem to work. In so, need you help on how to make the checkboxes stay checked when going back to through each button / toggle.
So is there a way that will keep my checkboxes checked when toggleing? And How (please use code examples)
Is there a better way I could do to make this work more efficiently, so it will load the page faster? If so, How? (please use code examples)
KITE_PAGE.PHP (works the same for ball, hula hoop and other products)
<div>
<input type="checkbox" class="product_chkKite101" name="product_chk" value=" Like Kite 101 " /><label >Like USA Kite</label>
<input type="checkbox" class="product_chkKite102" name="product_chk" value=" Like Kite 102 " /><label >Like Mexico Kite</label>
<input type="checkbox" class="product_chkKite103" name="product_chk" value=" Like Kite 103 " /><label >Like Canada Kite</label>
</div>
NOTLIKE_KITE_PAGE.PHP (works the same for ball, hula hoop and other products)
<div>
<input type="checkbox" class="product_chkKite101" name="product_chk" value=" Not Like Kite 101 " /><label >Not Like USA Kite</label>
<input type="checkbox" class="product_chkKite102" name="product_chk" value=" Not Like Kite 102 " /><label >Not Like Mexico Kite</label>
<input type="checkbox" class="product_chkKite103" name="product_chk" value=" Not Like Kite 103 " /><label >Not Like Canada Kite</label>
</div>
Advance Search Page:
Html from Advance Search page
Buttons (again only three is shown):
<ul class="category">
<li>KITES</li>
<li>BALLS</li>
<li>HULA HOOPS</li>
</ul>
The Div where the pages will load into:
<div id="product_container" >
<div class="kite box" >
<div class="tx-row" id='kite-in' >
</div>
<div class="tx-row" id='kite-x' >
</div>
</div>
<div class="ball box" >
<div class="tx-row" id='ball-in' >
</div>
<div class="tx-row" id='ball-x' >
</div>
</div>
<div class="document box" >
<div class="tx-row" id='hoop-in' >
</div>
<div class="tx-row" id='hoop-x' >
</div>
</div>
</div>
JQuery that retrieves the information when button is clicked
$(document).ready(function(){
var $content = $('.box');
function showContent(type) {
$content.hide().filter('.' + type).show();
}
$('.category').on('click', '.kite-btn', function(e) {
if ($('#kite-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#kite-in").load("/wp-content/themes/child/kite_page.php");
$("#kite-x").load("/wp-content/themes/child/notlike_kite_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$('.category').on('click', '.ball-btn', function(e) {
if ($('#ball-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#ball-in").load("/wp-content/themes/child/ball_page.php");
$("#ball-x").load("/wp-content/themes/child/notlike_ball_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$('.category').on('click', '.hoop-btn', function(e) {
if ($('#hoop-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#hoop-in").load("/wp-content/themes/child/hoop_page.php");
$("#hoop-x").load("/wp-content/themes/child/notlike_hoop_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$(".box").hide();
});
An Additional Question to this as well:
Is there a way to disable a checkbox with same class (example: class="product_chkKite101" ) when one is checked between pages?
first what you can do is use on click attribute for all checkbox and pass the current element and better use id also because it will be unique and only one for a one checkbox
<input id="product_chkKite101" type="checkbox" onclick="checkChecked(this)" class="product_chkKite101" name="product_chk" value=" Not Like Kite 101 " /><label >Not Like USA Kite</label>
now in checkChecked function first make an empty array
var checkedCheckbox = [];
function checkChecked(ele){
var id = ele.id;
if ($.inArray(id, checkedCheckbox) !== -1)
{
var index = checkedCheckbox.indexOf(id);
if (index > -1) {
checkedCheckbox.splice(index, 1);
}
}else{
checkedCheckbox.push(id);
}
localStorage.setItem("selected", JSON.stringify(selected));
}
now to make checkbox checked when page is reload or when button is toogled you can run this code
var checkCheckedStorage = [];
$(function() {
if (localStorage.getItem("selected") != null) {
checkCheckedStorage = JSON.parse(localStorage.getItem("selected"));
checkChecked = checkCheckedStorage;
checkCheckedStorage.forEach(function(ele) {
console.log(ele);
$('#' + ele).prop('checked', true);
});
}
});
if this code doesnot get executed when toggling the buttons then what you can do is write the code inside a function again and call it from the toggle event of a button
I figured out why it wasn't staying checked. Every time I click on a button / toggle again, it reloads the information. I had my if statement with in my jquery in correct.
Updated jQuery
Had to add an id inside a div to each page. Then checked to see if the id is there or not. If it is not there, then upload the page. If it is there, just use the current page contents.
$('.category').on('click', '.kite-btn', function(e) {
if ($('#kitechk').length){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#kite-in").load("/wp-content/themes/child/kite_page.php");
$("#kite-x").load("/wp-content/themes/child/notelike_kite_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
alert('finish')
}
});

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Keeping data from detached Checkbox

I have an app I am creating, I've been able to get through it so far relatively hassle free. Until now. At the moment I need to find a way to keep the information produced by if statements for a check box. I have been able to get this working for a radio button by just storing the data in a global variable but I am not sure how to with a check box.
Code:
if ($('#Chk_0').is(':checked')) {
check = "Check1" + ", ";
countCheck++;
}
if ($('#Chk_1').is(':checked')) {
check = "Check2" + ", ";
countCheck++;
}
if (countCheck == 0) {
Check = "Nothing is checked";
}
Checkbox:
<div data-role="collapsible" id="cCheck" class="hCheck">
<h3>CheckBox</h3>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Option</legend>
<input type="checkbox" name="Check" id="Check_0" class="custom" value="" />
<label for="Check_0">Check1</label>
<input type="checkbox" name="Check" id="Check_1" class="custom" value="" />
<label for="Check_1">Check2</label>
</fieldset>
</div>
</div>
You can use an array and a string.
var checkedOptions=[]
var checkedGroup="";
if ($('#Check_0').is(':checked')) {
if(checkGroup=="Check"){
checkedGroup.push("Check_0");
}
else
{
checkGroup="Check"
checkedGroup=["Check0"];
}
countCheck++;
}
BTW: You have an error in your code. The IDs of the input tags and the jQuery are not the same.
As i understand your question ,you need to know is any check box is checked and if any checked you need the ids so this may be help
var ids = '';
$(':checked').each(function (i, element) {
ids += $(element).prop('id')+",";
})
then you can chekc if ids has length
if (ids.length>0) {
//use ids variable here
}

validating at least one checkbox selected on dynamically added fields

If you're dynamically adding form fields to an existing form, what's the best way of adding validation?
Consider this fiddle: http://jsfiddle.net/yWGK4/
<form action="#" method="post">
<div id="parent">
<div class="child">
<input type="checkbox" name="box1[]" value="1" /> 1
<input type="checkbox" name="box1[]" value="2" /> 2
<input type="checkbox" name="box1[]" value="3" /> 3
</div>
</div>
</form>
<button id="addBoxes">Add Boxes</button>
<script>
$(function() {
var parentdiv = $('#parent');
var m = $('#parent div.child').size() + 1;
$('#addBoxes').on('click', function() {
$('<div class="child"><input type="checkbox" name="box'+m+'[]" value="1" /> 1 <input type="checkbox" name="box'+m+'[]" value="2" /> 2 <input type="checkbox" name="box'+m+'[]" value="3" /> 3 </div>').appendTo(parentdiv);
m++;
return false;
});
});
</script>
On that form I'm adding new checkbox groups, and want to make sure at least one box from each group is checked (not one box across all groups). Anyone got any clever methods? Everything I've looked at would get very complicated due to the dynamically added fields.
It doesn't matter if the checkboxes are dynamic when validating on submit etc. so something like this would check if at least one checkbox per .child is checked :
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
FIDDLE
If you want to check it using jQuery you can use `.each()
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
You can find more about this jQuery functions in this links:
each()
find()
here's what I came up with. Basically you loop over the .child groups and test if they have a checkbox in the checked state..
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});

Categories

Resources