Change required field form when option is selected - javascript

I have a form like below
<form>
<div class="6 op" style="display: none;">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
In the code above, required is in service and capacity. I want to know how to add required to notes field automatically only when I choose Hotspot option in service field.
Do you know how to do that ?
Thank you

You can add onchange event handler to select option and as a param pass the value of the selected option. In this case when the value is hotspot you can use setAttribute to add the attribute required to the textarea else set it to false or remove it using removeAttribute. Also id of dom elements need to be unique
let txtArea = document.getElementById('exampleFormControlTextarea1');
function changeService(val) {
if (val.toLowerCase() === 'hotspot') {
txtArea.setAttribute('required', true)
} else {
txtArea.setAttribute('required', false)
}
}
<form>
<div class="6 op" style="">
<div class="form-group"><label for='exampleFormControlSelect1'>Service</label>
<select onchange='changeService(this.value)' class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect2" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>

Check this simple example below ,
using jquery , if someone select specific role , code toggle class and toggle REQUIRED properties on chosen element
$('select#role').change(function(){
let role = $(this).children("option:selected").val();
if (role == 0 ){
$('.detailed').removeClass("detailed");
$('#employee').prop('required',true);
}
else{
$('#staff').addClass("detailed");
$('#employee').prop('required',false);
}
}); // close $('select#role').change(function(){

let el = document.querySelector("#exampleFormControlSelect1");
el.addEventListener("change",(e)=>{
if(el.options[el.selectedIndex].value == "Hotspot" ) {
document.querySelector("#exampleFormControlTextarea1").setAttribute("required","");
} else {
document.querySelector("#exampleFormControlTextarea1").removeAttribute("required");
}
});
<form>
<div class="6 op" style="">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
First of all, remove the display:none property from first div. Then check the codes above.

$('#serviceToggle').on('change', function () {
var data = $(this).val();
if (data == 'hotspot') {
$('#notes').prop('required', true);
} else {
$('#notes').prop('required', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="serviceToggle">Service</label>
<select class="form-control" id="serviceToggle" required>
<option></option>
<option value="fiber">Fiber</option>
<option value="hotspot">Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1">
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="notes">Notes</label>
<textarea class="form-control" id="notes" rows="3"></textarea>
</div>
<input type="submit" value="Submit">
</form>

You can achieve this using jQuery. You need to set the field to required on the onChange event of dropdown.
// Perform some code on the change event of a dropdown
$("#exampleFormControlSelect1").change(function () {
var selected = $(this).children("option:selected").val();
// Get selected value and save it in selected variable
console.log(selected);
if(selected == "Fiber"){
//check the selected value and set the field to required
console.log('i am here');
// Set capacity input to required if value if Fiber
// $("#capacity").attr('required',true);
// Set Notes field to required if value if Fiber
$("#exampleFormControlTextarea1").attr('required',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="6 op">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="text" class="form-control" id="capacity" placeholder="example: 1">
<select class="form-control" id="exampleFormControlSelect1">
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
In the above example, the Notes field will become required, if you select Fiber in Service Dropdown.

Related

Collect input data and put in one object for create JSON

I meet things which I don't understand. I collect all data from form and put to object, but I cannot understand why in that object one key is empty string and value also empty string? Please explain, if you can where is my mistake and why its work like that. And how is better and short way make validation if user not fill anyone input and push submit, and result should be alert("Empty form")
<form id="form">
<div class="mb-3">
<label class="form-label">Email address</label>
<input name="email" type="email" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">First name</label>
<input name="firstName" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Last name</label>
<input name="lastName" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Nickname</label>
<input name="nickname" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Password</label>
<input name="password" type="password" class="form-control">
</div>
<div class="mb-3 ">
<label class="form-label">Select an option</label>
<select name="option" class="form-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
<div class="mb-3 ">
<label class="form-label">Type in your message</label>
<textarea
class="form-control"
placeholder="Leave a comment here"
style="height: 100px"
name="message"
></textarea>
</div>
<div class="mb-3">
<label class="form-label">Default file input example</label>
<input name="file" class="form-control" type="file">
</div>
<div class="mb-3 form-check">
<input name="terms" type="checkbox" class="form-check-input">
<label class="form-check-label" >Согласен с условиями</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
const myForm = document.getElementById("form");
myForm.addEventListener("submit", element => {
element.preventDefault();
const keyValues = {};
for(let key of myForm) {
keyValues[key.name] = key.value;
}
localStorage.setItem("Item", JSON.stringify(keyValues));
window.location = 'result-submit.html';
})
Try typing the following code and see what you will find in the console :
myForm.addEventListener("submit", (element) => {
element.preventDefault();
const keyValues = {};
console.log(myForm);
for (let key of myForm) {
console.log(key, key.name, key.value);
keyValues[key.name] = key.value;
}
localStorage.setItem("Item", JSON.stringify(keyValues));
// window.location = "result-submit.html";
});
You will notice that it is the button that causes this problem, and to bypass it, try adding this condition :
if (key.type !== "submit") {...}
So your loop will look like this
for (let key of myForm) {
if (key.type !== "submit") {
keyValues[key.name] = key.value;
}
}
As for checking the input, the best way on the client side is to use the input attribute built in html : https://www.w3schools.com/html/html_form_attributes.asp
The submit button is part of the form and is sent along with the form data. Give the button a name so it doesn't appear as an empty key
Add required and name attributes to your required inputs and let the browser do the initial validation. If you want to do further validity you can use JS, perhaps by using the FormData interface.
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
function handleSubmit(e) {
e.preventDefault();
const FD = new FormData(form);
for (const input of FD) {
console.log(input);
}
}
<form id="form">
<div>
<label>Email address</label>
<input name="email" type="email" required>
</div>
<div>
<label>First name</label>
<input name="firstName" type="text" required>
</div>
<div>
<label>Password</label>
<input name="password" type="password" required>
</div>
<div>
<label>Select an option</label>
<select name="option" required>
<option selected disabled value="">Select option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
<div>
<label>Type in your message</label>
<textarea name="comment" required placeholder="Leave a comment here"></textarea>
</div>
<div>
<label>Согласен с условиями</label>
<input name="terms" type="checkbox" required>
</div>
<button type="submit">Submit</button>
</form>

Set text field min and max value based on the option selected in previous dropdown

I have a drop down and a text box next to it.
When some value is selected in the dropdown, the textbox should allow min and max characters based on the selected option.
Suppose I select option 1, then the textbox next to it should allow minimum 10 characters and max 16 characters.
How to achieve it?
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0" disabled> </option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="id" type="number" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" maxlength="20" />
</div>
</div>
</div>
you have to change a little your code
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0/0" disabled> </option>
<option value="10/16">name1</option>
<option value="20/32">name2</option>
<option value="30/48">name3</option>
<option value="40/64">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="id" type="text" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" maxlength="20" />
</div>
</div>
</div>
and jQuery
$('#prooftype').change(function(){
var tmp = $(this).val().split('/');
$('input#id').attr('minlength',tmp[0]).attr('maxlength',tmp[1]);
})
If you pass the the option value of 12/16 to the backend, obviously the data will reflect. I think you need something like this:
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0/0" disabled> </option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="inputid" type="text" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" maxlength="20" />
</div>
</div>
</div>
And your JQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var selectedopt;
$('#prooftype').change(function(){
selectedopt= $(this).val();
//Add your condition here, and check the selected option value:
if(selectedopt== "name1")
{
//Set input min and max value based on the selected option value.
$('#inputid').attr('minlength','10').attr('maxlength','16');
}
elseif(selectedopt== "name2")
{
$('#inputid').attr('minlength','20').attr('maxlength','25');
}
// And so on........
})
</script>

Div show/hide not working?

The show or hide not working. the div keeps on showing, even if i select an option which should hide it.
However if i console log, it gives me respective show/hide output.
The following are sample code:
$('#categoryt').change(function() {
selection = $(this).val();
console.log(selection);
if (selection == "2") {
console.log("show");
$('#Subjectd').show();
} else {
console.log("hide");
$('#Subjectd').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="insert.php">
<div class="form-group" id="formdiv">
<label for="Category">Category</label>
<select class="custom-select" id="categoryt">
<option selected>Choose Role</option>
<option value="1">Student</option>
<option value="2">Teacher</option>
<option value="3">Animation Designer</option>
<option value="4">Content Verifier</option>
<option value="5">Admin</option>
</select>
</div>
<div class="form-group" id="formdiv">
<label for="Name">Name</label>
<input type="text" id="Name" name="Name" placeholder="Name" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Schoold">
<label for="School">School</label>
<input type="text" id="School" name="School" placeholder="School" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Subjectd">
<label for="Subject">Subject</label>
<input type="text" id="Subject" name="Subject" placeholder="Subject" class="form-control" />
</div>
<div class="form-group" id="formdiv" id="Classd">
<label for="Class">Class</label>
<input type="text" id="Class" name="Class" placeholder="Class" class="form-control" />
</div>
You have two id's in your element
<div class="form-group" id = "formdiv" id = "Subjectd">
change to
<div class="form-group" id = "Subjectd">
Please remember that your element can only have one ID and that your ID must be unique in the entire page. Meaning you should never have two elements that share the same ID. Class, on the other hand, can be shared by multiple elements and you can have multiple classes on a single element.
i.e
<div class="form-group class_two class_three">

Display extra form fields if dropdown is selected

I'm trying to make two extra form fields appear if the user selects 'Yes' from a dropdown. If the user does not select 'Yes' from the dropdown, then the two extra fields are not required and are disabled, however if 'Yes' is selected these fields must be filled in before form submission. I have this so far, however it's not working. If anyone could point out the issue it would be greatly appreciated.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
JSFiddle
checkIfYes needs to be defined before the HTML that references it.
I would also recommend changing the select onclick event to onchange so that it only gets called when the user actually changes he value
See updated fiddle : Updated Fiddle
<script>
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
</script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onchange='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>

How to get attributes values on change of select dropdown

I have a select dropdown of addresses on change of select dropdown I need to get option attributes and paste them in input fields.
Here is what I tried so far TryFiddle
I have data attributes as data-address, data-city, data-zipcode and data-country for each option, when I select any option I want that options data-attr to be pasted in respective input boxes;
here is my code
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
alert('change');
$("#bill_address").val($(this).attr('data-address'));
$("#bill_city").val($(this).attr('data-city'));
$("#bill_zipcode").val($(this).attr('data-zipcode'));
$("#bill_country").val($(this).attr('data-country'));
})
})
Html code
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
</div>
I dont know whats going wrong it should work, please provide any suggestions
This is one of the rare places where jQuery doesn't do much for you, your best bet is to use the select box's native selectedIndex property and options collection:
// Get the selected HTMLOptionElement
var opt = this.options[this.selectedIndex];
E.g.: (updated fiddle)
$(document).ready(function() {
$('#saved_billing_addresses').on("change", function() {
var opt = this.options[this.selectedIndex];
if (opt) {
opt = $(opt);
$("#bill_address").val(opt.attr('data-address'));
$("#bill_city").val(opt.attr('data-city'));
$("#bill_zipcode").val(opt.attr('data-zipcode'));
$("#bill_country").val(opt.attr('data-country'));
}
})
});
Try it..
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($('option:selected', this).data('address'));
$("#bill_city").val($('option:selected', this).data('city'));
$("#bill_zipcode").val($('option:selected', this).data('zipcode'));
$("#bill_country").val($('option:selected', this).data('country'));
})
});
.hide-it{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
</div>
You have some typos:
$(this) within change event is not $(this).find(':selected')
.data('address') could be used for attr('data-address')
event handler within the same event handler is useless
whenever possible you can cache selected elements
My proposal is:
$(function () {
$('#saved_billing_addresses').on("change", function(e){
var jqSelectedOption = $(this).find(':selected');
$("#bill_address").val(jqSelectedOption.data('address'));
$("#bill_city").val(jqSelectedOption.data('city'));
$("#bill_zipcode").val(jqSelectedOption.data('zipcode'));
$("#bill_country").val(jqSelectedOption.data('country'));
});
});
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
This is what you need.
$('#saved_billing_addresses').on("change",function(event){
const $this = this.options[this.selectedIndex];
$("#bill_address").val($this.getAttribute('data-address'));
$("#bill_city").val($this.getAttribute('data-city'));
$("#bill_zipcode").val($this.getAttribute('data-zipcode'));
$("#bill_country").val($this.getAttribute('data-country'));
});
You can also use the find to get the data attributes
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($(this).find(':selected').data('address'));
$("#bill_city").val($(this).find(':selected').data('city'));
$("#bill_zipcode").val($(this).find(':selected').data('zipcode'));
$("#bill_country").val($(this).find(':selected').data('country'));
})
});
Why you added two on Change events functions,Please remove second one. Try this..
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($(this).find('option:selected').attr('data-address'));
$("#bill_city").val($(this).find('option:selected').attr('data-city'));
$("#bill_zipcode").val($(this).find('option:selected').attr('data-zipcode'));
$("#bill_country").val($(this).find('option:selected').attr('data-country'));
})
});

Categories