Populating form fields on change of drop down using javascript - javascript

I am trying to populate data in my fields depending on the value selected in the drop down box. I have passed the dropdown option select to the javascript function, but having problem in updating the form fields. Please check my code for the error I've committed.
This is my html code:
<div class="form-ui">
<span class="form-elements reqField">
<select class="dropdown" onchange="populateData(this.options[this.selectedIndex].value,1)">
<option value="1">Please Select</option>
<option value="2">Mrs.Jane Smith</option>
<option value="3">Mr.Junior Smith</option>
</select>
</span>
<span class="form-elements reqField">
<select id="itle1" class="dropdown">
<option value="1">Mr.</option>
<option value="2">Ms.</option>
<option value="3">Mrs.</option>
</select>
</span>
<span class="form-elements">
<input id="FirstName1" type="text" class="text" value="" />
</span>
<span class="form-elements reqField">
<input id="LastName1" type="text" class="text" value="" />
</span>
</div>
And the javascript code:
function populateData(value,person){
if(value==2){
$('#Title'+person).value=3;
$('#FirstName'+person).value="Jane";
$('#LastName'+person).value="Smith";
}
if(value==3){
}
}

jQuery uses val() to get and set values.
So your js function should be
$('#FirstName'+person).val("Jane");
$('#LastName'+person).val("Smith");
and not
$('#FirstName'+person).value="Jane";
$('#LastName'+person).value="Smith";
Also
<select class="dropdown" onchange="populateData(this.options[this.selectedIndex].value,1)">
should be
<select class="dropdown" onchange="populateData(this.value,1)">

quick answer is that I think you need to use val() not value - can't quite remember how it works with select though
http://api.jquery.com/val/

HTML ID error here <select id="itle1" class="dropdown">
Should be Title1 not itle1
Also I think the javascript should look like this
function populateData(value,person){
if(value==2){
$('#Title'+person+' option[value="3"]').attr('selected','selected');
$('#FirstName'+person).val("Jane");
$('#LastName'+person).val("Smith");
}
if(value==3){
}
}

You could use a FORM instead of a DIV, and the attribute name, instead of id.
They were designed a long time ago to manage forms.
You can use jQuery for that, but everything is already built-in in pure Javascript to handle forms.
<form class="form-ui">
<span class="form-elements reqField">
<select class="dropdown" onchange="populateData(this)">
<option value="1">Please Select</option>
<option value="2">Mrs.Jane Smith</option>
<option value="3">Mr.Junior Smith</option>
</select>
</span>
<span class="form-elements reqField">
<select name="title" class="dropdown">
<option value="1">Mr.</option>
<option value="2">Ms.</option>
<option value="3">Mrs.</option>
</select>
</span>
<span class="form-elements">
<input name="FirstName" type="text" class="text" value="" />
</span>
<span class="form-elements reqField">
<input name="LastName" type="text" class="text" value="" />
</span>
</form>
<script>
function populateData(sel){
var form = sel.form,
value = sel.options[sel.selectedIndex].value;
switch(value){
case '3':
form.FirstName.value = 'Junior';
form.LastName.value = 'Smith';
form.title.value = '1';
break;
case '2':
break;
default:
}
}
</script>

Related

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.

Execute javascript on new born DOM elements after select change

i have a problem on new elements created after select change event.
This is my HTML:
<div class="cont-filtri">
<div class="form-group uno">
<label>Marca <span class="mandatory">*</span>:</label>
<select name="brad" class="form-control" required>
<option value="">Scegli</option>
<option value="1">Yamaha</option>
</select>
</div>
<div class="form-group due hide">
<label>Modello <span class="mandatory">*</span>:</label>
<select name="model" class="form-control" required disabled>
<option value="">Scegli</option>
<option value="1">Super bella</option>
</select>
</div>
<div class="form-group tre hide">
<label>Anno :</label>
<select name="year" class="form-control" disabled>
<option value="">Scegli</option>
<option value="1">2017</option>
</select>
</div>
</div>
<button type="button" class="btn btn-default aggiungi-filtro"><i class="fa fa-plus" aria-hidden="true"></i> Aggiungi filtro</button>
And this is my javascript :
$(".aggiungi-filtro").click(function(){
$(this).before('<hr/><div class="cont-filtri"><div class="form-group uno"> <label>Marca <span class="mandatory">*</span>:</label> <select name="brad" class="form-control" required> <option value="">Scegli</option> <option value="1">Yamaha</option> </select> </div><div class="form-group due hide"> <label>Modello <span class="mandatory">*</span>:</label> <select name="model" class="form-control" required disabled> <option value="">Scegli</option> <option value="1">Super bella</option> </select> </div><div class="form-group tre hide"> <label>Anno :</label> <select name="year" class="form-control" disabled> <option value="">Scegli</option> <option value="1">2017</option> </select> </div></div>')
});
$(".uno select").on("change",function(){
$(this).closest(".cont-filtri").find(".due select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".due").removeClass("hide");
});
$(".due select").on("change",function(){
$(this).closest(".cont-filtri").find(".tre select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".tre").removeClass("hide");
});
Here is the css for hidden elements:
.hide{
display:none;
}
This is my fiddle:
CLICK HERE
I'm trying to have the same control on new born elements.
For instance, when i switch my first select option, another select shows-up and so on.
This works perfectly on my first html element, but it doesn't work on the new borns.
Can you please help me?
Thank you!
You also can use delegation like this too:
$(document).on("change", ".uno select", function(){
....
});
With your code, the event listener is registered only on the pre-existing select.
You can either register a new listener for the new select in the method that creates it or use a listener that is registered a the document level as already suggested in other comments.
You can use event delegation, attaching the listener to a parent element (via JQuery selector or the document itself):
$(document).on("click", ".aggiungi-filtro", function(){
$(this).before('<hr/><div class="cont-filtri"><div class="form-group uno"> <label>Marca <span class="mandatory">*</span>:</label> <select name="brad" class="form-control" required> <option value="">Scegli</option> <option value="1">Yamaha</option> </select> </div><div class="form-group due hide"> <label>Modello <span class="mandatory">*</span>:</label> <select name="model" class="form-control" required disabled> <option value="">Scegli</option> <option value="1">Super bella</option> </select> </div><div class="form-group tre hide"> <label>Anno :</label> <select name="year" class="form-control" disabled> <option value="">Scegli</option> <option value="1">2017</option> </select> </div></div>')
});
$(document).on("change", ".uno select", function(){
$(this).closest(".cont-filtri").find(".due select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".due").removeClass("hide");
});
$(document).on("change", ".due select", function(){
$(this).closest(".cont-filtri").find(".tre select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".tre").removeClass("hide");
});
In your case you can avoid the event delegation because you may act differently.
I suggest you to use clone(true): Create a deep copy of the set of matched elements preserving the event handlers.
In this way you will reduce your code.
$(".aggiungi-filtro").click(function () {
$(this).before('<hr/>')
.before($('.cont-filtri:first').clone(true)
.find('select.form-control').val('').end()
.find(".form-group:gt(0)").addClass("hide").end());
});
$(".uno select").on("change", function () {
$(this).closest(".cont-filtri").find(".due select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".due").removeClass("hide");
});
$(".due select").on("change", function () {
$(this).closest(".cont-filtri").find(".tre select").attr("disabled", false);
$(this).closest(".cont-filtri").find(".tre").removeClass("hide");
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont-filtri">
<div class="form-group uno">
<label>Marca <span class="mandatory">*</span>:</label>
<select name="brad" class="form-control" required>
<option value="">Scegli</option>
<option value="1">Yamaha</option>
</select>
</div>
<div class="form-group due hide">
<label>Modello <span class="mandatory">*</span>:</label>
<select name="model" class="form-control" required disabled>
<option value="">Scegli</option>
<option value="1">Super bella</option>
</select>
</div>
<div class="form-group tre hide">
<label>Anno :</label>
<select name="year" class="form-control" disabled>
<option value="">Scegli</option>
<option value="1">2017</option>
</select>
</div>
</div>
<button type="button" class="btn btn-default aggiungi-filtro"><i class="fa fa-plus" aria-hidden="true"></i> Aggiungi
filtro
</button>

PHP:- validate and pass the value by POST in newtab

Below code is about passing the value to the new tab by POST.
My question is the value selected in drop-down list needed to be validated.
As 'select' value is default value. If the default value is selected then some alert must be shown else the remaining behavior is same as below code.
<form action="send_mail.php" name="choose_aff" method="POST">
<select name="company" id="company" class="company_select" style="width:250px;">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="xyz">xyz</option>
</select>
<input class="proceed_btn" type="submit" value="Proceed to mail>>" style="float:right" onclick="this.form.target='_blank';return true;">
</form>
You can validate without external libraries, just using javascript in client side (if you want) You need something like this:
<script type="text/javascript">
function myValidateFunction() {
alert("something happened!");
console.log("something happened!");
//what i want!
}
</script>
...
<form action="send_mail.php" name="choose_aff" method="POST" target="_blank">
<select name="company" id="company" class="company_select" style="width:250px;" onchange="myValidateFunction()">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="xyz">xyz</option>
</select>
<input class="proceed_btn" type="submit" value="Proceed to mail" style="float:right;" />
</form>
Then you should validate the data sent in send_mail.php file
Add target="_blank" to form attributes like this
<form action="send_mail.php" name="choose_aff" method="POST" target="_blank">
I remove a button and then the send_mail.php will open only when value is changed from dropdown. Add dropdown will send value using POST
<form action="send_mail.php" name="choose_aff" method="POST">
<select name="company" id="company" class="company_select" style="width:250px;" onchange="submit()">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="xyz">xyz</option>
</select>
</form>

How to put option value into another input

When the user selects an option from the list, i want to put the option values into the space - however again every time i try, it goes wrong. Can anyone help or point me in the right direct with this please - thanks.
This is the form code.
<form>
<div class="form-group">
<div class="col-xs-6">
<div class="input-group">
<span class="input-group-addon"><i class="gi gi-user"></i></span>
<select class="form-control input-md" id="subscription" name="subscription">
<option value="1">Choose Plan</option>
<option value="Solo">Solo - 1</option>
<option value="Double">Double - 2</option>
<option value="Triple">Triple - 3</option>
</select>
</div>
</div>
<div class="col-xs-3">
<input id="plan" type="text" name="plan" class="form-control input-md" value="">
</div>
</div>
</form>
Assuming you're using JQuery, try this code:
// JQuery
$("#subscription").on('change', function(){
$('#plan').val($(this).val());
});
// Vanilla JS
var subscription = document.getElementById('subscription');
var plan = document.getElementById('plan');
subscription.onclick = function(){
plan.value = this.value;
}

Better way to change id's of controls using jquery

I have the following form that renders from a django model_formset. It starts with one form and some static controls (like date etc).The form set fields are inside the 'form-wrapper' div
<form action="/customer/images/1/upload_xray" method="post" id="xrayform" enctype="multipart/form-data">
<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="1"><input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"><input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000">
<input type="hidden" name="csrfmiddlewaretoken" value="LI1L39J1C7P4tQeqfJhL5CBuW283FmOI">
<div class="form-group">
<label for="date">Date</label>
<input id="date" type="text" name="date" class="form-control input-sm datepicker input-append date" readonly="">
</div>
<div class="form-group">
<label for="id_title">Title</label>
<select class="form-control input-sm" id="id_title" name="title">
<option value="" selected="selected">---------</option>
<option value="Observation">Observation</option>
<option value="Initial">Initial</option>
<option value="Progress">Progress</option>
<option value="Final">Final</option>
<option value="Post Treatment">Post Treatment</option>
</select>
</div>
<hr class="divider">
<div class="form-wrapper">
<div class="form-group">
<label for="id_form-0-image">Image</label>
<input id="id_form-0-image" name="form-0-image" type="file">
</div>
<div class="form-group">
<label for="id_form-0-type">Type</label>
<select class="form-control input-sm" id="id_form-0-type" name="type">
<option value="" selected="selected">---------</option>
<option value="xray">X-ray Image</option>
<option value="internal">Intraoral Image</option>
<option value="external">Extra-oral Image</option>
<option value="model">Model</option>
</select>
</div>
<div class="form-group">
<label for="id_form-0-desc">Desc</label>
<select class="form-control input-sm" id="id_form-0-desc" name="form-0-desc">
<option value="" selected="selected">---------</option>
<optgroup label="Xray" />
<option value="PA Ceph">PA Ceph</option>
<option value="Lateral Ceph">Lateral Ceph</option>
<option value="Panoramic">Panoramic</option>
<optgroup label="Interior oral">
<option value="Anterior Occlution">Anterior Occlution</option>
<option value="Anterior Occlusion Relaxed">Anterior Occlusion Relaxed</option>
<option value="Overjet Right">Overjet Right</option>
<option value="Overjet Left">Overjet Left</option>
<option value="Right Occlusion">Right Occlusion</option>
<option value="Left Occlusion">Left Occlusion</option>
<option value="Upper Occlusal">Upper Occlusal</option>
<option value="Lower Occlusal">Lower Occlusal</option>
<optgroup label="External oral" />
<option value="Frontal">Frontal</option>
<option value="Lateral Right">Lateral Right</option>
<option value="Lateral Left">Lateral Left</option>
<option value="Oblique smile Right">Oblique smile Right</option>
<option value="Oblique smile Left">Oblique smile Left</option>
<option value="Frontal smile">Frontal smile</option>
<option value="Oblique Right">Oblique Right</option>
<option value="Oblique Left">Oblique Left</option>
<optgroup label="Model"/>
<option value="Model Upper Occlusal">Model Upper Occlusal</option>
<option value="Model Lower Occlusal">Model Lower Occlusal</option>
<option value="Model Right Buccal">Model Right Buccal</option>
<option value="Model Left Buccal">Model Left Buccal</option>
<option value="Model Anterior Dental">Model Anterior Dental</option>
</select>
</div>
</div>
</form>
<div class="row">
<button class="btn btn-sm btn-success pull-right" id="add-form">+</button>
</div>
The add button adds a new form-wrapper element and increments by one the proper input fields so the model_formset of django to function correctly. Each new form-wrapper element consists of a delete button to delete it. On deletion javascript corrects the id's and values again for the formset to function correctly. I have made it work, but uses to much .each methods. Do u think is a better way to do that?
javascript
$(document).on('click','.delete', function (e){
e.preventDefault();
var forms;
var index = parseInt($(this).prop('id')) - 1;
var formWrapper = $(".form-wrapper")[index];
formWrapper.remove();
forms = $(".form-wrapper");
$("#id_form-TOTAL_FORMS").val(parseInt($("#id_form-TOTAL_FORMS").val()) - 1);
forms = $('.form-wrapper');
forms.each(function (index, item){
var form_groups = $(item).children('.form-group');
form_groups.each(function (index2, item2){
controls = $(item2).children();
controls.each(function(index3, item3){
var id = $(item3).prop('id');
parts = id.split('-');
parts[1] = String(index);
id = parts.join('-');
});
});
});
$('button.delete').each(function(index, item){
var id = parseInt($(item).prop('id'));
id = index + 2; //First start button starts with id=2 as in "delete 2nd form"
console.log('id after '+id);
$(item).prop('id', id);
});
});
Basicaly take the formwrappers to know how many forms are there, take each children (form-group) and then each children(control elements) and change their id's. Not having any trouble in speed yet, it works great, but don't like it's cleanness.
You can use .attr() like
$('button.delete').attr('id', function (index, item) {
return index + 2;
});
Demo: Fiddle

Categories

Resources