Checkbox and Select Options update a Total Value - javascript

I have to create a small calculator form by using checkboxes and a select field.
If the user clicks on two checkboxes the select field will update to the option 2 and the total will update to a total figure of 456
Here is my HTML
<div>
<label for="one">1</label>
<input type="checkbox" name="1" id="1" value="228" />
</div>
<div>
<label for="two">2</label>
<input type="checkbox" name="2" id="2" value="228" />
</div>
<div>
<label for="three">3</label>
<input type="checkbox" name="3" id="3" value="228" />
</div>
<div>
<label for="four">4</label>
<input type="checkbox" name="4" id="4" value="228" />
</div>
<div>
<label for="five">5</label>
<input type="checkbox" name="5" id="5" value="228" />
</div>
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="text" name="Total" value="Total">
Here is a fiddle - http://jsfiddle.net/barrycorrigan/se21b1p6/1/
I'm just not sure how to create this in jquery. Any help will be greatly appreciated.
Thanks

this works:
$(function() {
var total = $("input[name='Total']");
var checkBox = $("input[type='checkbox']");
var _select = $("select");
checkBox.click(function(){
checkBox.prop("checked", false);
var _index = $(this).attr("id")
total.val(_index * 228);
_select.val(_index);
checkBox.each(function(){
if (_index > 0) {
$(this).prop("checked", true);
_index--;
}
});
});
_select.change(function() {
checkBox.prop("checked", false);
var _val = $(this).val();
total.val(_val * 228);
checkBox.each(function() {
if (_val > 0) {
$(this).prop("checked", true);
_val--;
}
});
});
});
You can see it in the fiddle: http://jsfiddle.net/yuanzm/se21b1p6/6/

you can try with this also
var countChecked = function() {
var n = $( "input:checked" ).length;
$('select >option:eq('+ n +')').prop('selected', true);
sum();
};
countChecked();
function sum() {
var inputs = $('input[type=checkbox]:checked'),
result = $('#total'),
sum = 0;
for(var i=0; i< $('input[type=checkbox]:checked').length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
$(result).val(sum);
}
$( "input[type=checkbox]" ).on( "click", countChecked );
http://jsfiddle.net/amolks/yfat78rL/

Related

Convert CheckBoxList to Multiselect Dropdown

I am currently trying to figure out how to edit the below script to convert a list from a check list to a multi select drop down list if it is possible. Any help that can be offered is appreciated.
function checkCheckBoxList(oSrc, args) {
var isValid = false;
$("#<%= cklLocations.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
isValid = true;
});
args.IsValid = isValid;
}
You can map the checked checkboxes
const $dropdown = $("#dropdown");
const $checks = $("#cklLocations input[type='checkbox']").on("click", function() {
$dropdown[0].length = 1; // remove all but first
const opts = $("#cklLocations input[type='checkbox']:checked").map(function() {
return `<option value="${this.value}">${this.name}</option>`
}).get().join("")
$dropdown.append(opts)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cklLocations">
<label>A<input type="checkbox" name="A" value="a" /></label>
<label>B<input type="checkbox" name="B" value="b" /></label>
<label>C<input type="checkbox" name="C" value="c" /></label>
<label>D<input type="checkbox" name="D" value="d" /></label>
</div>
<select id="dropdown" multiple>
<option disabled>Please select</option>
</select>

Activate Selectfield by click

I have 3 links they fill the selectfield with different option. If are the textlabel is active and somebody click the link selectlist1 or other it must activate the selectlabel. How i can do that?
<!doctype html>
<html>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<script>
var selectData = {
"sel1":{
"100":"select100", // selectdaten
"101":"select101",
"102":"select102",
"103":"select103",
"104":"select104"
},
"sel2":{
"201":"select201",
"202":"select202",
"203":"select203",
"204":"select204",
"205":"select205"
},
"sel3":{
"301":"select301",
"302":"select302",
"303":"select303",
"304":"select304",
"305":"select305"
}
};
jQuery(document).ready(function ($) {
$(document).on('click', '.selectin', function (event) {
event.preventDefault();
var b = $(this),
buttonId=b.attr('id'),
selectSet = selectData[buttonId],
selectField = $('#selectin');
selectField.empty();
if(selectSet){
$.each(selectSet,function(k,v){
selectField.append($('<option>', {value:k, text:v}));
});
}
return false;
});
});
</script>
<li>Selectlist1</li>
<li>Selectlist2</li>
<li>Selectlist3</li>
<form method="post" name="multiform" id="form8" action="" onchange="toggleRadio();">
<label for="radio1">INPUT Text</label>
<input id="radio1" type="radio" name="select" checked />
<label for="radio2">SELECT from</label>
<input id="radio2" name="select" type="radio" />
<label id="textLabel" for="textin">Formular
<input id="textin" type="text" placeholder="test1" />
</label>
<label id="selectLabel" for="selectin">Items
<select id="selectin">
<option selected></option>
<option value="6">item 6</option>
<option value="7">item 7</option>
<option value="8">item 8</option>
<option value="9">item 9</option>
</select>
</label>
</form>
<script>
function toggleRadio() { // will activate when the form will change.
var radio1 = document.getElementById('radio1'); // radio 1
var radio2 = document.getElementById('radio2'); // radio 2
if (radio1.checked == true) { // if the first checked display input and hide select
document.getElementById('textLabel').style.display = 'block';
document.getElementById('selectLabel').style.display = 'none';
document.getElementById('selectin').selectedIndex = 0; // clear selected option
}
else { // because you got only 2 option you don't have to use another condition
document.getElementById('textLabel').style.display = 'none';
document.getElementById('selectLabel').style.display = 'block';
document.getElementById('textin').value = ''; // clear input
}
}
toggleRadio(); // call the function
</script>
</body>
</html>
I have 3 links they fill the selectfield with different option. If are the textlabel is active and somebody click the link selectlist1 or other it must activate the selectlabel. How i can do that?
Insert this code on your selectin click;
var radio2 = document.getElementById('radio2');
if(radio2.checked == false){
radio2.checked = true;
toggleRadio();
}
This would check if radio2 is checked, if not, it will toggle it and call your function for displaying the select fields. Run the snippet, thanks.
<!doctype html>
<html>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<script>
var selectData = {
"sel1": {
"100": "select100", // selectdaten
"101": "select101",
"102": "select102",
"103": "select103",
"104": "select104"
},
"sel2": {
"201": "select201",
"202": "select202",
"203": "select203",
"204": "select204",
"205": "select205"
},
"sel3": {
"301": "select301",
"302": "select302",
"303": "select303",
"304": "select304",
"305": "select305"
}
};
jQuery(document).ready(function($) {
$(document).on('click', '.selectin', function(event) {
var radio2 = document.getElementById('radio2');
if (radio2.checked == false) {
radio2.checked = true;
toggleRadio();
}
event.preventDefault();
var b = $(this),
buttonId = b.attr('id'),
selectSet = selectData[buttonId],
selectField = $('#selectin');
selectField.empty();
if (selectSet) {
$.each(selectSet, function(k, v) {
selectField.append($('<option>', {
value: k,
text: v
}));
});
}
return false;
});
});
</script>
<li>Selectlist1</li>
<li>Selectlist2</li>
<li>Selectlist3</li>
<form method="post" name="multiform" id="form8" action="" onchange="toggleRadio();">
<label for="radio1">INPUT Text</label>
<input id="radio1" type="radio" name="select" checked />
<label for="radio2">SELECT from</label>
<input id="radio2" name="select" type="radio" />
<label id="textLabel" for="textin">Formular
<input id="textin" type="text" placeholder="test1" />
</label>
<label id="selectLabel" for="selectin">Items
<select id="selectin">
<option selected></option>
<option value="6">item 6</option>
<option value="7">item 7</option>
<option value="8">item 8</option>
<option value="9">item 9</option>
</select>
</label>
</form>
<script>
function toggleRadio() { // will activate when the form will change.
var radio1 = document.getElementById('radio1'); // radio 1
var radio2 = document.getElementById('radio2'); // radio 2
if (radio1.checked == true) { // if the first checked display input and hide select
document.getElementById('textLabel').style.display = 'block';
document.getElementById('selectLabel').style.display = 'none';
document.getElementById('selectin').selectedIndex = 0; // clear selected option
} else { // because you got only 2 option you don't have to use another condition
document.getElementById('textLabel').style.display = 'none';
document.getElementById('selectLabel').style.display = 'block';
document.getElementById('textin').value = ''; // clear input
}
}
toggleRadio(); // call the function
</script>
</body>
</html>

Make a multiselect form

I have this select form to add in my database countries.
https://jsfiddle.net/Da4m3/394/
I want to change this form into this:
this is html code:
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_0" name="members_create_campaign_form[countrySelectionType]" required="required" value="0" checked="checked" /> All</label>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_1" name="members_create_campaign_form[countrySelectionType]" required="required" value="1" /> Selected</label>
<div id="clist_div" class="simplebox cgrid540-right" style="display:none;">
<div style="padding:5px"></div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Excluded Countries</b></p>
<select size="10" name="excludedcountries" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['excludedcountries'],this.form['members_create_campaign_form[countries][]'])" multiple >
<option value='97'>Afghanistan</option>
<option value='191'>Aland Islands</option>
<option value='105'>Albania</option>
<option value='114'>Algeria</option>
</select>
</div>
<div class="simplebox cgrid40-left">
<input class="button-blue" type="button" name="right" value=">>" onclick="moveSelectedOptions(this.form['excludedcountries'],this.form['members_create_campaign_form[countries][]'])"><br/><br/>
<input class="button-blue" type="button" name="left" value="<<" onclick="moveSelectedOptions(this.form['members_create_campaign_form[countries][]'],this.form['excludedcountries'])">
</div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Selected Countries</b></p>
<select size="10" id="members_create_campaign_form_countries" name="members_create_campaign_form[countries][]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['members_create_campaign_form[countries][]'],this.form['excludedcountries'])" multiple >
</select>
and with this js:
$(document).ready(function () {
if ($('#members_create_campaign_form_countrySelectionType_1').is(':checked')) {
$('#clist_div').show('slow');
}
$('#members_create_campaign_form_countrySelectionType_0').click(function () {
$('#clist_div').hide('slow');
});
$('#members_create_campaign_form_countrySelectionType_1').click(function () {
$('#clist_div').show('slow');
});
selectDiff('clist_div', 'members_create_campaign_form_countries');
});
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
function SelectAllList(CONTROL){
for(var i = 0;i < CONTROL.length;i++){
CONTROL.options[i].selected = true;
}
}
function hasOptions(obj) {
if (obj!=null && obj.options!=null) {
return true;
}
return false;
}
function moveSelectedOptions(from,to) {
if (!hasOptions(from)) { return; }
for (var i=0; i<from.options.length; i++) {
var o = from.options[i];
if (o.selected) {
if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
to.options[index] = new Option( o.text, o.value, false, false);
}
}
// Delete them from original
for (var i=(from.options.length-1); i>=0; i--) {
var o = from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
if ((arguments.length<3) || (arguments[2]==true)) {
sortSelect(from);
sortSelect(to);
}
from.selectedIndex = -1;
to.selectedIndex = -1;
}
how i can do that? i have tried but all time don't insert in to my database!
Is from this value allTarget that put me all, and this value countries[] for multiselect, i don't know where and how i can put this values.
I have do some modifications and i have this code that when i select from left side is working, is adding to my database but when i push options to right side is not adding in database.
<div class="st-form-line">
<span class="st-labeltext">Countries</span>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_0" name="www" required="required" value="0" checked="checked" /> All</label>
<label class="margin-right10"><input type="radio" id="members_create_campaign_form_countrySelectionType_1" name="www" required="required" value="1"/> Selected</label>
<div id="clist_div" class="simplebox cgrid540-right" style="display:none;">
<div style="padding:5px"></div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Excluded Countries</b></p>
<select size="10" name="countries[]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form['countries[]'],this.form['countries[]'])" multiple >
<?php foreach($arrayCountries as $country) {?>
<option value="<?= $country ?>" ><?= $country ?></option>
<?php } ?>
</select>
</div>
<div class="simplebox cgrid40-left">
<input class="button-blue" type="button" name="right" value=">>" onclick="moveSelectedOptions(this.form['countries[]'],this.form['countries[]'])"><br/><br/>
<input class="button-blue" type="button" name="left" value="<<" onclick="moveSelectedOptions(this.form['[countries[]'],this.form['countries[]'])">
</div>
<div class="simplebox cgrid200-left">
<p style="text-align:center;"><b>Selected Countries</b></p>
<select size="10" id="members_create_campaign_form_countries" name="countries[]" style="width:200px; height:160px;" onDblClick="moveSelectedOptions(this.form ['countries[]'],this.form['countries[]'])" multiple >
</select>
</div>
</div>
<div class="clear"></div>
</div>
Quickly coded, but is this what you're looking for?
https://jsfiddle.net/Da4m3/398/
(didn't bother to write the css)
The magic happens in the js code
s = $('#selected');
n = $('#not-selected');
l = $('#left');
r = $('#right');
l.on('click', function() {
move = s.find('option:checked');
move.attr('selected', false);
n.append(move);
});
r.on('click', function() {
move = n.find('option:checked');
move.attr('selected', false);
s.append(move);
});

Do not repeat yourself best practices showing and hiding fields

I am trying to figure out the best way to show and hide fields that are being reused. Cleaning up the code so that I do not repeat myself "DRY". Will someone please assist me in the best practices of doing so?
What I have is a select that allows the user to choose from two different reports.
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreport" value="checklistreport" >Checklist Stats</option>
<option id ="locationreport" value="locationreport" >Location Stats</option>
</select>
Then each report have a lot of similar fields. How can I have them use the same fields but hide/show the differences and go to the correct form "action" based which report is chosen.
Location Report
<form name="generatereport" method="post" action="_location_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
</script>
Checklist Report
<form name="generatereport" method="post" action="_checklists_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="8">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="7" readonly></textarea>
<br /><br />
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="8">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="7" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Many of these fields are the same is there a way i can just have one set and show them if either option is chosen and not have two different sets?
This is what I have tried:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
<script>
$(document).on('change', '#reporttype', function() {
var value = $(this).val();
//var checklistreport = $("#checklistreport");
//var locationreport = $("#locationreport");
var location = $("#location");
var employeelist = $("#employeelist");
var chosendates = $("#chosendates");
var formattype = $("#formattype");
var submitbtn = $("#submitbtn");
if (value == "checklistreports") {
//checklistreport.show();
//locationreport.hide();
location.show();
employeelist.show();
chosendates.show();
formattype.show();
submitbtn.show();
} else if (value == "locationreports") {
//checklistreport.hide();
//locationreport.show();
location.show();
employeelist.hide();
chosendates.show();
formattype.show();
submitbtn.show();
} else {
//checklistreport.hide();
//locationreport.hide();
location.hide();
employeelist.hide();
chosendates.hide();
formattype.hide();
submitbtn.hide();
}
});
</script>
<br /><br />
<!--<div id="locationreport" style="display: none;">-->
<form name="generatereport" method="post" action="_location_queries.cfm">
<!--<div id="checklistreport" style="display: none;">-->
<form name="generatereport" method="post" action="_checklists_queries.cfm">
</form>
<div id="location" style="display: none;">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="employeelist" style="display: none;">
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="9">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="chosendates" style="display: none;">
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
</div>
<br /><br />
<div id="formattype" style="display: none;">
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
</div>
<br /><br />
<div id="submitbtn" style="display: none;">
<input type="submit" name="submit" value="Continue" />
</div>
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Not sure how I choose which action for the form. Depending on which report is chosen.
https://jsfiddle.net/bobrierton/o2gxgz9r/10018/
You have a few options here:
Option #1:
Always show the "common" inputs, and only hide the inputs that are conditional upon selection, that way your code is cleaner because you only have to manage the conditional elements (not all of them as you are doing now)
Option #2:
Use CF includes to hold your "common" elements, and "conditional" elements, combining them where necessary to build the correct list.
Option #3:
Use JavaScript to hold your "common" elements, and "conditional" elements, and render the composed list based on your conditions.
var location = $('select[name=Location]');
// This lists could hold anything you want, jQuery elements
// references, strings, etc.
var lists = {
common: ['a', 'b', 'c'],
locationreports: ['location #1', 'location #2'],
checklistreports: ['checklist #1', 'checklist #2']
};
$('#reporttype').on('change', function() {
var value = $(this).val();
// Grab a copy of the common list to begin with
var options = [].concat(lists.common);
// Now combine the conditional options
if (value === "checklistreports" || value === "locationreports") {
options = options.concat(lists[value]);
}
// Now you have a complete list of options to show based
// your conditions, so now you can just show them all, or
// do whatever you want with this new list.
location.empty();
options.forEach(function($element) {
// Do something with the list
location.append('<option value="' + $element + '">' + $element + '</option>');
})
There are lots of other options, but between using and combining includes, or composing objects together you should be able to customize a nice DRY workflow.

Input Field is not enabled after changing Select option

I have created a stand alone code for enabling/disabling input field and it is working perfectly .
HTML:
Identification Type:
<select name="Identification-Type" id="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="23434">--sfgdg--</option>
<option value="135111">--dfgb--</option>
<option value="1165611">--gdg--</option>
<option value="114511">--vcbc--</option>
</select>
<!-- <input type="checkbox" class="Identification-Number" value="Identification-Number"
name="Identification-number" id="Identification-Number"> -->
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number" id="Identification-Number">
JS:
$('select[name="Identification-Type"]').change(function () {
var $this = $('#Identification-Number');
$this.attr("disabled", false);
$this.attr("disabled", ($(this).val() == '1111') ? true : false);
}).trigger('change');
JSFIDDLE LINK
But,when I tried to incorporate this logic in another form, it is not working .
HTML:
<form name="pancettaForm" method="post" action="demor" id="pancettaForm">
<ul>
<li>
<label for="PartyChoose">Choose Appropriate Party:</label>
</li>
<br>
<input id="person" name="PartyChoose" type="radio" value="update-person" class="required" />Person
<br />
<input id="organization" name="PartyChoose" type="radio" value="update-organization" class="required" />Organization
<br />
<li id="Family-Name" style="display: none;">
<input type="checkbox" class="Family-Name" value="Family-name" name="Family-name">
<label for="Family-Name"><em>*</em>Family Name:</label>
<input type="text" name="Family-Name" class="required">
</li>
<li id="Organization-Name" style="display: none;">
<inpname="Organization-name">
<label for="Organization-Name"><em>*</em>Organization Name:</label>
<input type="text" name="Organization-Name" class="required">
</li>
<div class="extraPersonTemplate">
<div class="controls-row">
<li id="Identification-Type" style="display: none;">Identification Type:
<select name="Identification-Type" class="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="1">--sdsd--</option>
<option value="2">--cxc--</option>
<option value="3">--cvcv--</option>
<select> <a id="Identification-Number" style="display: none;">
<input type="hidden" class="Identification-Number">
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number">
</a>
</li>
</div>
</div>
<div id="container"></div>
<a href="#" id="addRow" style="display: none;"><i class="icon-plus-sign icon-white">
</i> Add Identifier</a>
<li id="Adminsys-Type" style="display: none;">Admin System Type:
<select name="Adminsys-Type" class="Adminsys-Type">
<label for="Adminsys-Type">Admin Type:</label>
<option value="0">--Select--</option>
</select>
</li>
<li id="Adminsys-Number" style="display: none;">
<input type="checkbox" class="Adminsys-Number" value="Adminsys-Number" name="Adminsys-number">
<label for="Adminsys-Number"><em>*</em>Admin System Value:</label>
<input type="text" name=Adminsys-Number>
</li>
</ul>
<input type="submit" id="button" name="submit" value="Search">
</form>
JS:
$(document).ready(function () {
var counter = 0;
$('input[name=Organization-Name]').attr('disabled', true);
$('input[name=Identification-Number]').attr('disabled', true);
$('input[name=Family-Name]').attr('disabled', true);
$('input[name=Adminsys-Number]').attr('disabled', true);
$('#pancettaForm').change(function () {
$('.Organization-Name').click(function () {
if ($('.Organization-Name').is(':checked')) {
$('input[name=Organization-Name]').val('').attr('disabled', false);
} else {
$('input[name=Organization-Name]').attr('disabled', true);
}
});
$('select[name="Identification-Type' + counter + '"]').change(function () {
var $this = $('.Identification-Number');
var $input = $this.siblings('input[type=text]');
$input.attr("disabled", false);
$input.attr("disabled", ($(this).val() == '1111') ? true : false);
});
$('.Adminsys-Number').click(function () {
if ($('.Adminsys-Number').is(':checked')) {
$('input[name=Adminsys-Number]').val('').attr('disabled', false);
} else {
$('input[name=Adminsys-Number]').attr('disabled', true);
}
});
$('.Family-Name').click(function () {
if ($('.Family-Name').is(':checked')) {
$('input[name=Family-Name]').val('').attr('disabled', false);
} else {
$('input[name=Family-Name]').attr('disabled', true);
}
});
$('#Family-Name,#Identification-Number,#Organization-Name').hide();
if ($('#person').prop('checked')) {
$('#Family-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
} else if ($('#organization').prop('checked')) {
$('#Organization-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
}
});
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
$('<div/>', {
'class': 'extraPerson' + counter,
'id': 'extraPerson' + counter,
html: GetHtml() + '</i> Remove Identifier'
}).hide().appendTo('#container').slideDown('slow');
counter++;
});
$("#container").on('click', '.removeRow', function () {
//$("#extraPerson"+counter).remove();
if (counter < 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$(this).parent().remove();
});
function GetHtml() {
// var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
if (counter == 0) {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
counter++;
return $html.html();
} else {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
// $html.find('[id=Identification-Type]')[0].id="Identification-Type" + counter;
// var remove='</i> Remove Identifier';
return $html.html();
}
}
})
JSFIDDLE LINK
How can I dynamically change the name of select attribute so that I can selectively enable and disable input fields in multiple rows.
Hope this will help you a bit and I hope I got it correct:
I reworked you change function which determines the select boxes and enables the input field, like this
$('.Identification-Type').change(function () {
//#Identification-Type input
/** this can be used to count the input fields and use it in a loop later **/
var $inputFields = $('.extraPersonTemplate #Identification-Type input').length;
var $idNumber = $('input[name=Identification-Number]');
var $idNumber0 = $('input[name=Identification-Number0]');
($('select[name=Identification-Type]').val() == '1111') ? $idNumber.attr('disabled', true) : $idNumber.removeAttr('disabled');
($('select[name=Identification-Type0]').val() == '1111') ? $idNumber0.attr('disabled', true) : $idNumber0.removeAttr('disabled')
})
But from my point of view, this is not a the best approach since its not very dynamically.
If you manage to count up the select[name=Identification-Type] + counter not only for one input but for both of them like <input type="text" name="Identification-Number0"> and <input type="text" name="Identification-Number1"> it would be possible to include a loop within in this change function and loop over the $inputFields which are found
http://jsfiddle.net/xKL44/2/ this has helped me in the past... Try it out!
$('#wow').change(function() {
// Remove any previously set values
$('#show_box, #total_box').empty();
var sum = 0,
price;
$(this).find('option:selected').each(function() {
// Check that the attribute exist, so that any unset values won't bother
if ($(this).attr('data-price')) {
price = $(this).data('price');
sum += price;
$('#show_box').append('<h6>' + price + '</h6>');
}
});
$('#total_box').text(sum);
});

Categories

Resources