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!
Related
How would I block form submission if the user presses cancel for confirmation of selecting Doctor.
<form method="post" action="registration.php" autocomplete="off" onsubmit="return validateMyForm();">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="role" id="role">
<option value="Patient">Patient</option>
<option value="Doctor">Doctor</option>
<option value="Nurse" >Nurse</option>
</select>
<input type="submit">
</form>
<script>
$("#role").change(function(){
var val = $(this).val();
switch (val){
case "Doctor":
var d = confirm("Are you a doctor?");
}
});
</script>
To disable the submission of the form you can use return false on the onsubmit attribute of the form.
Since you already have a call to the validateMyForm() function there, you just need to make sure that this function return false:
function validateMyForm() {
....
// do some checks...
return false;
}
If you to prevent the submission of the form based on the answer to your confirm, you should save the answer in some variable that you can use later on:
<script>
var d;
$("#role").change(function(){
var val = $(this).val();
switch (val){
case "Doctor":
d = confirm("Are you a doctor?");
}
});
</script>
And inside the function:
function validateMyForm() {
if (!d) {
return false;
}
}
Your d variable will be false if cancel is pressed, so:
$("#role").change(function(){
let val = $(this).val();
let blockSubmit = false;
if (val == 'Doctor') {
let d = confirm("Are you a doctor?");
blockSubmit = !d;
}
else {
blockSubmit = false
}
$('input[type="submit"]').prop('disabled', blockSubmit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form method="post" action="registration.php" autocomplete="off" onsubmit="return validateMyForm();">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="role" id="role">
<option value="Patient">Patient</option>
<option value="Doctor">Doctor</option>
<option value="Nurse">Nurse</option>
</select>
<input type="submit">
</form>
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();
});
});
I am creating a dynamic HTML form with N number of input fields and their input types also varies. I need to validate all fields before submit the form data to Rest Service in key value format. On form button click i am doing this
var data;
var submit = 0;
var formField = [];
var i = 0;
$('form input').each(function() {
if ($(this).val().length == "0") {
submit = 1;
} else {
formField[i] = $(this).val();
}
i++;
});
if (submit == 0) {
//if submit == 0 submit the form
data = {"credentialFields[0].value" : formField[0],
"credentialFields[1].value" : formField[1],
"credentialFields[2].value" : formField[2],
};
There i have problem like i am not able to use HTML5 native validation because i am not using button type="submit" and i am not able to validate input types like radio, checkbox and select. please suggest me the best solution for this problem.
<form id="myForm" method="POST">
<textarea name='area2' required>some textarea</textarea>
<input type='text' name='text1' required />
<input type='text' name='text2' value='some text' required />
<input type='radio' name='radio' value='radio1' required/>
<input type='radio' name='radio' value='radio2' required/>
<input type='checkbox' name='checkbox1' value='checkbox1' required/>
<input type='checkbox' name='checkbox2' value='checkbox2' required />
<select required>
<option value='option1'>option one</option>
<option value='option2' selected='selected'>option two</option>
</select>
<button type="submit">submit</button>
</form>
<script>
var data={};
$('#myForm').submit(function(event){
// cancels the form submission if it's invalid
event.preventDefault();
var inputs = $('#myForm').find(':checked,:selected,:text,textarea').filter(function() {
return $.trim( this.value ) != '';
});
var formField = inputs.map(function(){
return this.value;
}).get();
$.each(formField, function( index, value ) {
data['credentialFields['+index+'].value']=value;
});$.ajax({ type : "POST",
url : "restUrl",
data : data
});
});
</script>
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();
});
}
}
I had this JavaScript running for a while but I altered it a slight bit and now I cant get it to even run. I had an alert in the JavaScript for a while and I couldn't even get that to trigger. There is some PHP above this code but it shouldn't interfere with the JavaScript.
<form action="http://go.gbpi.net/Outage/add-question/" method="post">
Question Name (A descriptive name for the question. Example: "Phone number", or "Pizza Size"): <br /><input type="text" name="questionName" />
<?php
echo("Category: <br /><select name=\"category\" id=\"category\">");
$mysqli = db_init();
$mysqli->next_result();
$cats = $mysqli->query("call GetActiveCategories()");
while ($row = $cats->fetch_assoc()){
$categori = $row['Category_Text'];
if(!($categori == $category)){
echo("<option value = \"".$categori."\">".$categori."</option>");}
}
echo("</select>");
?>
Question Text:<br /><input type="text" name="questionText" style='width:80%' />
Question Type:<br /><select name="myList" id="myList" onchange="selectType(); return false;">
<option value = "1">Yes or No</option>
<option value = "2">Multiple Choice</option>
<option value = "3">Multiple Select</option>
<option value = "4">Open Response</option>
<option value = "5">Final Reply</option>
<option value = "6">Summary</option>
</select>
<div id='regexes'>
type of input: <br /><select name="regex" id="regex">
<option value = "-1">any input</option>
<?php
$mysqli->next_result();
$regexes = $mysqli->query("call GetValidRegexes()");
while($regex_row = $regexes->fetch_assoc()){
$rid = $regex_row['Validation_ID'];
$rname = $regex_row['Validation_Name'];
echo("<option value = \"".$rid."\">".$rname."</option>");
}
?>
</select>
</div>
<div id='buttons'></div>
<button id="adda" onclick="addAnswer(); return false;">add answer (max: 10)</button>
<input type="submit" value="add question" />
</form>
<?php
echo("<a href='./define-relationships/'>Define Question Relationships</a><br />");
?>
<script type="text/javascript">
document.getElementById("adda").style.visibility="hidden";
</script>
<script type="text/javascript">
var answers = 0;
var inHTML = "";
function addAnswer()
{
if(answers < 10){
write = document.getElementById('buttons');
write.innerHTML = write.innerHTML + "answer: <input type=\"text\" name=\"answer" + answers + "\" /> <br>";
answers = answers + 1;}
}
</script>
<script type="text/javascript">
function selectType()
{
alert("HAHA I HATE YOU!");
var type=document.getElementById("myList").value;
if(type == "2" || type == "3"){
document.getElementById("buttons").style.visibility="visible";
document.getElementById("adda").style.visibility="visible";
document.getElementById("regexes").style.visibility="hidden";
}
else if(type == "4"{
document.getElementById("buttons").style.visibility="hidden";
document.getElementById("adda").style.visibility="hidden";
document.getElementById("regexes").style.visibility="visible";
}
else{
document.getElementById("buttons").style.visibility="hidden";
document.getElementById("adda").style.visibility="hidden";
document.getElementById("regexes").style.visibility="hidden";
}}
</script>
Without a jsfiddle it's hard to know for sure if this is the problem, but you have a syntax error in the last script on the page.
else if(type == "4"{
Add the closing paren and see if that helps.