jquery dynamically created checkbox not working properly with function - javascript

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();
});
});

Related

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/

Keep the dropdown values after submit the form

Creating dropdown box dynamically and options are adding through javascript arrays and I wanted to keep the values after i submit the form. Let us say if I select 'OOR' and '2' then after submit the form, I wanted to see these values in those dropdowns.
Thanks.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script language="javascript">
OORs=new Array("1","2","3","4");
NoOORs=new Array("A","B","C");
populateSelect();
$(function() {
$('#fenv').change(function(){
populateSelect();
});
});
function populateSelect(){
fenv=$('#fenv').val();
$('#market').html('');
if(fenv=='OOR'){
$.each(OORs,function(index,t) {
$("#market").append("<option value='"+t+"'>" +t+ "</option>");
});
}
else {
$.each(NoOORs,function(index,t) {
$("#market").append("<option value='"+t+"'>" +t+ "</option>");
});
}
}
</script>
<form>
<select id="fenv" NAME="fenv">
<option value="OOR2">OOR2</option>
<option value="OOR">OOR</option>
</select>
<select id="market" name="market"></select>
<input type="submit" name="submit" value="submit" >
</form>
You can make use of hidden fields to persist the data after form submits. Like this:
OORs=new Array("1","2","3","4");
NoOORs=new Array("A","B","C");
populateSelect();
$(function() {
$('#fenv').change(function(){
populateSelect();
});
});
function populateSelect(){
fenv=$('#fenv').val();
marketvalues = [];
$('#market').html('');
if(fenv=='OOR'){
$.each(OORs,function(index,t) {
$("#market").append("<option value='"+t+"'>" +t+ "</option>");
marketvalues.push(t);
});
}
else {
$.each(NoOORs,function(index,t) {
$("#market").append("<option value='"+t+"'>" +t+ "</option>");
marketvalues.push(t);
});
}
$("#marketvalues").val(marketvalues.join(","));
}
</script>
<form method="post">
<select id="fenv" NAME="fenv">
<option value="OOR2" <cfif structKeyExists(form, "fenv") and form.fenv EQ "OOR2"> selected="selected"</cfif>>OOR2</option>
<option value="OOR" <cfif structKeyExists(form, "fenv") and form.fenv EQ "OOR"> selected="selected"</cfif>>OOR</option>
</select>
<select id="market" name="market">
<cfif structKeyExists(form, "marketvalues") and trim(form.marketvalues) NEQ "">
<cfloop list="#form.marketvalues#" index="mv">
<option value="#mv#" <cfif form.market EQ mv> selected="selected"</cfif>>#mv#</option>
</cfloop>
</cfif>
</select>
<input type="submit" name="submit" value="submit"/>
<input type="hidden" name="marketvalues" id="marketvalues" value=""/>
</form>
To persist some data you will need to use php session or post.
For the first select it should be easy:
<select id="fenv" NAME="fenv">
<option value="OOR2" <?php if($_POST["fenv"]=="OOR2") echo "selected";?>>OOR2</option>
<option value="OOR" <?php if($_POST["fenv"]=="OOR") echo "selected";?>>OOR</option>
</select>
For the second part is more complicated tho. You could do some javascript magic setting it to the propper value:
var element = document.getElementById('market');
element.value = "<?php echo(isset($_POST['market'])&&($_POST['market']!='')?$_POST['market']:'');?>";
Its easy to do.
Once you submit your form (to the same page only), you can check for the submit condition in CF and run a JavaScript function that takes the submitted values.
Submit the form
fn populateSelect() populates the select boxes
CFIF checks if the page load is a form submission
runs the fn afterFormSubmitSetSelectedValues(fenv, market) values
<form method="post">
<select id="fenv" NAME="fenv">
<option value="OOR2">OOR2</option>
<option value="OOR">OOR</option>
</select>
<select id="market" name="market"></select>
<input type="submit" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script language="javascript">
var OORs = ["1","2","3","4"], //declaring the OORs
NoOORs = ["A","B","C"], //the NoOORs
fenvRef = $('#fenv'), //creating the ref using jQuery Once, so we do not need to do a DOM query again and again
marketRef = $('#market'), // same for market
populateSelect = function () {
var fenv = fenvRef.val(),
marketvalues = [];
marketRef.html('');
if ('OOR' === fenv) {
$.each(OORs, function(index,t) {
marketRef.append("<option value='" + t + "'>" + t + "</option>");
marketvalues.push(t);
});
} else {
$.each(NoOORs, function(index,t) {
marketRef.append("<option value='" + t + "'>" + t + "</option>");
marketvalues.push(t);
});
}
},
afterFormSubmitSetSelectedValues = function (fenv, market) { // upon reload this Fn() will set the selected values
fenvRef.val(fenv);
if ('OOR' === fenv) {
populateSelect();
}
marketRef.val(market);
};
$(function() {
fenvRef.change(function() {
populateSelect();
});
});
// this will populate the initial values
populateSelect();
<cfif isDefined('form') AND structKeyExists(form, 'submit')>
//only executed if the form is previously submitted
afterFormSubmitSetSelectedValues('<cfoutput>#form.fenv#</cfoutput>', '<cfoutput>#form.market#</cfoutput>');
</cfif>
</script>
Good luck!

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

Multiply and add values in text area by element in select

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

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