Change form fields based on dropdown values - javascript

I have an HTML for in which I have dropdown at the beginning, How do I change the form fields base on selection of dropdown value?
Here is the code.
Like if I select General Inquiry it should display first 2 form fields and the form fields in general div
If I select Credit Inquiry it should display first 2 form fields and the form fields in credit div
if I select payment Inquiry it should display first 2 form fields and the form fields in payment div
<form action="">
<select name="cases" id="cases">
<option value="general">General Inquiry</option>
<option value="credit">Credit Inquiry</option>
<option value="payment">Payment Issue</option>
</select><br>
<label for="email">Email Address <span>*</span></label>
<input type="text">
<label for="full name">Full Name <span>*</span></label>
<input type="text">
<div class="general" id="general">
<label for="documents">Wish to submit any requested documents?</label>
<input type="radio" name="radio">Yes
<input type="radio" name="radio">No <br><br>
<label for="select">How did you find out about us?<span>*</span></label><br>
<select name="case" id="case-type">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select><br>
</div>
<div class="credit" id="credit">
<label for="Date of Inquiry">Date of Inquiry<span>*</span></label>
<input type="date">
<label for="Agency">Agency 3 <span>*</span></label>
<input type="text">
</div>
<div class="payment" id="payment">
<label for="Service Phone Number">Service Phone Number<span>*</span></label>
<input type="text">
<label for="select">Topic<span>*</span></label><br>
<select name="case" id="case-type">
<option value="topic1">Topic 1</option>
<option value="topic2">Topic 2</option>
<option value="topic3">Topic 3</option>
</select><br><br>
</div>
<br><br>
<button>Submit</button>
</form>

Late to the party here, but here is another way
// hide all the divs
$('div').hide()
// Show and hide selected div
$('#cases').change(function () {
var value = this.value;
$('div').hide()
$('#' + this.value).show();
});
Also created a demo

I wrote for case "general"..U can follow this for other cases
$("#cases").change(function () {
var case = $( "#cases option:selected" ).val();
if(case=="general")
{
//show 2 form fields here and show div
$("#general").show();
}
});

Just hide all divs an show the corresponding one on select change if this is what you mean
$('div').hide()
$('#cases').change(function(){
var v=this.value;
$('div').hide().filter(function(){return this.id==v}).show()
});

Related

Set labels of radio button group dynamically based on values selected in drop down lists

I have an html form with 4 form elements - 3 drop down lists and one group of radio buttons.
I want the label of the radio buttons to be set dynamically based on the values selected in the drop down lists.
Ex- The values selected in the drop down lists are q-tip, hold and h1 rspectively.
So, the labels in the radio button group (Direction) should be:
First radio button - q-tip hold h1.
Second radio button - h1 hold q-tip
This is the jsfiddle link : http://jsfiddle.net/coderr/yznf1qk3/22/
<div style="float:left;">
<h5>Object</h5>
<select name="object" id="object">
<option value="q-tip">q-tip</option>
<option value="o2">o2</option>
</select>
</div>
<div style="float:left;">
<h5>Action</h5>
<select name="action" id="action">
<option value="hold">hold</option>
<option value="a2">a2</option>
</select>
</div>
<div style="float:left;">
<h5>Person</h5>
<select name="humann" id="human">
<option value="h1">h1</option>
<option value="h2">h2</option>
</select>
</div>
<fieldset>
<legend>Direction</legend>
<input type="radio" name="direction" value="towards">q-tip hold h1<br>
<input type="radio" name="direction" value="away">h1 hold q-tip<br>
</fieldset>
You need to add some HTML to make it easier to access the text
$("#selects").on("change",function() { // any change of selects
const dirs = $(this).find("select").map(function() { return this.value }).get(); // get the values in an array
const $rads = $("[name=direction]"); // the radios
$rads.eq(0).next().text(dirs.join(" ")); // update the span after the radio - I wrapped in label too
dirs.reverse(); // reverse the array
$rads.eq(1).next().text(dirs.join(" ")); // add to the second radio span
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="selects">
<div style="float:left;">
<h5>Object</h5>
<select name="object" id="object">
<option value="q-tip">q-tip</option>
<option value="o2">o2</option>
</select>
</div>
<div style="float:left;">
<h5>Action</h5>
<select name="action" id="action">
<option value="hold">hold</option>
<option value="a2">a2</option>
</select>
</div>
<div style="float:left;">
<h5>Person</h5>
<select name="humann" id="human">
<option value="h1">h1</option>
<option value="h2">h2</option>
</select>
</div>
</div>
<fieldset>
<legend>Direction</legend>
<label><input type="radio" name="direction" value="towards"><span>q-tip hold h1</span></label><br>
<label><input type="radio" name="direction" value="away"><span>h1 hold q-tip</span></label><br>
</fieldset>

Duplicate fields in a form upon selection

I made a form to select skills. After the 1st selection is made, a 2nd list is shown with options depending of the 1st choice.
Then, a "+" button allow to duplicate the fields ans add another skill.
My problem :
The inital form is OK but when I press "+" the second form created doesn't work (the second "select field" is not filtered according to the first select.
Please can you help?
Thanks a lot.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Skill form</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" /></script>
</head>
<body>
<h1>Insert your skills</h1>
<div class="copycat">
<div id="form">
<form action="" method="post" name="addbloc">
<p>
<label for="tpl">Family :</label>
<select name="tpl" id="tpl">
<option value="">-- Select your family --</option>
<option value="Language" data-id='#champ1'>Language</option>
<option value="Cooking" data-id='#champ2'>Cooking</option>
</select><br />
<div class="champ" id="champ1">
<label for="Language">Skill :</label>
<select name="Language" id="Language">
<br/>
<option value="">-- Select your skill --</option>
<option value="Spanish" data-id='#champ1'>Spanish</option>
<option value="Chineese" data-id='#champ1'>Chineese</option>
<option value="French" data-id='#champ1'>French</option>
</select><br />
<input onclick="copycat();" id="button" value="+" type="button">
</div>
<div class="champ" id="champ2">
<label for="Cooking">Skill :</label>
<select name="Cooking" id="Cooking">
<br/>
<option value="">-- Select your skill --</option>
<option value="Italian" data-id='#champ2'>Italian</option>
<option value="Mexican" data-id='#champ2'>Mexican</option>
<option value="Japanese" data-id='#champ2'>Japanese</option>
<option value="Greek" data-id='#champ2'>Greek</option>
</select><br />
<input onclick="copycat();" id="button" value="+" type="button">
</div>
</p>
</form>
</div>
</div>
<!-- WIP ----- Submit button to store in database -->
<div style="z-index:99;"><input type="submit" name="Submit" value="Submit" class="bouton"></div>
<script type="text/javascript">
// Show 2nd field according to first field selection
$(document).ready(function() {
$('.champ').hide(); // on cache les champ par défaut
$('select[name="tpl"]').change(function() { // lorsqu'on change de valeur dans la liste
$('.champ').hide();
var selectedDataID = $(this).find('option:selected').attr('data-id');
$(selectedDataID).show();
});
});
// Duplicate field when + button is pressed
function copycat(){
$('.copycat:first').clone().appendTo($('#form'));
}
</script>
</body>
</html>
You cannot use same ids for different elements so instead of id i have change that to html attributes i.e :data-id .Then , when you select any option from select-box only divs which are inside form should change not others which are added dynamically so use $(this).closest("form").. to make change inside form htmls . Lastly ,these elements are created dynamically so use $(document).on('change', 'select[name="tpl"]',...
Also, your copycat function is copying entire div so next time if you press + it will show 2 copy of select and so on .To fix this use $('.copycat form:first')....
Demo Code :
$(document).ready(function() {
$('.champ').hide();
$(document).on('change', 'select[name="tpl"]', function() {
$(this).closest("form").find('.champ').hide(); //hide the champ div inside form which is there
var selectedDataID = $(this).find('option:selected').attr('data-id');
//get the div with dta-id of slected option
$(this).closest("form").find("div[data-id=" + selectedDataID + "]").show();
});
});
// Duplicate field when + button is pressed
function copycat() {
//copy first form
$('.copycat form:first').clone().appendTo($('#form'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Insert your skills</h1>
<div class="copycat">
<div id="form">
<form action="" method="post" name="addbloc">
<p>
<label for="tpl">Family :</label>
<!--instead of id added data-id -->
<select name="tpl" id="tpl">
<option value="">-- Select your family --</option>
<option value="Language" data-id='champ1'>Language</option>
<option value="Cooking" data-id='champ2'>Cooking</option>
</select><br />
<!--added data-id-->
<div class="champ" data-id="champ1">
<label for="Language">Skill :</label>
<select name="Language" id="Language">
<br/>
<option value="">-- Select your skill --</option>
<option value="Spanish" data-id='#champ1'>Spanish</option>
<option value="Chineese" data-id='#champ1'>Chineese</option>
<option value="French" data-id='#champ1'>French</option>
</select><br />
<input onclick="copycat();" id="button" value="+" type="button">
</div>
<!--added data-id-->
<div class="champ" data-id="champ2">
<label for="Cooking">Skill :</label>
<select name="Cooking" id="Cooking">
<br/>
<option value="">-- Select your skill --</option>
<option value="Italian" data-id='#champ2'>Italian</option>
<option value="Mexican" data-id='#champ2'>Mexican</option>
<option value="Japanese" data-id='#champ2'>Japanese</option>
<option value="Greek" data-id='#champ2'>Greek</option>
</select><br />
<input onclick="copycat();" id="button" value="+" type="button">
</div>
</p>
</form>
</div>
</div>
<!-- WIP ----- Submit button to store in database -->
<div style="z-index:99;"><input type="submit" name="Submit" value="Submit" class="bouton"></div>

What gets submitted to the database is just the entry of "other" and not what i typed in manually?

When i select the option value of "other" in my dropdown lis the form row below appears and allows me to type a manual cemetery but what gets submitted to the database is just the entry of "other" and not what i typed in manually?
<script>
function handleSelect() {
var selected = document.getElementById("mySelect").value;
var details = document.getElementById("other-details");
if (selected === "other") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Cemetery</label>
<select name="cemetery" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="select" selected="selected">Select Cemetery</option>
<option value="Akatarawa">Akatarawa</option>
<option value="Taita">Taita</option>
<option value="Wainuiomata">Wainuiomata</option>
<option value="Whenua Tapu">Whenua Tapu</option>
<option value="Makara">Makara</option>
<option value="Karori">Karori</option>
<option value="St Johns">St Johns</option>
<option value="Awa Tapu">Awa Tapu</option>
<option value="Paraparaumu">Paraparaumu</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="" placeholder="Enter other Cemetery" />
</div>
</div>
</body>
Try setting name of the input to cemetery.
<input type="text" id="other" class="form-control" name="cemetery" placeholder="Enter other Cemetery" />
This may work, but not a good practise.
I suggest you to do something like following
HTML
<input type="text" id="other" class="form-control" name="other-cemetery" placeholder="Enter other Cemetery" />
PHP
if($_POST["cemetery"] == "other"){
$cemetery = $_POST["other-cemetery"];
}
Update: The first solution that I gave may not work in other cases. So add the following line to handleSelect() function. (Not selected case)
document.getElementById("other").value = document.getElementById("mySelect").value;
Thanks Dum, combining that link of JS and setting the Value of the "other" drop down to empty.
Example: <option value="">Other</option>
This has resolved my issue. Many thanks

Display div when specific option selected [duplicate]

This question already has answers here:
Want to show/hide div based on dropdown box selection
(7 answers)
Closed 4 years ago.
I want to show a DIV when a specific OPTION Value is selected. i have a html element like this.
<select id="type">
<option value="Article on Company">Article on Company</option>
<option value="Article on Company">Article by Company</option>
<option value="Concept Paper">Concept Paper</option>
</select>
And here is the following content
<div class="subdiv">
<div class="form-group mb-20">
<label>Title</label>
<input class="form-control" name="title">
</div>
<div class="form-group mb-20">
<label>Description</label>
<input class="form-control" name="description">
</div>
<div>
I want to hide the class subdiv when page load. If a user select the option "Article on Company" or "Article by Company" i want to show input fields with name 'title, description'. If a user select the option with value "Concept Paper", then i want to show only input field with name description. Please help me.
You can hide/show element based on the selected option value. Try the following way:
$('#type').change(function(){
$('.subdiv').show();
if($(this).val() == 'Article on Company' || $(this).val() == 'Article by Company'){
$('[name=title], [name=description]').parent().show();
}
else if($(this).val() == 'Concept Paper'){
$('[name=description]').parent().show();
$('[name=title]').parent().hide();
}
else
$('.subdiv').hide();
});
.subdiv{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type">
<option value="Select">---Select-</option>
<option value="Article on Company">Article on Company</option>
<option value="Article by Company">Article by Company</option>
<option value="Concept Paper">Concept Paper</option>
</select>
<div class="subdiv">
<div class="form-group mb-20">
<label>Title</label>
<input class="form-control" name="title">
</div>
<div class="form-group mb-20">
<label>Description</label>
<input class="form-control" name="description">
</div>
<div>

Change the form action when an onchange event is triggered on <select> with 2 forms on page

I ran into an issue where I have two forms on a page -
A desktop version of the form
A mobile version.
Both forms don't show to the user as it depends on their viewport or device. When the user selects "Student Loan" from the agency drop-down selection (in either form), we want the form submission's action to be /quote/quotes-sl.php instead of the form default of /quote/quotes.php.
The good news is that on the mobile-friendly form (the first form in the code below), the solution works. However, for the desktop form, it does not even though it has the same form id/name. I tried renaming the desktop form to have a different formID/name` and then add another script for that form, but that doesn't work.
Any direction or advice is greatly appreciated.
(function() {
var theForm = document.getElementById('tdhcustom-pre-1-form');
var theSelector = document.getElementById('agency');
theSelector.onchange = function() {
theForm.action = theSelector[theSelector.selectedIndex].getAttribute('data-action');
}
})();
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
<div>
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="1.test" />
<div id="edit-owed-wrapper" class="form-item">
<label class="edit-owed" for="edit-owed"> Tax Debt Owed: <span class="form-required" title="This field is required.">*</span></label>
<select id="edit-owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$30,000 to $39,999">$30,000 to $39,999</option>
<option value="$40,000 to $59,999">$40,000 to $59,999</option>
<option value="$60,000 to $79,999">$60,000 to $79,999</option>
<option value="$80,000 to $99,999">$80,000 to $99,999</option>
<option value="$100,000+">$100,000 +</option>
</select>
</div>
<div id="edit-agency-wrapper" class="form-item">
<label class="edit-agency" for="edit-agency"> Tax Agency: <span class="form-required" title="This field is required.">*</span></label>
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="Federal" data-action="/quote/quotes.php">Federal</option>
<option value="STATE" data-action="/quote/quotes.php">State</option>
<option value="FEDERAL_AND_STATE" data-action="/quote/quotes.php">Federal and State</option>
</select>
</div>
<input id="edit-submit" class="form-submit" height="31" name="submit" src="http://www.test.com/wp-content/uploads/2009/07/form-submit-6-17-small.png" type="image" value="Submit" width="214" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</div>
</form>
<div class="mycustombanner desk-view">
<img class="wp-image-12546 size-full alignnone" src="http://www.test.com/wp-content/uploads/2009/12/top-form-irs-hardship-status.png" alt="irs hardship status" width="618" height="194" />
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-2-form">
<div>
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="1.test-desktop" />
<div id="edit-owed-wrapper" class="form-item">
<label for="edit-owed"> Tax Debt Owed: <span class="form-required" title="This field is required.">*</span></label>
<select id="edit-owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$30,000 to $39,999">$30,000 to $39,999</option>
<option value="$40,000 to $59,999">$40,000 to $59,999</option>
<option value="$60,000 to $79,999">$60,000 to $79,999</option>
<option value="$80,000 to $99,999">$80,000 to $99,999</option>
<option value="$100,000+">$100,000 +</option>
</select>
</div>
<div id="edit-agency-wrapper" class="form-item">
<label for="edit-agency"> Tax Agency: <span class="form-required" title="This field is required.">*</span></label>
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="Federal" data-action="/quote/quotes.php">Federal</option>
<option value="STATE" data-action="/quote/quotes.php">State</option>
<option value="FEDERAL_AND_STATE" data-action="/quote/quotes.php">Federal and State</option>
</select>
</div>
<input id="edit-submit" class="form-submit" height="37" name="submit" src="http://www.test.com/wp-content/uploads/2010/04/form-submit-6-17-1.png" type="image" value="Submit" width="207" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</form>
</div>
It is invalid HTML to have more than one element with the same ID in one document - that's why the selector is failing.
Try giving both forms different IDs, as well as for the select element, for example:
<form id="tdhcustom-pre-1-form1"...
<select id="agency1"...
...
...
<form id="tdhcustom-pre-1-form2"...
<select id="agency2"...
Then you could do:
[
['tdhcustom-pre-1-form1', 'agency1'],
['tdhcustom-pre-1-form2', 'agency2'],
].forEach(([formSelector, agencySelector]) => {
const form = document.getElementById(formSelector);
const agency = document.getElementById(agencySelector);
agency.addEventListener('change', () => {
form.action = agency[agency.selectedIndex].getAttribute('data-action');
});
});
Now that I've looked at your code more, I'm going to say more confidently that sharing the same id between your forms is the problem you're having. This line:
var theForm = document.getElementById('tdhcustom-pre-1-form');
...isn't going to care which form is hidden, and which form is shown. It's always going to return you the same form. Your browser must be favoring the mobile form over the desktop form.

Categories

Resources