I have downloaded the code for dual list box moving. it is working fine with default select boxes. but i have to generate the select box with ajax. when the select box options are dynamically generated, then moving options to one select box to another is not working.
Here is the link I have downloaded the code:
https://www.virtuosoft.eu/code/bootstrap-duallistbox/
Above linked demo is working fine since it has predefined select box.
but when i have created a dymanic selectbox options, then it is not moving options to one select box to another.
Thanks in advance. Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Agent Move Tool</title>
<link rel="stylesheet" href="HTTPS://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/CSS" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap4-duallistbox/4.0.2/bootstrap-duallistbox.css">
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="HTTPS://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap4-duallistbox/4.0.2/jquery.bootstrap-duallistbox.min.js"></script>
<style>
h2,hr, .hr-parent{
color:#188CCC;
text-align:center;
width:100%;
}
hr{
border-top:1px solid #188CCC;
margin-top:5px;
}
.btn-outline-secondary {
color: #fff;
background-color: #4285F4;
background-image: none;
border-color: #000;
}
.btn-outline-secondary:hover {
color: #fff;
background-color: #3B71CA;
border-color: #3B71CA; /*set the color you want here*/
}
option{
border-bottom: 1px solid #ddd;
padding-bottom: 8px;
padding-top: 4px;
padding-left:4px;
}
.visibility{
visibility:hidden;
}
.visibleShow{
visibility:visible;
}
</style>
</head>
<body class="container">
<div class="row">
<div class="hr-parent">
<img src="cigna-logo.svg" width="125px" class="img-responsive"/>
<h2>Agent Team Move Tool</h2>
</div>
<hr/>
<br/>
<div style="text-align:center;margin-top:15px;margin-bottom:15px;width:100%;">
<button type="button" id="get_teams" class="btn btn-warning">Get All Teams</button>
</div>
<div id="show_teams">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="sel1">Select Team From which you want to move agents</label>
<select class="form-control first-team" id="sel1" name="sellist1">
<option>Select</option>
<option value="MainTeam">CumulusAll - 5020</option>
<option value="MainTeam">CumulusCallGen - 5001</option>
<option value="MainTeam">CumulusCity - 5018</option>
<option value="MainTeam">CumulusCRM - 5003</option>
<option value="MainTeam">CumulusFinance - 5016</option>
<option value="MainTeam">CumulusHealth - 5017</option>
<option value="MainTeam">CumulusMain - 5014</option>
<option value="MainTeam">CumulusMobile - 5021</option>
<option value="MainTeam">CumulusOutbound - 5022</option>
<option value="MainTeam">CumulusTravel - 5015</option>
<option value="MainTeam">CumulusUtility - 5019</option>
<option value="MainTeam">CumulusUWF - 5023</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="sel1">Select The Team to Which you want to move agents</label>
<select class="form-control" id="sel1" name="sellist1">
<option>Select</option>
<option>CumulusMobile - 5021</option>
<option>CumulusOutbound - 5022</option>
<option>CumulusTravel - 5015</option>
<option>CumulusUtility - 5019</option>
<option>CumulusUWF - 5023</option>
</select>
</div>
</div>
<div class="col-md-12">
<select multiple="multiple" size="10" name="duallistbox_demo2" class="demo2" title="duallistbox_demo2">
</select>
<script>
var demo2 = $('.demo2').bootstrapDualListbox({
nonSelectedListLabel: '', // Heading of left side
selectedListLabel: '', // Heading of right side
preserveSelectionOnMove: 'moved',
moveOnSelect: false,
nonSelectedFilter: '' // filtering multiple at once, use this "ion ([7-9]|[1][0-2])"
});
</script>
</div>
</div>
</div>
<div class="col-md-12">
</br>
<div class="form-group">
<label for="comment">Event log:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div class="form-inline">
<div class="form-group row">
<label for="comment">Filename to Save As:</label>
<input class="form-control" id="inputFileNameToSaveAs"></input>
<button class="btn btn-info" style="margin-left:15px;" onclick="saveTextAsFile()">Save Text to File</button>
</div>
</div>
<div class="form-inline" style="margin-top:15px;">
<div class="form-group row">
<label for="comment">Select a File to Load:</label>
<input type="file" class="form-control" id="fileToLoad">
<button class="btn btn-info" style="margin-left:15px;" onclick="loadFileAsText()">Load Selected File</button>
</div>
</div>
</div>
<div class="col-md-12" style="text-align:center;margin-top:25px;">
<div class="form-group">
<button type="button" class="btn btn-success">Save</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('.moveall').html(">> Move All");
$('.move').html("> Move Selected");
$('.removeall').html("<< Remove All");
$('.remove').html("< Remove Selected");
$('#show_teams').hide();
$('#bootstrap-duallistbox-nonselected-list_duallistbox_demo2 option').hide();
$(document).on('change',".first-team", function(){
if(this.value=="MainTeam"){
$('#bootstrap-duallistbox-nonselected-list_duallistbox_demo2 option').show();
$('#bootstrap-duallistbox-nonselected-list_duallistbox_demo2').append('<option value="option1">Elmer Fudd - 1318</option><option value="option2">Josh Peterson - 1081</option><option value="option3">Trudy Jones - 1087</option><option value="option4">John Elway - 1312</option><option value="option5">Rick Barrows - 1082</option><option value="option6">Sammy Jackson - 1300</option><option value="option7">Demetra Moore - 1304</option><option value="option8">Angel Jolie - 1305</option><option value="option9">Johnny Knoxville - 1306</option><option value="option10">Jenna Anniston - 1301</option><option value="option11">Bradley Pitt - 1302</option><option value="option12">Bruce Willis - 1303</option><option value="option13">Steve O - 1308</option><option value="option14">Sandra Jefferson - 1080</option><option value="option15">Maria Quinteros - 1088</option><option value="option16">Owen Harvey - 1085</option><option value="option17">Bruce Wayne - 1320</option><option value="option18">Peter Parker - 1321</option><option value="option19">Steve Rogers - 1323</option><option value="option20">Annika Hamilton - 1086</option>');
$('#comment').text("Elmer Fudd - 1318 Agent removed from Team CumulusAll - 5020 at 06/01/2023 04:03:00pm Successfully.
Added to Team CumulusUWF - 5023");
}else{
$('#bootstrap-duallistbox-nonselected-list_duallistbox_demo2 option').hide();
$('bootstrap-duallistbox-selected-list_duallistbox_demo2 option').hide();
$('#comment').text("");
}
});
$('#get_teams').click(function(){
$('#show_teams').slideDown(1000);
});
});
function saveTextAsFile()
{
var textToSave = document.getElementById("comment").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("comment").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>
Related
presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined
I have a form divided in 3 different steps.
I want two different things:
Focus in input in steps 2 and 3
Validation for non-empty fields in steps 1 and 2
This is my code:
window.onload = function() {
document.getElementById("i_am").focus();
};
var form = document.getElementById('register');
form.noValidate = true;
form.addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
document.getElementById('youremailidMsg').innerHTML = document.getElementById('email_id').value == '' ? 'Please enter your email' : '';
}
}, false);
var questionNumber=0;
var questions=document.querySelectorAll('.notshown');
function next(){
questionNumber++;
if(questions.length>questionNumber)
{
document.querySelector('.shown').classList.remove('shown');
questions[questionNumber].classList.add('shown');
}
}
.notshown {
display: none;
}
.shown {
display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form class="" id="register" method="POST" action="" >
<div id="q0" class="notshown shown form-group">
<div class="form-group">
step 1
<select id="i_am" class="form-control">
<option value="">Choose your gender</option>
<option value="1-1">Men</option>
<option value="1-2">Woman</option>
</select>
</div>
<a class="btn btn-danger" onclick="next()">NEXT</a>
</div>
<div id="q1" class="notshown form-group">
<div class="form-group">
step 2
<input class="form-control" id="province_id" placeholder="City name" required="required">
</div>
<a class="btn btn-danger" onclick="next()" type="submit">NEXT</a>
</div>
<div id="q2" class="notshown">
<div class="form-group">
step 3
<input type="text" id="email_id" placeholder="Your email" required="required">
<div id="youremailidMsg"></div>
</div>
<button type="submit" class="btn btn-danger" >REGISTER</button>
</div>
</form>
Run here
https://jsfiddle.net/h7v94mxz/9/
So, I rewrote this using jQuery since you included the jQuery library in your question, as well as in the fiddle you provided.
Keep in mind, I did not take the time to make this bullet-proof from a validation standpoint, but I think you should be able to take what I have and build on it.
Let me know if you have any questions.
var questionNumber = -1;
var questions = $('.notshown');
var inputSelector = "input:not(:disabled):not([readonly]), textarea:not(:disabled):not([readonly]), select:not(:disabled):not([readonly])";
var form = $('#register');
form.on("input change propertychange", inputSelector, function() {
validateInput(this);
});
function validateInput(control) {
var $control = $(control);
if ($control.is("div")) {
$control.find(inputSelector).each(function() {
validateInput(this);
});
} else {
$control.removeClass("invalid-input");
$control.siblings(".error-message").remove();
if ($control.val() === "") {
$errorMessage = $("<span/>");
$errorMessage.addClass("error-message");
$errorMessage.text("Value cannot be empty!");
$control.addClass("invalid-input");
$errorMessage.insertAfter($control);
}
}
}
function next() {
var question = $(questions[questionNumber]);
validateInput(question);
if (question.find(".invalid-input").length) {
// contains invalid inputs, do not proceed
return false;
} else {
questionNumber++;
question = $(questions[questionNumber]);
if (questions.length > questionNumber) {
$('.shown').removeClass('shown');
question.addClass('shown');
// focus first input in group
question.find(inputSelector)[0].focus();
} else {
console.log('submitting!');
form.submit();
}
}
}
next();
.notshown {
display: none;
}
.shown {
display: block;
}
.invalid-input {
border: 1px solid red !important;
background-color: pink !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form class="" id="register" method="POST" action="">
<div id="q0" class="notshown form-group">
<div class="form-group">
step 1
<select id="i_am" class="form-control">
<option value="">Choose your gender</option>
<option value="1-1">Men</option>
<option value="1-2">Woman</option>
</select>
</div>
<a class="btn btn-danger" onclick="next()">NEXT</a>
</div>
<div id="q1" class="notshown form-group">
<div class="form-group">
step 2
<input class="form-control" id="province_id" placeholder="City name" required="required">
</div>
<a class="btn btn-danger" onclick="next()" type="submit">NEXT</a>
</div>
<div id="q2" class="notshown">
<div class="form-group">
step 3
<input type="text" id="email_id" placeholder="Your email" />
<div id="youremailidMsg"></div>
</div>
<a type="submit" onclick="next()" class="btn btn-danger">REGISTER</a>
</div>
</form>
I am reading data from a csv file and showing it in the form of table on screen. I have checkbox before every row with 'ID' saved as value in respective checkboxes. Now I want to remove fields with 'checked' checkboxes from the displayed table on the click of button - Cancel/Save
HTML Code-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>ABCD</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src ="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript2.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>EFGH</h2>
<p>KLMNO </p>
</div>
<div class="panel panel-primary">
<div class="panel-heading">KKKK</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<div class="page-header">
<h2>----</h2>
</div>
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6"><input type="file" accept=".csv" id="fileUpload"/></div>
<div class="col-sm-6"><input type="button" id="upload" class="btn btn-primary" value="Upload" /></div>
</div>
<div class="col-sm-7">
<div class="col-sm-2"><input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility:hidden" /></div>
<div class="col-sm-2"><input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility:hidden" /></div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self:center">
<div class="panel-body" style="max-height: 400px;min-height:400px;overflow-y: scroll;">
<div class="row">
<div class="col-sm-12"><center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="search" placeholder="Enter PO to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center></div><br /><br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
JavaScript2.js
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
$("<td/>").html('<input type="checkbox" id='+cells[0]+'>').appendTo(row);
//alert(cells[0]);
for (var j = 0; j < cells.length; j++) {
$("<td/>").html('<input type="text" disabled value=' +cells[j]+ '>').appendTo(row);
$("<td/>")
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
//document.getElementById("filter").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
How can this be implemented?
I assumed that you want to remove the row completely. Maybe you should clarify that a bit.
Add this script tag under your html file, or include it as a seperate js file. Tested, working.
<script type="text/javascript">
$("#cancel").on("click", function() {
$('input:checked').each( function() {
$( this ).closest("tr").remove();
});
});
</script>
To remove checked checkboxes you can use jQuery.
To remove just the checkboxes:
$('input').is(':checked').remove()
To do this "on a submit" of something, like a button click:
//Specific for button with ID someButton
$('button #someButton').on('click', function() {
$('input').is(':checked').remove();
});
Have a look at the jQuery checked selector, especially when combining it with the .is() function.
Like #Kartal answer, but without the .each() method you can delete all selected rows from the table like so:
//Remove all selected rows
$('button #someButton').on('click', function() {
$('tr > input:checked').remove();
});
The > selector is described here
I am trying to build a simple Pension calculator. Three inputs are taken in one form page and the result is displayed in another page. Output is in text format. But the following problem happens:
The output is shown as e.g. 2100021000 instead of actual 21000 this happens in all calculated results.
How to display results properly without the repeats ?
How do I display results in three separate text boxes in the results page similar to the text input form page ? I'm new to this. Need help.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content='width=device-width, initial-scale=1' name='viewport'/>
<title>Pension Calculator</title>
<link rel="stylesheet" href="js1/jquery.mobile-1.4.3.min.css" type="text/css"/>
<script src="js1/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="js1/jquery.mobile-1.4.3.min.js" type="text/javascript"></script>
<script>
// Bind to 'pageinit' event for our data page
//$(document).delegate('#data', 'pageinit', function(){
$(document).on('pagecreate', '#page1', function() {
// Do some processing when the button with id 'calc' is clicked or tapped
$('#calc').bind('click', function() {
//event.preventDefault();
var basic = $('[name="basic"]').val(),
pbasic = $('[name="pbasic"]').val(),
gratuity = $('[name="gratuity"]').val(),
da = $('[name="da"]').val(),
years = $('[name="years"]').val(),
total = $('[name="total"]').val(),
basic = basic + (basic*da/100);
pbasic = basic/2;
da = pbasic*da/100;
gratuity = (basic) + ((da))*15/26 * years;
if
(gratuity > 1000000)
gratuity = 10000000;
total = (pbasic) + (da);
gratuity = gratuity.toFixed(2);
pbasic = pbasic.toFixed(2);
total = total.toFixed(2);
// Get to the DOM node that has the actual BMI text
// while ($total.children().length) {
// $total = $total.children().first();
// Set it to the calculated value
// $total.text(total);
$result = $('#results #gratuity');
$result.text(gratuity);
$result = $('#results #pbasic');
$result.text(pbasic);
$result = $('#results #total');
$result.text(total);
});
});
</script>
</head>
<body>
<div id="page1" data-role="page">
<header data-role="header">
<h1>Simple Pension Calculator</h1>
</header>
<div data-role="content" data-theme="a">
<div data-role="content">
<form id="theForm">
<div data-role="fieldcontain" data-inset="true">
<label for="basic">Present Basic (Basic including Grade Pay + NPA)</label>
<input type="number" name="basic" id="basic" value="0" autofocus required>
</div>
<div data-role="fieldcontain">
<label for="years">Years of Service</label>
<input type="number" name="years" id="years" value="0" required>
</div>
<div data-role="fieldcontain">
<label for="da">Existing DA (%)</label>
<input type="number" name="da" id="da" value="0" required>
</div>
</form>
<a id="calc" href="#results" data-role="button" data-icon="gear">Calculate</a>
</div>
</div>
</div>
<div id="results" data-url="results" data-role="page">
<div data-role="header">
<h1>Results</h1>
</div>
<div data-role="content">
Your Gratuity:<br>
<span id="gratuity"><span style="font-size: 52px; "><strong>24</strong></span></span><br>
Your Basic Pension:<br>
<span id="pbasic"><span style="font-size: 52px; "><strong>24</strong></span></span><br>
Your Pension:<br><br>
<span id="total"><span style="font-size: 52px; "><strong>24</strong></span></span>
</div>
</div>
</body>
</html>
Clean up your code like this:
<div id="page1" data-role="page">
<header data-role="header">
<h1>Simple Pension Calculator</h1>
</header>
<div role="main" class="ui-content">
<form id="theForm">
<div data-role="fieldcontain" data-inset="true">
<label for="basic">Present Basic (Basic including Grade Pay + NPA)</label>
<input type="number" name="basic" id="basic" value="0" autofocus required />
</div>
<div data-role="fieldcontain">
<label for="years">Years of Service</label>
<input type="number" name="years" id="years" value="0" required />
</div>
<div data-role="fieldcontain">
<label for="da">Existing DA (%)</label>
<input type="number" name="da" id="da" value="0" required />
</div>
</form>
<a id="calc" href="#results" data-role="button" data-icon="gear">Calculate</a>
</div>
</div>
<div id="results" data-url="results" data-role="page">
<div data-role="header">
<h1>Results</h1>
</div>
<div role="main" class="ui-content">
Your Gratuity:<br />
<span id="gratuity" class="resultspan"></span><br />
Your Basic Pension:<br />
<span id="pbasic" class="resultspan"></span><br />
Your Pension:<br />
<span id="total" class="resultspan"></span>
</div>
</div>
Style the results span with CSS class instead of inline:
.resultspan {
font-size: 52px;
font-weight: bold;
}
In the script, pbasic, gratuity and total are not read from the DOM but rather set during calculation, so initialize them to zero. When reading other values from the inputs, you can use parseInt() to ensure the text is converted to integers before using them in the calculations:
$('#calc').on('click', function() {
//event.preventDefault();
var basic = parseInt($('#basic').val()),
da = parseInt($('#da').val()),
years = parseInt($('#years').val()),
pbasic = 0,
gratuity = 0,
total = 0;
basic = basic + (basic*da/100);
pbasic = basic/2;
da = pbasic*da/100;
gratuity = (basic) + ((da))*15/26 * years;
if (gratuity > 1000000)
gratuity = 10000000;
total = (pbasic) + (da);
gratuity = gratuity.toFixed(2);
pbasic = pbasic.toFixed(2);
total = total.toFixed(2);
$('#results #gratuity').text(gratuity);
$('#results #pbasic').text(pbasic);
$('#results #total').text(total);
});
Working DEMO
I'm trying to swap visibility of 2 elements based on a drop-down selection in the form.
If user selects any of the first 6 items, the "Message" area remains.
If user selections last item "Reproduction Rights", then "Message" disappears and is swapped with "Rights message" div.
I've got it working with the repro rights showing/hiding, but not the message box. I'm new to java, so pardon my ignorance. Here's the full page code or view at Paul-Rand.com:
Got it working with this code, but is there a cleaner way to do it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Paul-Rand.com :: Contact Us</title>
{embed=site/meta}
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/twocolumn}" />
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/global}" />
<script type="text/javascript" src="{path=scripts/livevalidation_standalone}"></script>
<script type="text/javascript">
// <![CDATA[
function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';
if ( txt.match(id1) ) {
document.getElementById(id1).style.display = 'block';
}
if ( txt.match(id2) ) {
document.getElementById(id2).style.display = 'block';
}
}
// ]]>
</script>
</head>
<body>
{embed="site/mainNav"}
<div id="container">
<div id="centercontent">
<h1>Contact Us</h1>
<div class="form-left">
<p>To send us a message, please fill out the form below. We'll get back to you shortly!</p>
{exp:freeform:form
required="name|email|message"
collection="Contact Form"
return="site/success"
notify="dlewandowski38#yahoo.com"
template="randContact"
file_upload="Email attachments"
send_attachment="yes" }
<label>Name / Company Name <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="name" id="Name" class="formMediumText"/></span>
</label>
<script type="text/javascript">var Name = new LiveValidation('Name');Name.add(Validate.Presence);</script>
<label>Email <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="email" id="Email" class="formMediumText"/></span>
<script type="text/javascript">var Email = new LiveValidation('Email');Email.add(Validate.Email );</script>
</label>
<label>Regarding
<br style="clear:both">
<span>
<select name="regarding" id="Regarding" class="formMediumText" onchange="display(this,'subject','Reproduction Rights');">
<option value="subject">General Inquiry</option>
<option value="subject">Suggestion for the site</option>
<option value="subject">Problem with the site</option>
<option value="subject">Work to Share</option>
<option value="subject">Story to Share</option>
<option value="subject">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select>
</span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="subject" style="display: none">
<label>Message
<br style="clear:both">
<span>
<textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea>
</span>
</label>
</div>
<br style="clear:both"/>
<hr/>
<h2 style="margin-bottom:-18px">Help the site grow</h2>
<h5 style="margin-bottom:-6px">Have a piece of Paul Rand work that's not seen on the site? Share it! </h5>
<p>Send your files (any image type, 800px wide or larger), your name and website (if available). I'll add it to the appropriate gallery and give you credit for your addition.</p>
<p>Your contributions are GREATLY APPRECIATED!</p>
<br/>
<label for="file" style="float:left;">Share a File (up to 5 per message):</label>
<span><input type="file" name="file1" id="file1" class="formPicBrowse"/></span>
<span><input type="file" name="file2" id="file2" class="formPicBrowse"/></span>
<span><input type="file" name="file3" id="file3" class="formPicBrowse"/></span>
<span><input type="file" name="file4" id="file4" class="formPicBrowse"/></span>
<span><input type="file" name="file5" id="file5" class="formPicBrowse"/></span>
<br style="clear:both"/>
<br/>
{if captcha}
<label>For security, please enter the word you see below:
<br style="clear:both">
<p style="width:160px;">{captcha}</p>
<span><input type="text" name="captcha" onfocus="if(this.value == 'Security Code') { this.value = ''; }" value="Security Code" id="Captcha" class="formMediumText" style="width:130px" /></span>
<script type="text/javascript">var Captcha = new LiveValidation('Captcha');Captcha.add(Validate.Presence);</script>
</label>
{/if}
<br style="clear:both"/>
<br/>
<p><input type="submit" name="submit" value="Send" class="buttons" style="font-size:18px; padding-top:8px;"/></p>
{/exp:freeform:form}
</div>
<script type="text/javascript">
var Name = new LiveValidation( 'Name', {onlyOnSubmit: true } );
Name.add( Validate.Presence );
var Email = new LiveValidation( 'Email', {onlyOnSubmit: true } );
Email.add( Validate.Presence );
var Message = new LiveValidation( 'Message', {onlyOnSubmit: true } );
Message.add( Validate.Presence );
var Captcha = new LiveValidation( 'Captcha', {onlyOnSubmit: true } );
Captcha.add( Validate.Presence );
</script>
</div>
</div>
{embed=site/bottomSection}
{embed=site/footer}
{embed=site/googleTracking}
</body>
</html>
For start it's good manners to clean your code to contain only the necessary bits before you post it here. It's difficult to wade through all of it in search of the relevant bits.
This isn't a JavaScript problem as such, just a plain logic issue. So what you want to do is a switch. If user selected option a set div 1 visible and div 2 invisible. If user selected option b do the opposite. Below is the modified display function
function display(obj) {
txt = obj.options[obj.selectedIndex].value;
if (txt.match("Reproduction Rights")) {
document.getElementById("Reproduction Rights").style.display = 'block';
document.getElementById("MessageDiv").style.display = 'none';
}
else {
document.getElementById("Reproduction Rights").style.display = 'none';
document.getElementById("MessageDiv").style.display = 'block';
}
}
and the HTMLto go with it. Two points to notice about this. You don't need the call to the hide() function in the onchange event handler, the display function is a switch, it'll do all the work. I also added a wrapping div with an id of MessageDiv to allow hiding both the message box and the text accompanying the message box. If the text isn't supposed to be hidden then by all means leave the div out.
<label>Regarding
<br style="clear:both">
<span><select name="regarding" id="Regarding" class="formMediumText" onchange="display(this, 'Reproduction Rights');">
<option value="General Inquiry">General Inquiry</option>
<option value="Suggestion for the site">Suggestion for the site</option>
<option value="Problem with the site">Problem with the site</option>
<option value="Work to Share">Work to Share</option>
<option value="Story to Share">Story to Share</option>
<option value="Pictures to Share">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select></span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="MessageDiv">
<label>
Message <em>(required)</em>
<br style="clear:both">
<span><textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea><script type="text/javascript">var Message = new LiveValidation('Message');Name.add(Validate.Presence);</script>
</span>
</label>
</div>