angularJs button click in form erroneously refreshing page - javascript

I am trying to implement on click add a new input field.So, There are 2 buttons to add and remove input box after clicking on add button it should add a set of the input box and on clicking remove button it should remove the particular input box. But on Clicking "add" it only adds 1 input field and refreshes the whole page and the form data of that page is showing in the search bar but on the other side "remove" button works fine. Both the functions are right I guess but I don't understand what is wrong? What do I do? I don't want add button to refresh the page and showing data in the search bar. And it must add many no of input boxes after clicking on it. What needs to be done here. please help!!
Here is my code:
index.php
<form method="post">
<div class="form-group " >
<input type="text" placeholder="Campaign Name" class="form-control c-square c-theme input-lg" name="camp_name"> </div>
<div class="row col-md-12">
<div class="form-group col-md-6">Start Date
<input type="date" placeholder="start date" class="form-control c-square c-theme input-lg" name="start_date">
</div>
<div class="form-group col-md-6">End Date
<input type="date" placeholder="end date" class="form-control c-square c-theme input-lg" name="end_date"> </div>
</div>
<div class="row col-md-12">
<div class="form-group">
<label for="inputPassword3" class="col-md-8 control-label">Select Store</label>
<div class="col-md-6 c-margin-b-20">
<select class="form-control c-square c-border-2px c-theme" multiple="multiple" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
</div>
</div>
<div class="row col-md-12" ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<label for="inputPassword3" class="col-md-1 control-label">Elements</label>
<div class="form-group col-md-3 ">
<input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="ele">
</div>
<label for="inputPassword3" class="col-md-1 control-label">Quantity</label>
<div class="form-group col-md-3" >
<select class="form-control c-square c-border-2px c-theme" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
<button class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square"
ng-click="addNewChoice()" >
add
</button>
<button ng-show="$last" ng-click="removeChoice()"
class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >
Remove
</button>
</fieldset>
</div>
</div>
</div>
<div class="form-group">
<input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">
</div>
<input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit">
</form>
angular script
<script type="text/javascript">
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>

The default type of a button element is submit. That is the reason your form gets submitted. In order to avoid this behaviour you can set the type to button as in the below code.
References w3.org
Reference Html Standard
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form method="post">
<div class="form-group " >
<input type="text" placeholder="Campaign Name" class="form-control c-square c-theme input-lg" name="camp_name"> </div>
<div class="row col-md-12">
<div class="form-group col-md-6">Start Date
<input type="date" placeholder="start date" class="form-control c-square c-theme input-lg" name="start_date">
</div>
<div class="form-group col-md-6">End Date
<input type="date" placeholder="end date" class="form-control c-square c-theme input-lg" name="end_date"> </div>
</div>
<div class="row col-md-12">
<div class="form-group">
<label for="inputPassword3" class="col-md-8 control-label">Select Store</label>
<div class="col-md-6 c-margin-b-20">
<select class="form-control c-square c-border-2px c-theme" multiple="multiple" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
</div>
</div>
<div class="row col-md-12" ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<label for="inputPassword3" class="col-md-1 control-label">Elements</label>
<div class="form-group col-md-3 ">
<input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="ele">
</div>
<label for="inputPassword3" class="col-md-1 control-label">Quantity</label>
<div class="form-group col-md-3" >
<select class="form-control c-square c-border-2px c-theme" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
<button type="button" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square"
ng-click="addNewChoice()" >
add
</button>
<button type="button" ng-show="$last" ng-click="removeChoice()"
class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >
Remove
</button>
</fieldset>
</div>
</div>
</div>
<div class="form-group">
<input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">
</div>
<input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit">
</form>
Hope this helps :)

Related

How can I convert form data with multiple sections to json

I am trying to save data in html form as json. But only my last row is saved. The reason for this is probably because the names of the inputs in the two sections are the same.
But I want the json file like this:
{"name":"Name1","surname":"Surname1","gender":"f","birthDay":"15","birthMonth":"1","birthYear":"1995"},
{"name":"Name2","surname":"Surname2","gender":"m","birthDay":"20","birthMonth":"2","birthYear":"2020"}
But now output is:
{"name":"Name2","surname":"Surname2","gender":"m","birthDay":"20","birthMonth":"2","birthYear":"2020"}
function handleFormSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const formJSON = Object.fromEntries(data.entries());
console.log(JSON.stringify(formJSON))
}
const form = document.querySelector('#example-form');
form.addEventListener('submit', handleFormSubmit);
<div class="container py-4">
<form id="example-form">
<div class="row">
<div class="col-md-12 p-0">
<div class="col-md-12 form_field_outer p-0" id="app">
<div class="row form_field_outer_row">
<div class="form-group col-md-2">
<input class="form-control w_90" id="name" name="name" placeholder="Name" type="text" value="" /></div>
<div class="form-group col-md-2">
<input class="form-control w_90" id="surname" name="surname" placeholder="Surname" type="text" value="" /></div>
<div class="form-group col-md-2">
<select class="form-control" id="gender" name="gender"><option disabled="disabled" selected="selected">Gender</option>
<option value="f">Female</option>
<option value="m">Male</option>
<option value="n">None.</option></select></div>
<div class="form-group col">
<input class="form-control w_90" id="birthDay" maxlength="2" name="birthDay" placeholder="Day" type="text" value="" /></div>
<div class="form-group col">
<select class="form-control" id="birthMonth" name="birthMonth">
<option disabled="disabled" selected="selected">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
<div class="form-group col">
<input class="form-control w_90" id="birthYear" maxlength="4" name="birthYear" placeholder="Year" type="text" value="" /></div>
</div>
<br>
<div class="row form_field_outer_row">
<div class="form-group col-md-2">
<input class="form-control w_90" id="name" name="name" placeholder="Name" type="text" value="" /></div>
<div class="form-group col-md-2">
<input class="form-control w_90" id="surname" name="surname" placeholder="Surname" type="text" value="" /></div>
<div class="form-group col-md-2">
<select class="form-control" id="gender" name="gender"><option disabled="disabled" selected="selected">Gender</option>
<option value="f">Female</option>
<option value="m">Male</option>
<option value="n">None.</option></select></div>
<div class="form-group col">
<input class="form-control w_90" id="birthDay" maxlength="2" name="birthDay" placeholder="Day" type="text" value="" /></div>
<div class="form-group col">
<select class="form-control" id="birthMonth" name="birthMonth">
<option disabled="disabled" selected="selected">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
<div class="form-group col">
<input class="form-control w_90" id="birthYear" maxlength="4" name="birthYear" placeholder="Year" type="text" value="" /></div>
</div>
</div>
</div>
</div>
<br>
<div class="col-md ml-0 mt-3 py-3">
<div class="col-md-12">
<button type="submit" id="submitId" class="btn btn-success float-right "><i class="fa fa-check-circle"></i> Submit</button>
</div>
</div>
</form>
</div>
How can I solve this?
Thanks for answers.
You have to have unique id and name values to your form elements.
So change the two occurences of:
<input id="surname" name="surname">
to something like this:
<input id="surname_0" name="person[0][surname]">
And the second occurence:
<input id="surname_1" name="person[1][surname]">
(I removed all other attributes to improve readability for my answer)

Getting all form values and keys in 1 object [duplicate]

I have an HTML form, it's a pretty simple form, there's only 4 values that are required. It looks like this.
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// log our form object
console.log(formData)
event.target.reset()
})
<form id="heatmap-form">
<div class="form-row text-center">
<div class="form-group col">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
</div>
<div class="form-group col">
<label for="unit">Unit</label>
<span class="asterisk_input"></span>
<input name="unit" type="text" class="form-control" id="unit" placeholder="C, F, %, hPa etc" required>
</div>
<div class="form-group col">
<label for="height">Height</label>
<span class="asterisk_input"></span>
<input name="height" type="text" class="form-control" id="height" placeholder="In CM format" required>
</div>
<div class="form-group col">
<label for="startTime">Start time</label>
<span class="asterisk_input"></span>
<input name="startTime" type="datetime-local" class="form-control" id="startTime" placeholder="time" required>
</div>
</div>
<button id="optional-button" type="button" class="text-center my-4 btn btn-large btn-secondary">Show optional parameters</button>
<div id="optional-form" class="hidden form-row text-center optional-form">
<div class="form-group col-md-2">
<label for="endTime">End Time</label>
<input name="endTime" type="datetime-local" class="form-control" id="endTime">
</div>
<div class="form-group col-md-2">
<label for="maxValue">Max value</label>
<input name="maxValue" type="text" value=0 class="form-control" id="maxValue">
</div>
<div class="form-group col-md-2">
<label for="minValue">Min value</label>
<input name="minValue" type="text" value=0 class="form-control" id="minValue">
</div>
<div class="form-group col-md-2">
<label for="frameAmount">Number of frames</label>
<input name="frameAmount" type="text" value=10 placeholder="10" class="form-control" id="frameAmount">
</div>
<div class="form-group col-md-2">
<label for="translation">Translation</label>
<input name="translation" type="text" class="form-control" id="translation" placeholder="x">
</div>
<div class="form-group col-md-2">
<label class="text-center" for="linearInterpolation">Power of linear interpolation</label>
<input name="linearInterpolation" type="text" value=5 class="form-control" id="linearInterpolation">
</div>
<div class="form-group col-md-2">
<label for="omitted">list of omitted sensors</label>
<input name="omitted" type="text" class="form-control" id="omitted" placeholder="format eg. L4, L3, etc" value="">
</div>
</div>
<div class="d-flex flex-row justify-content-center">
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</div>
</form>
And here is my JavaScript $form.addEventListener('submit', (event) => { event.preventDefault() const formData = new FormData(event.target) // log our form object console.log(formData) event.target.reset() })
In my console log, why aren't I getting my form data object with properties and values on it that are set to the name value of my inputs as keys and values of the inputs as values? Instead I'm just getting an empty form data object.
Your naming convention of $form is common to indicate the use of jQuery. If that is the case, then you don't have a proper jQuery reference to your form and, even if you did, you aren't making a proper jQuery configuration of the event callback.
Even if you are not using jQuery, then $form isn't a proper reference to your form, which has an id=heatmap-form.
Also, you don't get your actual form field values directly from a FormData object. You have to access the data with one of the many properties/methods of a FormData instance.
let $form = document.querySelector("form");
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// Loop over the key/value pairs contained in the FormData object
// the .entries() method returns an enumerable for us to loop over
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]); // Get the key and the value
}
event.target.reset();
})
<form id="heatmap-form">
<div class="form-row text-center">
<div class="form-group col">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
</div>
<div class="form-group col">
<label for="unit">Unit</label>
<span class="asterisk_input"></span>
<input name="unit" type="text" class="form-control" id="unit" placeholder="C, F, %, hPa etc" required>
</div>
<div class="form-group col">
<label for="height">Height</label>
<span class="asterisk_input"></span>
<input name="height" type="text" class="form-control" id="height" placeholder="In CM format" required>
</div>
<div class="form-group col">
<label for="startTime">Start time</label>
<span class="asterisk_input"></span>
<input name="startTime" type="datetime-local" class="form-control" id="startTime" placeholder="time" required>
</div>
</div>
<button id="optional-button" type="button" class="text-center my-4 btn btn-large btn-secondary">Show optional parameters</button>
<div id="optional-form" class="hidden form-row text-center optional-form">
<div class="form-group col-md-2">
<label for="endTime">End Time</label>
<input name="endTime" type="datetime-local" class="form-control" id="endTime">
</div>
<div class="form-group col-md-2">
<label for="maxValue">Max value</label>
<input name="maxValue" type="text" value=0 class="form-control" id="maxValue">
</div>
<div class="form-group col-md-2">
<label for="minValue">Min value</label>
<input name="minValue" type="text" value=0 class="form-control" id="minValue">
</div>
<div class="form-group col-md-2">
<label for="frameAmount">Number of frames</label>
<input name="frameAmount" type="text" value=10 placeholder="10" class="form-control" id="frameAmount">
</div>
<div class="form-group col-md-2">
<label for="translation">Translation</label>
<input name="translation" type="text" class="form-control" id="translation" placeholder="x">
</div>
<div class="form-group col-md-2">
<label class="text-center" for="linearInterpolation">Power of linear interpolation</label>
<input name="linearInterpolation" type="text" value=5 class="form-control" id="linearInterpolation">
</div>
<div class="form-group col-md-2">
<label for="omitted">list of omitted sensors</label>
<input name="omitted" type="text" class="form-control" id="omitted" placeholder="format eg. L4, L3, etc" value="">
</div>
</div>
<div class="d-flex flex-row justify-content-center">
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</div>
</form>
You want to make yourself familiar with the FormData API. Use formData.entries() to access these:
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// log our form object
console.log(formData.entries().next().value)
event.target.reset()
})
<form id="$form">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</form>

html required in form not working with issues in modal

I have a modal where i put my form inside. Now, my problem is, when i click the button of my onclick="regpatient()" button, the required will pop-up but when i look at it in console, the data was submited by a post because of my onlick function. How can i do this?
Here is my modal:
<div class="modal-body">
<form class="form-horizontal" id="frm_patientreg">
<div class="form-group">
<label class="control-label col-sm-3" for="pfname">First Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pafname" name="pafname" placeholder="First name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmname">Middle Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pamname" name="pamname" placeholder="Middle name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="plname">Last Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="palname" name="palname" placeholder="Last name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="paddress">Address:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="paaddress" name="paaddress" placeholder="Address" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pcontact">Contact #:</label>
<div class="col-sm-7">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control" id="pacontact" name="pacontact" placeholder="Contact number" maxlength="11" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pbdate">Birthdate:</label>
<div class="col-sm-5">
<div class="input-group date" data-provide="datepicker">
<input type="text" class="form-control" id="pabdate" name="pabdate" placeholder="Birthdate" required>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="page">Age:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paage" name="paage" placeholder="Age" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pheight">Height:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paheight" name="paheight" placeholder="Height (cm)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pweight">Weight:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paweight" name="paweight" placeholder="Weight (kg)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="psex">Sex:</label>
<div class="col-sm-5">
<select class="form-control" id="psex" name="psex">
<option value="0">--- SELECT OPTION ---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmartiastat">Civil Status:</label>
<div class="col-sm-5">
<select class="form-control" id="pmartialstat" name="pmartialstat">
<option value="0">--- SELECT OPTION ---</option>
<option value="Single">Single</option>
<option value="Living common law">Living common law</option>
<option value="Married">Married</option>
<option value="Widowed">Widowed</option>
<option value="Separated">Separated</option>
<option value="Divorced">Divorced</option>
</select>
</div>
</div>
</div><!-- modal-body -->
<div class="modal-footer">
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
</form>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div><!-- modal-footer -->
</div><!-- modal-content -->
and here is my ajax where it fires when the button in footer of my modal is clicked:
function regpatient() {
var a = $('#psex').val();
var b = $('#pmartialstat').val();
if(a == "0" || b == "0") {
alert("Please select option");
}
else {
$.ajax({
url: siteurl+"sec_myclinic/addpatient",
type: "POST",
data: $('#frm_patientreg').serialize(),
dataType: "JSON",
success: function(data) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
}
If I understand your problem right you want to stop the button's default submit action and only use your onclick script. Try this:
onclick="regpatient(event)"
and
function regpatient(event) {
event.preventDefault();
...
Edit
The required fields are not getting validated by the onclick function. Some checks like this for the required values should help stop the ajax call.
if (!$('#pafname').val()) {
return alert('Please fill in all required fields.');
}
// ajax code here ...
Use this
<button value="button" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
instead of this
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>

Jquery Get iD and Value and display URL parameters

I used below HTML & JS script to get ID and value of each element inside the form.
But, i need to get all these value and like below and added to the URL on top when user submit the form to redirect booking engine.
Getting below output on console.log:
someaction?fromLocation=undefined&departureDate=undefined&tripType=undefined&returnDate=undefined
HTML:
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" form="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="Departure Date" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="Return Date" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
JS:
var url = $("#bookingForm").attr("action") + "?";
var urlElements = [];
$("#bookingForm").find('.form-group').each(function(){
urlElements.push($(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value") || $(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value"));
});
urlElements = urlElements.join("&");
url += urlElements;
console.log(url);
Just fix your name attributes to match your IDs, and use .serialize():
$("form").on("submit", function(event) {
event.preventDefault();
var form = $(this);
var url = form.attr('action') + '?' + form.serialize();
console.log(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="departureDate" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="returnDate" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
As a bonus, it will properly URL-encode your values.
Try like this
var $input = $(this).find('.form-control');
urlElements.push($input.attr("id") + "=" + $input.val());

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