Select Statement to loop through another javascript - javascript

Okay So I have a select statement that needs to populate a loop in a javascript. I have very very basic knowledge of JS. I have some very basic coldfusion here that I am using. Problem is one is client side and the other server-side.
I need the first select statement to loop through where my cfloop is inside the javascript. I need to somehow change that to a javascript loop (where it says $(document).ready(function(){). I don't know how. Can anyone help?
<cfoutput>
<script type='text/javascript' src='/jquery-1.8.2.js'></script>
<script type="text/javascript">
function changeHiddenInput (objDropDown)
{
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
}
</script>
</head>
<body>
<cfquery name="Types" datasource="DSN">
SELECT Taking.*, Type.*
FROM Taking
INNER JOIN Type ON Taking.Taking_TypeID = Type.Type_ID
ORDER BY Type_ID
</cfquery>
<form>How many to change?
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<cfloop index="ABC" from="1" to="12" step="1">
<option value="#ABC#">#ABC#</option>
</cfloop>
</select>
<input type="text" name="hiddenInput" id="hiddenInput" value="" />
</form>
<br>
<br>
<cfset Changing=4>
<script type="text/javascript">
$(document).ready(function(){
<cfloop index="I" from="1" to="#Changing#" step="1">
$('.box#I#').hide();
$('##dropdown#I#').change(function() {
$('.box#I#').hide();
$('##div' + $(this).val()).show();
});
</cfloop>
});
</script>
<form>
<cfloop index="J" from="1" to="#Changing#" step="1">
<select id="dropdown#J#" name="dropdown#J#">
<option value="0">Choose</option>
<cfloop query="Types" startrow="1" endrow="#Types.recordcount#">
<option value="area#J##Type_ID#">Change over #Type_Name#</option>
</cfloop>
</select>
<br>
<cfloop query="Types" startrow="1" endrow="#Types.recordcount#">
<div id="divarea#J##Type_ID#" class="box#J#">
<cfquery name="GetQuestions" datasource="DSN">
SELECT Questions.*
FROM Questions
WHERE Questions_OrgID=1
AND Questions_TypeID=#Types.Type_ID#
ORDER BY Questions_Rank
</cfquery>
<cfloop query="GetQuestions">
#Questions_Question#<br>
</cfloop>
</div>
</cfloop>
<br>
<br>
</cfloop>
</form>
</cfoutput>

I'm not entirely sure what you're trying to do. However you could turn something like this:
$(document).ready(function(){
<cfloop index="I" from="1" to="#Changing#" step="1">
$('.box#I#').hide();
$('##dropdown#I#').change(function() {
$('.box#I#').hide();
$('##div' + $(this).val()).show();
});
</cfloop>
});
Into something like:
$(document).ready(function(){
for (var i = 1; i <= #Changing#; i++)
{
$('.box' + i).hide();
$('##dropdown' + i).change(function() {
$('.box' + i).hide();
$('##div' + $(this).val()).show();
});
}
});
Update: in fact it sounds like it's entirely a JS solution?
function changeHiddenInput (objDropDown) {
for (var i = 1; i <= objDropDown.value; i++)
{
$('.box' + i).hide();
$('##dropdown' + i).change(function() {
$('.box' + i).hide();
$('##div' + $(this).val()).show();
});
}
}

Related

How to find dynamically created element using jQuery selectors?

I have a form which has certain elements in it. I want to get all the elements inside the form regardless of their depth.
This is my test code
$(document).ready(function(){
//script.init(markchaining);
$('#checkbutton').click(function(){
$('#saveForm :input').each(function(key){
if($(this).is('select'))
{
var id = $(this).attr('id');
console.log('id is '+id);
$(this).trigger('change');
console.log('if-> Element name is '+$(this).attr('name'));
}
else
{
console.log('else-> Element name is '+$(this).attr('name'));
}
});
});
});
function addRow(ele,name)
{
var id = ele.id;
$('#'+id+'').closest('tr').after('<tr><td class="label-cell">New Row</td><td><input type="text" name="'+name+'" /></td></tr>');
}
My Problem
I also have dynamic elements which will be created on certain select change events during the iteration. I want to get these dynamically created elements as I iterate through my form.
I am not able to access the "New Row" element which gets created dynamically on clicking the 'check' button
This is my complete test code
Just added a count variable to distinguish the names on console. https://jsfiddle.net/ztpjacyu/
$(document).ready(function() {
//script.init(markchaining);
$('#checkbutton').click(function() {
$('#saveForm :input').each(function(key) {
if ($(this).is('select')) {
var id = $(this).attr('id');
console.log('id is ' + id);
$(this).trigger('change');
console.log('if-> Element name is ' + $(this).attr('name'));
} else {
console.log('else-> Element name is ' + $(this).attr('name'));
}
});
});
//Clicked twice to show you the console
$('#checkbutton').click();
$('#checkbutton').click();
});
var count = 0;
function addRow(ele, name) {
var id = ele.id;
$('#' + id + '').closest('tr').after('<tr><td class="label-cell">New Row</td><td><input type="text" name="' + name + ++count + '" /></td></tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="mainform" id="saveForm" action="#">
<!--##GENERAL##-->
<input type="button" name="checkbutton" id="checkbutton" value="Check" /> <- Moved here so that you can see the console
<div id="fromuser">
<table width="100%" id="userTable">
<tr id="ReportNameRow">
<td class="label-cell">Report Name :</td>
<td>
<input type="text" name="CustomReportName" id="CustomReportName" />
</td>
</tr>
<tr id="ReportNamrRow">
<td class="label-cell">* Saved Report Name :</td>
<td>
<select name="rname" id="rname" onChange="addRow(this,'MYID');">
<option value="">---Select---</option>
<option value="Cash_Position">Cash Position</option>
<option value="Detail_Report">Detail Report</option>
<option value="FCCS/FBPS_Detail_Report">FCCS/FBPS Detail Report</option>
<option value="Reconciliation_Report">Reconciliation Report</option>
<option value="Statement_Report">Statement Report</option>
<option value="CustomReport">Enter Custom Report Name</option>
</select>
</td>
</tr>
<input type="hidden" name="hiddenid" value="I am hidden" id="hiddenid" />
<tr id="submit">
<td class="label-cell"></td>
<td>
<input type="submit" name="submitbutton" id="submitbutton" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
Update
if you want the element to be there before you execute your each , you can do this : https://jsfiddle.net/jbrt3Led/
$('#checkbutton').click(function() {
$("#rname").trigger('change');
$('#saveForm :input').each(function(key) {
if ($(this).is('select')) {
var id = $(this).attr('id');
console.log('id is ' + id);
console.log('if-> Element name is ' + $(this).attr('name'));
} else {
console.log('else-> Element name is ' + $(this).attr('name'));
}
});
});

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!

Jquery forms with adaptive table from selector

I need your help. Trying to build form in php + jquery, and have trouble with some functionality.
For example, I have this code:
<form action="" method="post" id="multiform">
<!-- Product selector -->
<table class="multi" id="MultiRow">
<tr><td>
<select name="store[product][]" required>
<option value="" selected="selected">-Product-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
<option value="19041">TRAVEL</option>
<option value="19063">HOUSEHOLD</option>
</select>
</td>
<!-- /Product selector -->
</table>
<input type="submit" value="ok">
How can I do that, If selected value is 430 or 440, then at right side inserts
<td><input type="text" id="motor[]" name="multiarray[vehicle_type][]"></td>
<td><input type="text" id="deadline[]" name="multiarray[end_date][]"></td>
<td><a class="del" href="#">DELETE BUTTON</a></td>
If selected value is 19041 or 19063, then inserts
<td><input type="text" id="location[]" name="multiarray[travel_location][]"></td>
<td><a class="del" href="#">DELETE BUTTON</a></td>
I need that there also will be +Add button and -delete button where i write:
<a class="del" href="#">DELETE BUTTON</a>
But for datepicker functionality I need that id for inputs will be unique, for ex: id="location1" , at next added row id="location2".
JsFiddle
$("#productselect").change(function(){
var select = document.getElementById("productselect");
var selecedproduct = select.options[select.selectedIndex].value;
$("tr[id^='forselect']").remove();
if(selecedproduct==430 || selecedproduct==440 )
{
var html ='<tr id="forselect"><td><input type="text" id="motor[]" name="multiarray[vehicle_type][]"></td>';
html +='<td><input type="text" id="deadline[]" name="multiarray[end_date][]"></td>';
html +='<td><a class="del" OnClick="removetags();return false;" href="#">DELETE BUTTON</a></td></tr>';
html +='<tr id="forselect"><td>add datepicker </td></tr>';
$("#MultiRow").append(html);
}
else if(selecedproduct==19041 || selecedproduct==19063 )
{
var html ='<tr id="forselect"><td><input type="text" id="location[]" name="multiarray[travel_location][]"></td>';
html +=' <td><a class="del" OnClick="removetags();return false;" href="#">DELETE BUTTON</a></td></tr>';
html +='<tr id="forselect"><td>add datepicker </td></tr>';
$("#MultiRow").append(html);
}
});
deldatepicker = function deldatepicker(id)
{
$("#remove"+id).remove();
}
adddatepicker = function adddatepicker()
{
var N = $("input[id^='location']").length;N++;
var html ='<tr id="remove'+N+'"><td><input type="text"id="location'+N+'" placeholder="date"></td><td><button OnClick="deldatepicker('+N+')">delete datepicker </button> </td></tr>';
$("#MultiRow").append(html);
$("#location"+N).datepicker();
}
removetags = function removetags()
{
$("tr[id^='forselect']").remove();
}
It may help you for you work.
Here it is.
Since you need the ids to be unique I have used Date.now() and then object.now.getUTCMilliseconds(). That will ensure that event when you delete and reinsert another row with same rowIndex it will not crash. Then the rest is trivial!
jQuery(document).ready(function(){
jQuery('select').on('change', function(e){
var tr = jQuery(this).closest('tr').get(0);
var cell = tr.insertCell(1);
var now = Date.now();
switch(jQuery('option:selected', this).val()){
case '430':
case '440':
cell.innerHTML = "<td><input type='text' id='motor[]' name='multiarray[vehicle_type][]'></td><td><input type='text' id='deadline[]' name='multiarray[end_date][]'></td><td><a class='del' href='#'>DELETE BUTTON</a></td><td><a class='del' href='#'>DELETE BUTTON</a></td>";
break;
cell.innerHTMl = "<td><input type='text' id='location"+now.getUTCMilliseconds()+"[]' name='multiarray[travel_location][]'></td><td><a class='del' href='#'>DELETE BUTTON</a></td><td><a class='del' href='#'>DELETE BUTTON</a></td>";
case '19041':
case '19063':
break;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="" method="post" id="multiform">
<!-- Product selector -->
<table class="multi" id="MultiRow">
<tr><td>
<select name="store[product][]" required>
<option value="" selected="selected">-Product-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
<option value="19041">TRAVEL</option>
<option value="19063">HOUSEHOLD</option>
</select>
</td>
<!-- /Product selector -->
</table>
<input type="submit" value="ok">

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

ColdFusion jQuery validation plugin + captcha

I have functioning jQuery validation code but I am trying to add a captcha. I think the validation is set correctly but the captchacheck.cfm page is set up wrong.
HTML page:
<script>
$(document).ready(function() {
$("#captchaDiv").load("captcha-show.cfm");
$("#reloadLink").click(function(e) {
$("#captchaDiv").load("captcha-show.cfm");
e.preventDefault();
});
})
</script>
<!--end refresh captcha-->
<script type="text/javascript">
$.validator.setDefaults({
submitHandler: function() {
// alert("submitted!");
$("#signupForm").submit();
}
});
$().ready(function() {
$("#signupForm").validate({
rules: {
cap: {
required: true,
remote: "captchacheck.cfm"
},
messages: {
cap: "captcha does not match"
}
}});
});
</script>
<!--the form-->
<form ....>
<div class="name-field">
<!--- Use the randomly generated text string for the CAPTCHA image. --->
<div id="captchaDiv"></div>
</div>
<div class="name-field">please type what you see:</div>
<div class="name-field">
<input id="cap" type="text" name="cap" placeholder="enter captcha"/>
</div>
<div class="ppnw"> Can't read? Reload
</div>
<div class="formbut1">
<input class="button" type="submit" name="submit" id="subsales" value="Submit" />
</div>
</fieldset>
</form>
Here is the remote page (captchacheck.cfm):
<cfsetting enablecfoutputonly="true">
<cfif cap eq session.captcha>
<cfset answer = TRUE>
<cfoutput> #answer#</cfoutput>
<cfelse>
<cfset answer = FALSE>
<cfoutput> #answer#</cfoutput>
</cfif>
Here is the page that generates the captcha image:
<cffunction name="makeRandomString" returnType="string" output="false">
<cfset var chars = "23456789ABCDEFGHJKMNPQRS">
<cfset var length = 5> <!---randRange(4,7)--->
<cfset var result = "">
<cfset var i = "">
<cfset var char = "">
<cfscript>
for(i=1; i <= length; i++) {
char = mid(chars, randRange(1, len(chars)),1);
result&=char;
}
</cfscript>
<cfreturn result>
</cffunction>
<cfset session.captcha = makeRandomString()>
<cfimage action="captcha" text="#session.captcha#" width="300" height="40">
Here is the Working Solution: Simple Javascript Working Example, No Jquery
Captcha-Show.cfm
<cffunction name="makeRandomString" returnType="string" output="false">
<cfset var chars = "23456789ABCDEFGHJKMNPQRS">
<cfset var length = randRange(2,7)>
<cfset var result = "">
<cfset var i = "">
<cfset var char = "">
<cfscript>
for(i=1; i <= length; i++) {
char = mid(chars, randRange(1, len(chars)),1);
result&=char;
}
</cfscript>
<cfreturn result>
</cffunction>
<cfset Session.captchaText = makeRandomString()/>
<cfset captchaimagepath = getdirectoryfrompath(getcurrenttemplatepath()) & 'newcaptcha' & gettickcount() & '.png'>
<cfimage action="captcha" width="192" height="60" text="#session.captchaText#" destination="#captchaimagepath#" difficulty="medium">
<cfcontent reset="yes" type="image/png" file="#captchaimagepath#" deletefile="yes">
Main File where you want to call the Captcha Code:
<div align="left">
<cfoutput><a onClick="verifyCode()"><img src=Captcha-Show.cfm?r=#gettickcount()# id=sessioncaptcha alt=captcha width=192 height=60></a></cfoutput>
</div><br>Click on the Image to reload a New Code!
function verifyCode()
{
document.getElementById('sessioncaptcha').src = 'captcha.cfm?r='+new Date().getTime();
}

Categories