Select decides which form action to open - javascript

I have a form that starts with a select. Based on the choice of that first select (which report is chosen) I need to change the action path of which .cfm the form submits to. Will someone please assist me in how I should do this? I am open to any proper way whether is HTML, ColdFusion or jQuery (Javascript).
So starts with a select:
<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>
If #checklistreports is chosen the form should be
<form name="generatereport" method="post" action="_checklists_queries.cfm">
But if #locationreports is chosen the form should be
<form name="generatereport" method="post" action="_location_queries.cfm">
Any help with this would be greatly appreciated.
I was trying to do in IF statement in CF but it has me stuck unfortunately with no results.

You can use a .change handler to change the action attribute of the form.
$("#reporttype").change(function() {
if ($(this).val() == "checklistreports") {
$("form[name=generatereport]").attr("action", "_checklists_queries.cfm");
} else {
$("form[name=generaterport]").attr("action", "_location_queries.cfm");
}
});

I would recommend to just indicate the action values of the form in the values of the options.
$('#reporttype').change(function(){
form_action = $(this).val();
$('form').attr('action', form_action);
$('span').text(form_action);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="_checklists_queries.cfm" >Checklist Stats</option>
<option value="_location_queries.cfm" >Location Stats</option>
</select>
<form name="generatereport" method="POST" action="#">
<p>This forms action value is <span>#</span></p>
</form>

You could always do it all with ColdFusion. It's so much simpler. Here is one approach.
formPage
<form action = "action.cfm" method="post">
<select name="pageToInclude">
<option value="locationQueries.cfm">Location</option>
rest of form.
action.cfm
<cfinclude template = "#form.pageToInclude#">

You already have an accepted answer, but I would like to propose a slightly cleaner solution to the answer you selected, as well as an alternative:
Option #1 (Inline and Clean):
// Cache the selector for better reuse.
var form = $("form[name=generatereport]");
$("#reporttype").change(function() {
var action = $(this).val() === 'checklistreports' ? '_checklists_queries.cfm' : '_location_queries.cfm';
form.attr('action', action);
});
The above option is just a more compact version of the answer you selected, but utilizes selector caching, which is good for performance.
Option #2 ('Global' Config Options):
// Cache the selector
var form = $('form[name=generatereport]');
// Now you can define the variable states for your app.
var config = {
checklistreports: {
action: '_checklists_queries.cfm'
},
locationreports: {
action: '_location_queries.cfm'
}
};
// Updating is trivial
$('#reporttype').change(function() {
var selected = $(this).val();
form.attr('action', config[selected].action);
});
This option is interesting because it lets you define all the different "states" for your components in one place, which is nice for readability and maintenance, and it makes the actual updating of components as simple as looking up the values it should have.

If the forms contains differents elements, you could hide the forms with css and with an onchange handler on the select unhide the right form.
html:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="checklistreports" >Checklist Stats</option>
<option value="locationreports" >Location Stats</option>
</select>
<form method="post" action="_location_queries.cfm" id="locationreports" style="display: none;">
<input type="text" name="location" placeholder="location">
</form>
<form method="post" action="_checklists_queries.cfm" id="checklistreports" style="display: none;">
<input type="text" name="location" placeholder="checklist">
</form>
js:
var locationReport = document.getElementById("locationreports");
var checklistReport = document.getElementById("checklistreports");
function onChangeForm(e) {
if (e.target.value === "locationreports") {
locationReport.style.display = "block";
checklistReport.style.display = 'none';
} else {
checklistReport.style.display = "block";
locationReport.style.display = "none";
}
}
document.getElementById("reporttype").onchange = onChangeForm;
jsfiddle example

Related

How to enable disable text input while making my function modular

Here is my script, what my goal is if other is selected in select, the other text input beside it will be enabled, this is what i've got so far, any approach will be really appreciated, I have 4 questions like this and I want it to be modular, best approach for doing my function to be reuseable.. How do I properly do this without any problem posting my data as 2 name inputs will generate 2 post variables in php.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
This method is reusable and pretty straight forward. Using data attributes, you could specify the element that needs to be shown on the specific option element. Also before showing any input element hide the elements that were attributed to the previous selection.
Example:
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
Your selectedOpt should be an object if you're using multiple selects on the same page and then just add the element to the object with the id as an index:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');

JavaScript Validation for Listbox when mulitple values are selected

I want to do JavaScript validation for listbox
If Value from Lisbox is not selected, it should get alert "Please Select Your Skill"
But if user select 3 Skill from 6 Skill. I need that 3 skiils should get alert using JavaScript.
Here is my Code...
call script on submit button..
<html>
<head>
<script></script>
</head>
<body>
<form name="registration" id="registration_form_id" action="" method="post">
<select id="skillid1" name="skill[]" multiple="multiple" size="3" >
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit" onClick="myFunction()">Submit</button>
</form>
</body>
</html>
Thank you
Rahul
First of all use onsubmit form event instead of button click. In this case you return false when the form should not be submitted. Here is an example:
function myFunction(form) {
var select = form['skill[]'];
// Check if skill is selected
if (select.selectedIndex === -1) {
alert("Please Select Your Skill");
return false;
}
// Check if selected 3 skills out of 6
if (select.selectedOptions.length) {
var options = [].map.call(select.selectedOptions, function(option) {
return option.text;
}).join('\n');
alert("You selected: \n" + options);
return true;
}
return false;
}
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<select id="skillid1" name="skill[]" multiple="multiple" size="3">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit">Submit</button>
</form>
Note that returning true from event handler will submit the form (in above demo submission is suppressed).
Here is JSFiddle demo.
To get the selected options from a multiple select, you should iterate over the options collection and collect the ones that are selected.
There is also the selectedOptions collection (per dfsq's answer), but support is patchy across browsers.
The looping method is made easier with a simple toArray function:
// Return an array of list members in numeric index order
// Respect sparse lists.
function toArray(list) {
var array = [];
// Use for loop for maximum compatibility
for (var i=0, iLen=list.length; i<iLen; i++) {
// Respect sparse lists
if (list.hasOwnProperty(i)) {
array[i] = list[i];
}
}
return array;
}
So if you have a reference to the select element, you can get the selected options using:
var selectedOptions = toArray(select.options).filter(function(option) {
return option.selected;
});
Now you can show the displayed text of each option in an alert using:
alert(selectedOptions.map(function(option){return option.text}).join('\n'));

JavaScript to set datalist by <input list="value"> for HTML5 on input/selection of value in another form

I am creating my first Web Form and I'm looking for a little help getting this JavaScript Function to work for me.
I am trying to use a JavaScript function to specify which datalist to use for a form input list=" " based on the selected value of a separate form. As you can see below I have supplied the first form (which I intend to 'fire' the JavaScript and input the variable) and the second form which should have the input list=" " value set by the script. In the first form I have used two different events simply to figure out which is the appropriate: onselect= and onchange=.
I greatly appreciate any help or comments.
Here is my code, I have approached this quite a few different ways and at this point it exists as:
<form>
Tendon Type: <input list="tendontype">
<datalist id="tendontype">
<option value="Cantilever" onselect="locationScript('ct')">
<option value="Drape" onchange="locationScript('ut')">
<option value="Span">
</datalist>
</form>
<form name="location">
Location: <input id="loc229" list="need js to insert here"><br />
<datalist id="pier">
<option value="Pier EN-1">
<option value="Pier EN-2">
</datalist>
<datalist id="unit">
<option value="Unit EN-2">
<option value="Unit EN-3">
</datalist>
<datalist id="span">
<option value="Span EN-1">
<option value="Span EN-2">
</datalist>
</form>
<script>
function locationScript(x) {
var locationlist;
if (x == 'ct') {
locationlist = setAttribute("list","pier")
} else {
if (x == 'ut') {
locationlist = setAttribute("list","unit")
} else {
locationlist = setAttribute("list","span")
}
}
document.getElementById("loc229").locationlist;
}
</script>

Populating the form bases on a dropdown box

I am building a tool which on a selection of a value from a dropdown box populates the other fields.So if suppose (a) is selected fileds 2 3 and 4 are displayed in a form but if(b) is selected fields 2 3 4 as well as additional fields 5 and 6 are added as well.Right now I am working around a way to have two forms one with fields 2 3 and 4 and other with 2 3 4 5 and 6.Depending on selection of values from dropdown list(a or b) either forms are shown/hidden.
But it doesn't do as expected.
The html is
<html>
<head>
<title>My Page</title>
</head>
<body>
<center><h1>URL Builder</h1></center>
<div align="center">
<select id ="Type1" name="Aoldropdown">
<option value="Fixed">Fixed Ad Units</option>
<option value="Scrolled">Scrolled Ad Units</option>
<option value="Custom">Custom Ad Units</option>
</select>
<form name="Aolform" id ="aol1" action="/URLBuilder/URLRetriever" method="GET">
<select name="Sizedropdown">
<option value="300x1050">300x1050</option>
<option value="300x600">300x600</option>
<option value="300x250">300x250</option>
<option value="728x90">728x90</option>
<option value="970x250">970x250</option>
<option value="320x50">320x50</option>
<option value="768x90">768x90</option>
<option value="1024x90">1024x90</option>
</select>
<br></br>
Base URL:<input type="text" name="baseURL"><br>
Title Number:<input type="text" name="titleNo"><br>
Placement ID: <input type="text" name="placementId"><br>
Flight ID: <input type="text" name="flightId"><br>
<input type="submit" value="Retrieve URL">
<!-- input type = "submit" Value ="Select URL Type"-->
</div>
</form>
<form name="Aolform2" id ="aol2" action="/URLBuilder/URLRetriever" method="GET">
<select name="Sizedropdown">
<option value="300x1050">300x1050</option>
<option value="300x600">300x600</option>
<option value="300x250">300x250</option>
<option value="728x90">728x90</option>
<option value="970x250">970x250</option>
<option value="320x50">320x50</option>
<option value="768x90">768x90</option>
<option value="1024x90">1024x90</option>
</select>
<br></br>
Placement ID: <input type="text" name="placementId"><br>
Flight ID: <input type="text" name="flightId"><br>
<input type="submit" value="Retrieve URL">
<!-- input type = "submit" Value ="Select URL Type"-->
</div>
</form>
<script type ="text/javascript">
var forms = document.forms['Aolform'];
//console.log(forms);
//console.log(forms.elements);
document.getElementById("Type1").addEventListener("onchange",onDropDownChange,true);
if(document.getElementById("Type1").value =='Custom'){
document.getElementById('aol1').style.visiblity='visible';
document.getElementById('aol2').style.visibility='hidden';
}
else
{
document.getElementById('aol2').style.visibility='visible';
document.getElementById('aol1').style.visibility='hidden';
}
</script>
</body>
</html>
Please help me fix this.
IS THERE ANY OTHER WAY I CAN DO IT.
Thanks
Swaraj
Check out this fiddle. I made a few changes, first instead of onchange just use change. Also you are referencing a non-existent function onDropDownChange(), so I have put your condition inside of that:
function onDropDownChange() {
if (document.getElementById("Type1").value == 'Custom') {
document.getElementById('aol1').style.display = 'none';
document.getElementById('aol2').style.display = 'block';
} else {
document.getElementById('aol2').style.display = 'none';
document.getElementById('aol1').style.display = 'block';
}
}
I also changed the function to use style.display instead of style.visibility so that you don't have a gap above the second form when it displays.
Yes, there are lots of ways to do what you want, but I'm going to give you a straight answer based on what you have done so far. Your script is incorrect because the conditional is not triggered by the event OnChange. Try it like this:
document.getElementById("Type1").onchange = function() {
if(document.getElementById("Type1").value =='Custom'){
document.getElementById('aol1').style.visiblity='visible';
document.getElementById('aol2').style.visibility='hidden';
}
else
{
document.getElementById('aol2').style.visibility='visible';
document.getElementById('aol1').style.visibility='hidden';
}
}
But you should check the behaviour of your "if" condition to see if that's what you really want to do.

Javascript producing a value into a form textbox on selection

Trying to figure out how I can produce text dynamically in a text box of a form using javascript.
I want to select a type of event from a dropdown list which I have made and on that selection a value be input in to the textbox of the form for eventprice.
So far this is what I have but I have no value being produced in the textbox any help appreciated.
function totalprice(){
if($('#type').val() == '3'){
$('#eventprice') == ("45");
}
}
<input type="text" disabled="" id="eventprice" onChange="totalprice();" name="eventprice" class="form-input" />
If you don't mind using jQuery, it is going to be a breeze: you'll simply need to add the data attribute price to every option. What this function does is:
Compares the value of all options to the value currently visible in the select box when the value is changed.
If the values are the same, copies the data-attribute to the other input.
Working demo: http://jsbin.com/acuyux/6/edit
The HTML
<select id="type">
<option data-price="25">Party</option>
<option data-price="35">Meeting</option>
<option data-price="45">Lounge</option>
</select>
<input type="text" id="eventprice" name="eventprice" disabled="" class="form-input" />
The JS
$('#type').change(function totalprice(){
$('option').each(function() {
if($(this).val() === $('#type').val()) {
$('#eventprice').val($(this).data('price'));
}
});
});
I would recommend using jQuery due to its efficient code.
HTML:
<input type="text" disabled id="eventprice" />
<select id="select">
<option data-cost="5">Event 1</option>
<option data-cost="10">Event 2</option>
</select>
jQuery:
$('#select').change(function () {
var str = $(this).find('option:selected').data('cost');
$('#eventprice').val(str);
});
// This code can be used to run it on load
// $('#select').trigger('change');
Code in action:
http://jsfiddle.net/LkaWn/
Hope this helps :)
Modify the 3rd/4th line of your code to be $('#eventprice').val("45"); as suggested, except that the suggestion had a syntax error.

Categories

Resources