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>
Related
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.
I wrote some HTML form where the form should alert when nothing is submitted. I started with creating this for the names. As expected, the message 'You must provide your full name!' shows when no name is entered. However, the message also shows up when the names are actually entered…
{% extends "layout.html" %}
{% block main %}
<!-- http://getbootstrap.com/docs/4.1/content/typography/ -->
<h1 class="mb-3">Form</h1>
<!-- http://getbootstrap.com/docs/4.1/components/forms/ -->
<form action="/form" method="post" id="form_id">
<div class="form-row names">
<div class="form-group col-md-3 name1">
<label for="inputFirstname">First name</label>
<input type="name" autofocus class="form-control" id="inputFirstname" placeholder="First name">
</div>
<div class="form-group col-md-3 name2">
<label for="inputLastname">Last name</label>
<input type="name" class="form-control" id="inputLastname" placeholder="Last name">
</div>
</div>
<div class="form-row clubs">
<div class="form-group col-md-3">
<label cfor="inlineFormCustomSelect">Club preference</label>
<select class="custom-select" id="inlineFormCustomSelect">
<option disabled selected value> -- select an option -- </option>
<option value="1">PSV</option>
<option value="2">Ajax</option>
<option value="3">Feyenoord</option>
<option value="4">De Graafschap</option>
<option value="5">RKVV Bergeijk 2</option>
</select>
<div class="invalid-feedback">Please choose one option</div>
</div>
</div>
<div class="form-group">
<label for="PFoot">Preferred foot</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="right">
Right
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="left">
Left
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="zweipotig">
Zweipotig
</label>
</div>
<!-- http://getbootstrap.com/docs/4.1/components/buttons/ -->
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<script>
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('.name1').value) {
alert('You must provide your full name!');
return false;
}
return true;
}
</script>
{% endblock %}
As expected, the message 'You must provide your full name!' shows when no name is entered. However, the message also shows up when the names are actually entered…
You are using the wrong selector (.name1) which refers a div element, not the input you are thinking. Try #inputFirstname
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('#inputFirstname').value) {
alert('You must provide your full name!');
return false;
}
else if(!document.querySelector('[name=algorithm]:checked')){
alert('You must provide Preferred foot!');
return false;
}
return true;
}
<form action="/form" method="post" id="form_id">
<div class="form-row names">
<div class="form-group col-md-3 name1">
<label for="inputFirstname">First name</label>
<input type="name" autofocus class="form-control" id="inputFirstname" placeholder="First name">
</div>
<div class="form-group col-md-3 name2">
<label for="inputLastname">Last name</label>
<input type="name" class="form-control" id="inputLastname" placeholder="Last name">
</div>
</div>
<div class="form-row clubs">
<div class="form-group col-md-3">
<label cfor="inlineFormCustomSelect">Club preference</label>
<select class="custom-select" id="inlineFormCustomSelect">
<option disabled selected value> -- select an option -- </option>
<option value="1">PSV</option>
<option value="2">Ajax</option>
<option value="3">Feyenoord</option>
<option value="4">De Graafschap</option>
<option value="5">RKVV Bergeijk 2</option>
</select>
<div class="invalid-feedback">Please choose one option</div>
</div>
</div>
<div class="form-group">
<label for="PFoot">Preferred foot</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="right">
Right
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="left">
Left
</label>
<label class="form-check-label">
<input type="radio" id="PFoot" name="algorithm" value="zweipotig">
Zweipotig
</label>
</div>
<!-- http://getbootstrap.com/docs/4.1/components/buttons/ -->
<button class="btn btn-primary" type="submit">Submit</button>
</form>
The class name1 is div, not an input. Then you have to use (".name1 input") in the querySelector
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('.name1 input').value) {
alert('You must provide your full name!');
return false;
}
return true;
}
in my case it's worked
<script>
document.querySelector('form').onsubmit = function() {
if (!document.querySelector('#inputFirstname').value) {
alert('You must provide your full name!');
return false;
}
return true;
}
I already have form object like this in a variable:
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form">...</form>
How can I serialize it using jQuery only?
JS
function submit_form(form){
var se = String(form);
console.log($(se).serialize());
}
Form in Console
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form"><input type="hidden" id="input1" value="1"><div class="form-group">
<label for="recipient-name" class="col-form-label">Link</label>
<input type="text" class="form-control" id="input1" value="FIRST LINK"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Category</label><select class="form-control"><option>cat 1</option><option value="1">cat 1</option><option value="2">cat 2</option><option value="3">cat 3</option><option value="4">cat 4</option></select></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Detail</label>
<input type="text" class="form-control" id="input1" value="ASDASDASASF"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Created_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Updated_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21"></div><div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="submit_form(this.form);" class="btn btn-primary">Send message</button>
</div></form>
HTML
<button type="button" onclick="submit_form(this.form);" class="btn btn-primary">Send message</button>
</div>';
$return .= '</form>';
There are two issues in your code. Firstly you're sending a Form Element object to the submit_form() function which you then attempt to coerce to a string. This is the source of your error. If you skip that step, the jQuery object can be created correctly.
Secondly to serialise data in a form all the fields must have name attributes on them, so you need to amend your HTML. Once those points are addressed, the logic works fine.
Also note that I changed the button to a submit so that the form is submit and then hooked a an unobtrusive event handler to listen for that event on the form. You should not be using on* event attributes at all as they are incredibly outdated.
$('#modal_form1').on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form"><input type="hidden" id="input1" value="1">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Link</label>
<input type="text" class="form-control" id="input1" value="FIRST LINK" name="link"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Category</label>
<select class="form-control" name="category">
<option>cat 1</option>
<option value="1">cat 1</option>
<option value="2">cat 2</option>
<option value="3">cat 3</option>
<option value="4">cat 4</option>
</select>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Detail</label>
<input type="text" class="form-control" id="input1" value="ASDASDASASF" name="detail"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Created_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21" name="created_at"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Updated_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21" name="updated_at"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="send_message">Send message</button>
</div>
</form>
Im using bootstrap 4, html, css, js the lot when trying to do this.
I'm trying to show some text boxes depending on the choice of the select option.
So if I choose "adadelta" I'd like to have only 4 specific text boxes(number type) show and everything else remain hidden. Should mention that the below form in hosted in a popover window which works fine, as such I've only included the form itself.
I've tried various javascript examples for similar situations but its just not showing the text boxes even when I try document.getElementById etc.
Any suggestions would be much appreciated.
<form>
<div class="form-group">
<label for="epochEdit">Epochs:</label>
<input type="number" class="form-control" id="epochEdit">
<label for="batchEdit">Batch Size:</label>
<input type="number" class="form-control" id="batchEdit">
</div>
<div class="form-group">
<label for="optChoose">Optimizer:</label>
<select class="form-control" id="optChoose">
<option selected>Open this menu</option>
<option value="sgd">sgd</option>
<option value="adadelta">adadelta</option>
<option value="rmsprop">rmsprop</option>
<option value="adam">adam</option>
<option value="adamax">adamax</option>
<option value="adagrad">adagrad</option>
<option value="nadam">nadam</option>
</select>
</div>
<div class="form-group">
<fieldset disabled>
<div class="form-group">
<label for="disabledNote">Note:</label>
<input type="text" id="disabledNote" class="form-control" placeholder="Optimizers will use keras default values!">
</div>
</fieldset>
<label for="lr">Learning Rate:</label>
<input type="number" class="form-control" id="lr">
<label for="rho">Rho:</label>
<input type="number" class="form-control" id="rho">
<label for="epsilon">Epsilon:</label>
<input type="number" class="form-control" id="epsilon">
<label for="decay">Decay:</label>
<input type="number" class="form-control" id="decay">
<label for="b1">Beta #1:</label>
<input type="number" class="form-control" id="b1">
<label for="b2">Beta #2:</label>
<input type="number" class="form-control" id="b2">
<label for="sDecay">Schedule Decay:</label>
<input type="number" class="form-control" id="sDecay">
<label for="moment">Momentum:</label>
<input type="number" class="form-control" id="moment">
<label for="nesterov">Nesterov:</label>
<input type="checkbox" class="form-check-input" id="nesterov">
</div>
<button id="subSettings" class="bg-color-3 btn btn-info"> Submit </button>
</form>
Try this
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var el = '<label for="lr">Learning Rate:</label>\
<input type="number" class="form-control" id="lr">\
\
<label for="rho">Rho:</label>\
<input type="number" class="form-control" id="rho">\
\
<label for="epsilon">Epsilon:</label>\
<input type="number" class="form-control" id="epsilon">\
\
<label for="decay">Decay:</label>\
<input type="number" class="form-control" id="decay">\
\
<label for="b1">Beta #1:</label>\
<input type="number" class="form-control" id="b1">\
\
<label for="b2">Beta #2:</label>\
<input type="number" class="form-control" id="b2">\
\
<label for="sDecay">Schedule Decay:</label>\
<input type="number" class="form-control" id="sDecay">\
\
<label for="moment">Momentum:</label>\
<input type="number" class="form-control" id="moment">';
function select() {
var optSel = $("#optChoose").val();
appendControls(optSel);
}
function appendControls(num) {
$('#elcontainer').empty();
if (num == "adadelta") {
$('#elcontainer').append(el);
}
}
</script>
</head>
<body>
<div class="container">
<h2>Form control: input</h2>
<p>The form below contains two input elements; one of type text and one of type password:</p>
<div class="form-group">
<label for="epochEdit">Epochs:</label>
<input type="number" class="form-control" id="epochEdit">
<label for="batchEdit">Batch Size:</label>
<input type="number" class="form-control" id="batchEdit">
</div>
<div class="form-group">
<label for="optChoose">Optimizer:</label>
<select class="form-control" id="optChoose" onchange="select();">
<option value="">Open this menu</option>
<option value="sgd">sgd</option>
<option value="adadelta">adadelta</option>
<option value="rmsprop">rmsprop</option>
<option value="adam">adam</option>
<option value="adamax">adamax</option>
<option value="adagrad">adagrad</option>
<option value="nadam">nadam</option>
</select>
</div>
<div class="form-group">
<fieldset disabled>
<div class="form-group">
<label for="disabledNote">Note:</label>
<input type="text" id="disabledNote" class="form-control"
placeholder="Optimizers will use keras default values!">
</div>
</fieldset>
<div id="elcontainer"></div>
<label for="nesterov">Nesterov:</label>
<input type="checkbox" class="form-check-input" id="nesterov">
</div>
<button id="subSettings" class="bg-color-3 btn btn-info"> Submit</button>
</div>
</body>
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'));
})
});