Switch Case JavaScript Form - javascript

I hope this is not a duplicate. I want to build a interactive web-form in this way. After every question or selection the user does the new question appear so till then all question are hidden , beside the first; and my second problem is that I want the second, third.. response to be dependent on which response they have on the previous question. Do you know how can I do that with switch case.
I will give here a small example of what i want:
So the only question that appears in form to be Where o you live, and if the user select France, a second dropdown list is created and is asking to select the city of France and only city of France is showed and so on.
<p>Where do you live</p>
<select name="country" id="country" required>
<option value="UK">UK</option>
<option value="UK">France</option>
</select>
<p>select the city in the uk</p>
<select name="town1 id="town1" required>
<option value="London">London</option>
<option value="Manchester">Manchester</option>
</select
<p>select the city in france</p>
<select name="town2 id="town2" required>
<option value="Paris">Paris</option>
<option value="St.Tropez">St.tropez</option>
</select>
Thank you for the help,
Alex

try this.
You don't need duplicate select for every country. Just set depencency with data-country.
And for another questions you can make the same. Set data attributes with appropriate values for questions wrappers, and they dynamically shows or hides on form changing.
// This listener makes dependency variants in select
document.getElementById('country').addEventListener('change', function() {
const selectedCountryValue = this.value;
document.getElementById('selectedCountry').innerText = this.children[this.selectedIndex].text;
const town = document.getElementById('town');
town.querySelectorAll('option').forEach(function(opt, i) {
opt.style.display = opt.dataset.country == selectedCountryValue ? 'block' : 'none';
if ((i == town.selectedIndex) && opt.dataset.country != selectedCountryValue) {
town.querySelectorAll(`option[data-country="${selectedCountryValue}"]`)[0].selected = true
}
});
})
document.getElementById('country').dispatchEvent(new Event('change'))
// This listener makes questions showed and required, if another questions answered appropriate answers
document.getElementById('dynamicForm').addEventListener('change', function() {
const form = this;
document.querySelectorAll('.question').forEach(function(question) {
let activeQuestion = true;
Object.keys(question.dataset).forEach(function(key) {
activeQuestion &= (question.dataset[key] == form.querySelector(`#${key}`).value);
})
question.style.display = (activeQuestion) ? 'block' : 'none'
question.querySelector('input, select').required = activeQuestion;
});
})
document.getElementById('dynamicForm').dispatchEvent(new Event('change'))
<form id="dynamicForm">
<p>Where do you live</p>
<select name="country" id="country" required>
<option value="UK">UK</option>
<option value="France">France</option>
</select>
<p>Select the city in the <span id="selectedCountry"></span></p>
<select name="town" id="town" required>
<option data-country="UK" value="London">London</option>
<option data-country="UK" value="Manchester">Manchester</option>
<option data-country="France" value="Paris">Paris</option>
<option data-country="France" value="St.Tropez">St.tropez</option>
</select>
<div class="question" data-country="France">
<p>Another one question if you live in France</p>
<input type="text" />
</div>
<div class="question" data-town="Paris">
<p>Another one question if you live in Paris</p>
<input type="text" />
</div>
</form>

Related

How to pass two user input dates through url

I have a requirement where I need to pass two dates(DateFrom and DateTo) through the URL using <a href> which goes to another page where it shows the report of that dates.both the dates are in format yyyy-mm-dd.
below is the code I'm using.
here DateFrom and DateTo in the URL will be the dates that the user selects.
I have used radio buttons to select the columns to be generated in the report. user will choose either 1st set of columns or 2nd set of columns. and the chosen set of columns will be shown in the report.
After choosing from date, to date, and set of columns, the user will click on the generate report button which goes to the other page where it shows the report.
How shall I pass those two date values and radio button conditions for selecting columns.
the UI is in FTL(freemarker). I'm also attaching an image of the UI for better understanding.
there are two different URLs for two different sets of columns.
the URLs are
1st set of columns: http://localhost:9191/preview?__report=production_1.rptdesign&__format=pdf&DateFrom=2022-06-10&DateTo=2022-06-10
2nd set of columns: http://localhost:9191/preview?__report=production_2.rptdesign&__format=pdf&DateFrom=2022-06-10&DateTo=2022-06-10
if the user selects 1st set of columns one <a href> will be used and if the user selects 2nd set of columns another <a href> will be used. I haven't completed the coding part yet. how shall I achieve this in FTL?
<input type="date" id="quality-fromdate">
<input type="date" id="quality-toDate">
<input id="radiobutton1" type="radio" name="radio-button">
<div class="select-columns-options-1" id="select-columns-options1">
<option value="tasks">Product Name</option>
<option value="tasks">Order Id</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
<option value="tasks">Due Date</option>
<option value="tasks">Estimated Completion Time</option>
</div>
<input id="radiobutton2" type="radio" name="radio-button">
<div class="select-columns-options-2">
<option value="tasks">Product Name</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
</div>
Generate Report
I wouldn't use <a> here, since the url has to be generated dynamically. Here's an example using a button and figuring out the url when the button is clicked. If you absolutely have to use <a>, you'd probably have to bind into the change events of the dates and the radios and update the href of the <a> that way.
const btnclick = () => {
let radio = document.querySelector("input[type='radio']:checked").id === "radiobutton1" ? 1 : 2;
let from = document.querySelector("#quality-fromdate").value;
let to = document.querySelector("#quality-toDate").value;
console.log(`http://localhost:9191/preview?__report=production_${radio}.rptdesign&__format=pdf&DateFrom=${from}&DateTo=${to}`)
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
To: <input type="date" id="quality-fromdate"> From: <input type="date" id="quality-toDate">
<br/>
<input id="radiobutton1" type="radio" name="radio-button" checked>
<select class="select-columns-options-1" id="select-columns-options1">
<option value="tasks">Product Name</option>
<option value="tasks">Order Id</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
<option value="tasks">Due Date</option>
<option value="tasks">Estimated Completion Time</option>
</select>
<br/>
<input id="radiobutton2" type="radio" name="radio-button">
<select class="select-columns-options-2">
<option value="tasks">Product Name</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
</select>
<br/>
<button onclick="btnclick()">Generate Report</button>
You had quite a bit to go, here is working version using eventListener and URL object
I am not testing the dates
You also needed to be more consistent with IDs etc. I assume your link needed the two selects (they were divs in your code)
const url = new URL("http://localhost:9191/preview?__format=pdf")
const linkSpan = document.getElementById("link");
const dateFrom = document.getElementById("quality-fromDate")
const dateTo = document.getElementById("quality-toDate")
const reportType1 = document.getElementById("select-columns-options1");
const reportType2 = document.getElementById("select-columns-options2");
document.getElementById("reportDiv").addEventListener("click", function(e) {
linkSpan.innerHTML = "";
const reportRad = document.querySelector("[name=radio-button]:checked")
if (!reportRad) return;
if (reportType1.selectedIndex < 1 || reportType2.selectedIndex < 1) return; // nothing selected
url.searchParams.set("__report", reportRad.id === "radiobutton1" ? "production_1.rptdesign" : "production_2.rptdesign")
url.searchParams.set("__reportType1", reportType1.value);
url.searchParams.set("__reportType2", reportType2.value);
url.searchParams.set("DateFrom", dateFrom.value)
url.searchParams.set("DateTo", dateTo.value)
linkSpan.innerHTML = `${reportType1.options[reportType1.selectedIndex].text} - ${reportType2.options[reportType2.selectedIndex].text}`;
})
<div id="reportDiv">
<input type="date" id="quality-fromDate">
<input type="date" id="quality-toDate">
<input id="radiobutton1" type="radio" name="radio-button">
<select class="select-columns-options-1" id="select-columns-options1">
<option value="pname">Product Name</option>
<option value="oid">Order Id</option>
<option value="qo">Quantity Ordered</option>
<option value="qp">Quantity To Produce</option>
<option value="ddd">Due Date</option>
<option value="ect">Estimated Completion Time</option>
</select>
<input id="radiobutton2" type="radio" name="radio-button">
<select class="select-columns-options-2" id="select-columns-options2">
<option value="pname">Product Name</option>
<option value="qo">Quantity Ordered</option>
<option value="qtp">Quantity To Produce</option>
</select>
<span id="link"></span>
</div>

How to use if else statements in select form?

In my registration page, I'm gonna use two drop-down select that one of them should be hidden if its Negative and if its positive new drop-down will open to choose ...
In mysql table I've table as diabetes name with enom
enum('negative', 'insulin', 'drug', 'ndm', 'mody', '')
Here's my code:
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
For example: If Diabetes is negative value is negative as default then Diabetes Type is hidden
and
If Diabetes is positive then Diabetes type will be appeared to choose items.
those values like insulin, drug, mdm, mody should be inserted into this:
value="positive"
How can I make it through java script?
I can't add class or div or span. Is it possible just through JavaScript using ??
Thank you so much
Use jquery, it is comparatively easier.
$(document).ready(function(){
$("#diabetestype").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").show();
}else{
$("#diabetestype").hide();
}
});
});
To make this code workable, you need to add value of Positive option also. So instead value="" change it to value="positive".
You can even hide the label also:
$(document).ready(function(){
$("#diabetestype").closest("div").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").closest("div").show();
}else{
$("#diabetestype").closest("div").hide();
}
});
});
<div><label for="diabetes">Diabetes:</label>
<select id="diabet" name="diabet" onchange="checkDiabet();">
<option value="negative">Negative</option>
<option value="positive" id="isDiabet">Positive</option>
</select>
</div>
<div id="type" style="display: hidden;">
<label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
<script>
function checkDiabet() {
var isDiabet = document.getElementById("isDiabet").selected;
if (isDiabet == true) { document.getElementById("type").removeAttribute("style"); }
else { document.getElementById("type").style.display = "none"; }
}
</script>
First, set the first select to fire the function checkDiabet() by the attribute onchange. Then give the option an id, which needs to be checked, so you can access it easily.
Then, set the second select to display: none This could be done in a CSS header or file, or like in this case inline. (div style=""), also add an id to access it easily. (div id="type")
Now comes the function checkDiabete(). It checks if the select is selected (can be true or false (bool)). Is selected => show (div id="type"), if not, hide this div (and all of it's contents)
(if is already hidden, it then overwrites the (style="display: none;") with (style="display: none;))
That's it! :)
Try this:
function SelectDiabetes() {
var d = document.getElementById("diabetes").value;
var dType = document.getElementById("diabetestypebox");
if(d == "negative")
dType.style.display = "none";
else
dType.style.display = "block";
}
SelectDiabetes();
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="SelectDiabetes(this.value);">
<option value="negative">Negative</option>
<option value="positive">Positive</option>
</select>
</div>
<div id="diabetestypebox"><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Call a js function onchange of select id diabetes
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="toggleTypes()">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" style="display:none" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Use the following javascript
function toggleTypes(){
var el=document.getElementById('diabetes');
var medElem=document.getElementById('diabetestype');
if(el.value=='positive') {
medElem.style.display='block';
} else {
medElem.style.display='none';
}
}

How do I have my drop down selections submit in the HTML form?

I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.

Drop down text input option

I want a drop down element where user can select from available options or select enter value option which in turn allows to enter value.
I specifically want that user can enter value only when they select "Enter a value " option.
Here is what I have tried so far.
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
}
});
JS fiddle
however it wont work properly if i click the enter value option again.
I think there are many plugins that do what you want but if you want to create your own, it's a basic and simple solution.
You can create a select and a textbox with display:none like this:
<select id="ddlDropDownList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="-1">Enter Value</option>
</select>
<input id="txtTextBox" type="text" />
<style>
#txtTextBox{
display:none;
}
</style>
then try this JQuery:
$("#ddlDropDownList").change(function(){
if($(this).val() == '-1'){
$("#txtTextBox").fadeIn();
}else{
$("#txtTextBox").fadeOut();
}
});
Check JSFiddle Demo
I have forked your JSFiddle to http://jsfiddle.net/pwdst/4ymtmf7b/1/ which I hope does what you wanted to achieve.
HTML-
<div class="ginput_container">
<label for="input_1_4">Select option</label>
<select class="medium gfield_select" id="input_1_4" name="input_4" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<div>
<label class="hidden-label" for="input_1_4_other">Other value</label>
<input class="holder" id="input_1_4_other" disabled="disabled" name="input_1_4_other" placeholder="None" type="text" />
</div>
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var $this = jQuery(this);
var val = $this.val();
var holder = $this.parent().find('.holder');
if (val === "*"){
holder.val('');
holder.removeAttr('disabled');
holder.focus();
} else {
holder.val(this.options[this.selectedIndex].text);
holder.attr('disabled', 'disabled');
}
});
When the "Enter value" option is chosen then the input box is enabled, value set to an empty string, and it is focused. If another option is chosen then the text input is disabled again, and the text value from the select list is used.
Thanks guys
I guess i have found my answer
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
JS FIDDLE

jquery - show and hide DIV with the select tag

<label for="continent">Select Continent</label>
<select id="continent" onchange="countryChange(this );">
<option value="empty">Select a Continent</option>
<option value="North America">North America</option>
<option value="South America">South America</option>
<option value="Asia">Asia</option>
<option value="Europe">Europe</option>
<option value="Africa">Africa</option>
</select>
<br/>
<label for="country">Select a country</label>
<select id="country">
<option value="0">Select a country</option>
</select>
<div id="soc-pri">
<label for="company">Company</label>
<input name="customer" type="radio" value="company" />
<label for="private">Private</label>
<input name="customer" type="radio" value="private" />
</div>
<div id="lib-ass">
<label for="individual firm / freelancer">Individual Firm / Freelancer Professionista</label>
<input name="customer" type="radio" value="privato" />
<label for="association">Associazione</label>
<input name="customer" type="radio" value="association" />
</div>
$(document).ready(function () {
$("select").change(function () {
if ($("select option:selected").val() == "Europe") {
$('#lib-ass').show();
$('#soc-pri').show();
} else if ($("select option:selected").val() != "Europe") {
$('#lib-ass').hide();
}
}).change();
});
Hello everyone, I just started to study jquery.
I have two select fields that contain the continents and countries.
My needs nascodere show the two-DIV, "lib-ass" and "soc-first":
1) When you select the continent of Europe the DIV "lib-ass," appears. That is OK
2) When you do not select the continent Europe DIV "lib-ass", hides. That is OK
3 When you do not select the country DIV Britain the "lib-ass" must hide. This is not OK.
When you select the country DIV Britain the "lib-ass" you have to show. This is not OK
My problem is that I can not hide-show, when you select your country Britain the DIV tag with id "lib-ass."
Where am I wrong?
I hope averdato much information as possible.
thanks
http://jsfiddle.net/carmy/jg7Ls/6/
http://jsfiddle.net/J2XDk/1/ Is this what you're looking to do?
I made a few changes: select values can be retrieved by calling .val() directly on the select (no need for finding the selected option). I also look it up specifically using the select box ID since just doing $('select') is ambiguous. Save values to variables so you don't have to execute the jQuery multiple times. The alternate condition for the Europe check can just use else, no need to specifically check for != "Europe"
$(document).ready(function () {
$("select").change(function () {
var continent = $('#continent').val(),
country = $('#country').val(),
$libass = $('#lib-ass'),
$socpri = $('#soc-pri');
if (continent === "Europe") {
$libass.show();
$socpri.show();
} else {
$libass.hide();
}
if(country === 'Britain') {
$libass.hide();
} else {
$libass.show();
}
}).change();
});
You could add the following to your logic:
$("#country").change(function(){
if($("#country option:selected").val() == "Britain") {
$('#lib-ass').show();
$('#soc-pri').show();
}else{
$('#lib-ass').hide();
}
}).change();
Where country is the select box of your selected country. The hashtag (#) is used to call a specific ID in Jquery.
Here is a working example

Categories

Resources