Multiply and add values in text area by element in select - javascript

Not that easy to explain, so let me paste a little code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
calculateSum();
$(".txt").live("keydown keyup", function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
// Iterate through each textboxes and add the values.
$(".txt").each(function() {
// Add only if the value is number.
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("#currentCost").html(sum.toFixed(2));
}
</script>
First off, I'd like to update that code to use the most recent version of jQuery, since it only works with 1.5 I think. (currently, it will just add the values in all textareas and update a span element)
<td>
<select name="struct[213]">
<option selected="selected" value="0"></option>
<option value="2" data-price="4000">A</option>
<option value="3" data-price="6000">B</option>
<option value="4" data-price="8000">C</option>
<option value="7" data-price="15000">D</option>
<option value="11" data-price="80000">E</option>
</select>
</td>
<td>
<input type="text" size="2" maxlength="4" class="txt"
name="numUnits[213]" value="0">
</td>
That's one of the textareas, all follow a similar fashion, and what I'd like to do with them is multiply the data-price in the select by the number entered in the textarea (all textareas and selects have the same [] following the name element), and then I'd like all those products added together in the span #currentCost:
<td class="L1" width="175">
Cost: <span class="redmoney" id="currentCost" name="currentCost">$0</span>
</td>
If that makes any sense...

Try
$(document).ready(function () {
calculateSum();
//register change handler for input and select elements
$(document).on("keyup, change", ".txt, select", function () {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
$(".txt").each(function () {
var value = $.trim(this.value);
if (value.length && !isNaN(value)) {
//find the select in the previous td and multiply the value
sum += parseFloat(value) * ($(this).parent().prev().find('option:selected').data('price') || 0);
//change back the color
$(this).css("background-color", "");
} else if (this.value.length != 0) {
$(this).css("background-color", "red");
}
});
$("#currentCost").html(sum.toFixed(2));
}
Demo: Fiddle

Related

How to sum the value of dynamically created textbox?

I want to sum the value of dynamically created textbox, but it doesn't work.
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount"/> </td> </tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customFields">
<tr>
<td>
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
</table>
You should use .on() on the table, which allows interaction with new dynamically-created elements. This will allow all keyup from all .code (even those added after page load) to bubble up to #customFields. The rest of your code should not need to be altered.
$(document).ready(function() {
$("#customFields").on( "keyup", ".code", function(){
calculateSum();
});
});
http://api.jquery.com/on/
Please see the
Running Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".code").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".code").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function addrow() {
$("#customFields").append('<tr><td><input type="text" class="ename" id="name" placeholder="Expense Name"/> </td> <td><input type="text" class="code" id="code" placeholder="Amount" onKeyUp = "calculateSum()"/> </td> </tr>');
}
</script>
</head>
<body>
<table id="customFields">
<tr>
<td colspan ="2">
<input type="button" value="Add" onclick="addrow();" />
</td>
</tr>
<tr><td><div id="sum">value</div></td></tr>
</table>
</body>
</html>

Change Dropdown value based on checkbox

I'm a bit stuck and not quite understanding why. I'm working within a pre-existing box that requires us to create a work-around - to simplify the explanation, basically what I need to do is populate a dropdown list with the value of a selected checkbox.
I've gotten the basics of that to work with the following code:
<h4>Select a Date:</h4>
<input type="checkbox" id="session_1" value="1" name="this">Session 1
<br>
<input type="checkbox" id="session_2" value="2" name="this">Session 2
<br>
<input type="checkbox" id="session_3" value="3" name="this">Session 3
<br>
<input type="checkbox" id="session_4" value="4" name="this">Session 4
<br/>
<input type="checkbox" id="session_5" value="5" name="this">Session 5
<br>
<input type="checkbox" id="session_6" value="6" name="this">Session 6
<br>
<br/><br/>
<select id="hidden_select">
<option>-</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
and the jQuery:
$(':checkbox').on('change',function(){
var th = $(this), name = th.prop('name');
if(th.is(':checked')){
$(':checkbox[name="' + name + '"]').not($(this)).prop('checked',false);
}
});
$('input#session_1').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(1)').attr('selected', true);
} else {
$('#hidden_select>option:eq(1)').attr('selected', false);
}
});
$('input#session_2').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(2)').attr('selected', true);
} else {
$('#hidden_select>option:eq(2)').attr('selected', false);
}
});
$('input#session_3').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(3)').attr('selected', true);
} else {
$('#hidden_select>option:eq(3)').attr('selected', false);
}
});
$('input#session_4').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(4)').attr('selected', true);
} else {
$('#hidden_select>option:eq(4)').attr('selected', false);
}
});
$('input#session_5').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(5)').attr('selected', true);
} else {
$('#hidden_select>option:eq(5)').attr('selected', false);
}
});
$('input#session_6').on('change', function () {
if ($(this).is(':checked')) {
$('#hidden_select>option:eq(6)').attr('selected', true);
} else {
$('#hidden_select>option:eq(6)').attr('selected', false);
}
});
You can see the jsfiddle here.
This works if you were to click one option and be done with it, or click different boxes in sequential order (1-6), but if you change your mind and go back (Select 1, then 4, then go back to one) the dropdown no longer updates.
Any thoughts as to why it stops recognizing the change? Is there a way to get past it?
Your options in your select are staying selected even after you click on a different checkbox. When you set one of the options to selected, make sure you remove the selected attribute from other options:
$('input#session_3').on('change', function () {
if ($(this).is(':checked')) {
//PUT THIS LINE ON EACH OF YOUR HANDLERS
$('#hidden_select>option').attr('selected', false);
$('#hidden_select>option:eq(3)').attr('selected', true);
} else {
$('#hidden_select>option:eq(3)').attr('selected', false);
}
});
Updated fiddle: https://jsfiddle.net/qnd75wmf/5/

Enable dropdown after typing all the values in textbox

In my HTML form, there are 2 textbox and one dropdown.
While loading the page, dropdown should not be editable(ie: disabled)
After filling all the textbox,the dropdown should be editable.
Please give an idea to solve this in javascript.
Try like this
HTML
<input type="text" id="text1" onblur="myFunction()">
<input type="text" id="text2" onblur="myFunction()">
<select id="select1" disabled>
<option>value</option>
</select>
Javascript
function myFunction() {
if (document.getElementById("text1").value.length > 0 && document.getElementById("text2").value.length > 0) {
document.getElementById("select1").disabled = false;
} else {
document.getElementById("select1").disabled = true;
}
}
Check both input elements value whenever keyup event is fired. If both the input elements have no inputs then disable the select element. Else enable it. Try this way,
javaScript :
function SetControlState(){
for(var i = 0; i < inputs.length; i++){
if(inputs[i].value.length == 0){
selectddl.disabled = true;
break;
} else{
selectddl.disabled = false;
}
}
}
var selectddl = document.getElementById("dropdl");
var inputs = document.getElementsByTagName('input');
var isEnabled = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i].id == 'first' || inputs[i].id == 'second'){
inputs[i].onkeyup = function(){
SetControlState();
};
}
}
HTML :
<select name="ddl" id="dropdl" disabled="true">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input type="text" id="first"/>
<input type="text" id="second"/>
jsFiddle

jquery dynamically created checkbox not working properly with function

I wrote a jquery for dynamic generation of check box as well as subtraction operation performed on text box with the value of checked check box. Jquery is working fine with predefined checkbox but not working with dynamically created checkbox. I tried solution like "ON" delegate but still i am struck here my code is like
HTML
<select class="select valid" id="destination" name="destination">
<option value="">Select One</option>
<option value="92">92(11)</option>
<option value="923">923(12)</option>
<option value="9230">9230(12)</option>
<option value="9231">9231(12)</option>
<option value="9232">9232(12)</option>
<option value="9233">9233(12)</option>
<option value="9234">9234(12)</option>
<option value="9235">925(12)</option>
</select>
<label for="port">Ports</label>
<input type="text" id="port" max="128" min="1"/><br><br />
<input type='checkbox' value="5" name='ch1[]' class='checkbox'/>Working Fine
<input type="submit" onsubmit="" value="Save" id="button1" name="button1">
JQuery
$(document).ready(function(){
$('#destination').change(function(){
$( ".dev" ).remove();
$( "#button1" ).before("<div class='dev' style='float:left;width:280px;'>
<input type='checkbox' value='1' name='ch1[]' class='checkbox'/>Not Working</div>");
});
var $cbs = $('.checkbox');
function calcUsage(){
var total = 0; //$("#more").val();
$cbs.each(function() {
if ($(this).is(':checked'))
{
// total = parseFloat(total) + parseFloat($(this).val());
total = parseFloat($(this).val());
}
});
$("#port").val($("#port").val()-total);
if($("#port").val()<0)
{
alert("Check Your Port Capacity");
}
}
//For checkboxes
$cbs.click(function() {
calcUsage();
});
});
JSFiddle Link
(*this is a sample code but i am populating checkbox on AJAX call for selected destination)
your not binding the new checkboxes that you are adding.
The click event is just binded to the checkboxs that you have when the document is ready. Your new checkboxes are not part of $cbs.
$(document).ready(function(){
$('#destination').change(function(){
$( ".dev" ).remove();
$( "#button1" ).before("<div class='dev' style='float:left;width:280px;'>
<input type='checkbox' value='1' name='ch1[]' class='checkbox'/>Not Working</div>");
});
function calcUsage(){
var total = 0; //$("#more").val();
$('.checkbox').each(function() {
if ($(this).is(':checked'))
{
// total = parseFloat(total) + parseFloat($(this).val());
total = parseFloat($(this).val());
}
});
$("#port").val($("#port").val()-total);
if($("#port").val()<0)
{
alert("Check Your Port Capacity");
}
}
//For checkboxes
$(document).on('click', '.checkbox', function() {
calcUsage();
});
});

Global If Else Statements

http://liveweave.com/EvfTww
I have two radio buttons one says div, and another says remove.
I add in some divs in html and when I select remove I want to be able to remove divs inside of #canvas when clicked.
The function provided below only works when divs are already visible when checked, but when I add new divs in the canvas from the code editor I also want to be able to remove those as well.
Any help is greatly appreciated.
HTML
<table id="main" border="1">
<tr>
<td id="canvas" valign="top"></td>
<td valign="top">
<div id="control_box">
<form id='tools'>
<input name="tool" id="tool-1" checked="checked" type="radio">
<label for="tool-1">DIV</label>
<input name="tool" id="tool-2" type="radio">
<label for="tool-2">Remove</label>
</form><br>
Border Width <select id="divborder">
<option value="1px">1px</option>
<option value="2px">2px</option>
<option value="3px" selected="selected">3px</option>
<option value="5px">5px</option>
<option value="7px">7px</option>
<option value="8px">8px</option>
<option value="9px">9px</option>
<option value="10px">10px</option>
</select><br>
Border Style <select id="divborderstyle">
<option value="dotted">dotted</option>
<option value="dashed">dashed</option>
<option value="solid" selected="selected">solid</option>
<option value="double">double</option>
<option value="groove">groove</option>
<option value="ridge">ridge</option>
<option value="inset">inset</option>
<option value="outset">outset</option>
</select><br>
Border Color
<input id="bcolor" type="text" name="bcolor" value="#f00" /></div><br>
BG Color
<input id="bgcolor" type="text" name="bgcolor" value="#000" onchange="window.set_fill_color(this.value); var col = this.value ; $('#colorSelectorFill').ColorPickerSetColor(col);" /></div>
<input type="button" id="nobg" value="none">
</div><br><br>
<textarea id='code' placeholder="The #canvas acts as page body"></textarea>
</td>
</tr>
</table>
JQuery/JavaScript
$('#tool-2').change(function() {
if ($(this).is(':checked')) {
alert('Remove Tool Chosen! You can now remove divs within the canvas.');
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
} else {
alert('Houston we have a problem!');
}
});
Try something like;
<input type="radio" name="test" value="div" checked> div
<input type="radio" name="test" value="remove"> remove
$("input[#name='test']").change(function(){
$("#parent_div_id").hide();
});
http://liveweave.com/lXdfqr
Using basically the same function as before, but this time I put it in another function called canvastools, and I removed the else statement as I do not need that for this experiment.
function canvastools(e) {
if ($('#tool-2').is(':checked')) {
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
}
}
I then call the function by stating that when the document is changed it will call the function.
$(document).change(function(e) {
canvastools(e);
});
I found that using the select element is a bit easier, however it's not exactly isolated. The remove tool's function will still apply even when a another tool/option is selected. I haven't figured out how to fix that problem just yet.
Here's the new fiddle/weave - http://liveweave.com/e5Efnc
function wrappertools(e) {
// Tools
$("select#tools").each(function() {
// DIV Tool
if ($(this).val() === 'div') {
$('#divoptions').show();
$('#spanoptions').hide();
// No Background Option
$('#nobg').click(function() {
$('input[name=bgcolor]').val('none');
});
var bcolor = $('input[name=bcolor]').val(),
bgcolor = $('input[name=bgcolor]').val(),
divborderstyle = $('#divborderstyle').val(),
divborder = $('#divborder').val();
alert('DIV Tool Selected!');
}
// Text Tool
if ($(this).val() === 'text'){
$('#spanoptions').show();
$('#divoptions').hide();
alert('Text Tool Selected!');
// No Background Option
$('#nospanbg').click(function() {
$('input[name=spanbgcolor]').val('none');
});
$('#addspantext').on('click', function() {
var spanbcolor = $('input[name=spanbcolor]').val(),
spanbgcolor = $('input[name=spanbgcolor]').val(),
spanborderstyle = $('#spanborderstyle').val(),
spanborder = $('#spanborder').val(),
spanfont = $('#spanfont').val(),
spancolor = $('#spancolor').val(),
spansize = $('#spansize').val(),
spantext = $('#spantext').val(),
placespan = $('<span style="position: relative; font-family: ' + spanfont + '; font-size: ' + spansize + '; font-color: ' + spancolor + '; border: ' + spanborder + ' ' + spanborderstyle + ' ' + spanbcolor + '; background: '+ spanbgcolor +';">' + spantext + '</span>');
$('.wrapper').append(placespan);
code.val(preview.html());
});
return false;
}
// Remove Tool
if ($(this).val() === 'remove') {
alert('Remove Tool Selected!');
$('#divoptions').hide();
$('#spanoptions').hide();
$('.wrapper div, .wrapper span').on('click', function() {
$(this).remove();
code.val(preview.html());
});
return false;
}
});
}
$(document).ready(function(e) {
wrappertools(e);
});
$(document).change(function(e) {
wrappertools(e);
});

Categories