Load <select> AngularJs in form - javascript

I'm trying to load my states, where it should be with a state already informed. But I cannot carry it, how can I do this?
It works when it is an input that's okay.
but when I will show again in a form, he is not showing the state in my
In my database the data is like: Arizona
My html code:
<div class="form-group">
<label class="col-sm-4 col-md-4 control-label " for="state">State | {{even.state}}</label>
<div class="col-sm-4 col-md-8">
<span class="block input-icon ">
<select class="form-control" ng-model="even.state" ng-options="state.state for state in states" ng-change="change(even.state)">
<option value="">State</option>
</select>
</span>
</div>
Function to getState
var getState = function () {
dirAPI.getState().success(function (data,status) {
$scope.states = data[0];
})
};
Function to Load general data
var loadEvent = function () {
dirAPI.getEvent().success(function (data) {
$scope.event = data;
});
};
This is a example, when a I load the form, the Arizona did
enter image description here
Thanks

Related

Use Select Element Without Dropdown

I currently have a pricing page on my website that uses the <select> and <option> html elements to let users select a pricing plan.
This is the code for the plan select dropdown:
<select name="plan" class="form-control" id="subscription-plan">
#foreach ($plans as $key => $plan)
<option value="{{ $key }}">{{ $plan }}</option>
#endforeach
</select>
And here is what the form looks like:
I would like to add 2 cards containing the plan info that can be selected by the user and act the same way as the dropdown, except without it being a dropdown. The id="subscription-plan" is important because it sends the corresponding plan the user selects to the Stripe API, which bills the user's credit card for the amount set in Stripe. Does anyone know how I could achieve this?
I would like to do something like this (but without the dropdown styling):
<select name="plan" class="form-control" id="subscription-plan">
#foreach ($plans as $key => $plan)
<option value="{{ $key }}">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h5 class="card-title text-muted text-uppercase text-center">Monthly</h5>
<h6 class="card-price text-center">$8.44<span class="period">/month</span></h6>
</div>
</div>
</option>
#endforeach
</select>
UPDATE:
I have tried this:
#foreach ($plans as $key => $plan)
<div class="col-6">
<label>
<input type="radio" name="plan" value="{{ $key }}" class="card-input-element" id="subscription-plan">
<div class="panel panel-default card-input">
<div class="panel-heading">{{ $plan }}</div>
<div class="panel-body">2 Memorials</div>
</div>
</label>
</div>
#endforeach
This code works and gives me the desired effect of having selectable cards, but the Stripe API now only receives the "monthly" plan even if the user submits their credit card details after selecting the "yearly" plan. This is because now both inputs have id="subscription-plan".
Stripe JavaScript:
const stripe = Stripe('{{ env('STRIPE_KEY') }}');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
const plan = document.getElementById('subscription-plan').value;
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.handleCardSetup(
clientSecret, cardElement, {
payment_method_data: {
billing_details: { name: cardHolderName.value }
}
}
);
if (error) {
// Display "error.message" to the user...
} else {
// The card has been verified successfully...
console.log('handling success', setupIntent.payment_method);
axios.post('subscribe',{
payment_method: setupIntent.payment_method,
plan : plan
}).then((data)=>{
location.replace(data.data.success_url)
});
}
});
UPDATE 2:
I have replaced const plan = document.getElementById('subscription-plan').value; with var plan = document.querySelector('input[name="plan"]:checked').value;. Now I get Uncaught TypeError: Cannot read property 'value' of null in console when I try to submit.
This should be doable by just iterating over the plans to create the cards and not using select at all. You could address the card selection with onclick handlers or by treating the cards as radio buttons sort of like you see here: https://codepen.io/stefanzweifel/pen/RNvGwz
Then instead of using the select value, you'd use the radio value.
you can simply use size attribute to select
<select name="plan" class="form-control" size=3 id="subscription-plan">
<option value="1">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h5 class="card-title text-muted text-uppercase text-center">Monthly</h5>
<h6 class="card-price text-center">$8.44<span class="period">/month</span></h6>
</div>
</div>
</option>
<option value="2">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h5 class="card-title text-muted text-uppercase text-center">Daily</h5>
<h6 class="card-price text-center">$0.44<span class="period">/day</span></h6>
</div>
</div>
</option>
<option value="3">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h5 class="card-title text-muted text-uppercase text-center">Yearly</h5>
<h6 class="card-price text-center">$80.44<span class="period">/year</span></h6>
</div>
</div>
</option>
</select>
I solved the JavaScript side of this issue on my own. What I did was change var plan = document.querySelector('input[name="plan"]:checked').value; into just var plan;. Then, I added:
$('input:radio').on('click', function(e) {
plan = this.value;
});.
Now, the form properly submits the correct plan based on the option the user selects to the Stripe API. This was a surprisingly difficult task for me to get this form to work without the use of the <select> and <option> elements. Here is the finished working code:
HTML
<div class="col-6">
<label>
<input type="radio" name="plan" value="monthly" class="card-input-element" checked="checked">
<div class="panel panel-default card-input">
<div class="panel-heading">Monthly</div>
</div>
</label>
</div>
<div class="col-6">
<label>
<input type="radio" name="plan" value="yearly" class="card-input-element">
<div class="panel panel-default card-input">
<div class="panel-heading">Yearly</div>
</div>
</label>
</div>
JavaScript
<script src="{{ asset('js/jquery-3.4.1.min.js') }}"></script>
<script>
window.addEventListener('load', function() {
const stripe = Stripe('{{ env('STRIPE_KEY') }}');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
var plan;
$('input:radio').on('click', function(e) {
plan = this.value;
});
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.handleCardSetup(
clientSecret, cardElement, {
payment_method_data: {
billing_details: { name: cardHolderName.value }
}
}
);
if (error) {
// Display "error.message" to the user...
} else {
// The card has been verified successfully...
console.log('handling success', setupIntent.payment_method);
axios.post('subscribe',{
payment_method: setupIntent.payment_method,
plan : plan
}).then((data)=>{
location.replace(data.data.success_url)
});
}
});
});
</script>
More experienced programmers may have known how to achive this from the start, but I guess we all have to learn somehow. Thank you all for your help.

dropdown selected on page load angular

Here is a dropdown :
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Role</label>
<select ng-model="User_Role" class="dropdown form-control" ng-options="t.RoleName for t in rollist track by t.ID">
<option value="" >-- Choose Role --</option>
</select>
</div>
</div>
the dropdown bind here:
$scope.rolelist = function () {
var role = UserService.getroleInfo();
role.then(function (d) {
//debugger;
$scope.rollist = d.data;
}, function (err) {
//debugger;
alert("Some Error Occured ");
});
}
how do selected the dropdown dynamic value in angularjs??
here is the dynamic dropdown <option label="Admin" value="1" >Admin</option>
can any one tell me how do i selected when page load using angular
Try this on your success call back :)
$scope.rollist = d.data;
$scope.User_Role=$scope.rollist[0]; // or $scope.User_Role=$scope.rollist[0].RoleName
here I used direct return in service instead of that you can use your http request in service
var app = angular.module('testApp',[]);
app.service('UserService',function(){
this.getroleInfo=function(){
return [{ID:1,RoleName:"Admin"},{ID:2,RoleName:"User"}];
};
});
app.controller('testCtrl',['$scope','UserService',function($scope,UserService){
/*+role.then(function (d) {
//debugger;
$scope.rollist = d.data;
}, function (err) {
//debugger;
alert("Some Error Occured ");
});*/
//place this below code in inside of your role.then(function(){})
$scope.rollist= UserService.getroleInfo();
$scope.User_Role={ID:2,RoleName:"User"};//here place your dynamic data
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Role</label>
<select ng-model="User_Role" class="dropdown form-control" ng-options="t.RoleName for t in rollist track by t.ID">
<option value="" >-- Choose Role --</option>
</select>
</div>
</div>
</div>
You could use ng-init in the div and call a function that sets the ng-model value. for example: ng-init="assignValue()", and in the controller:
$scope.assignValue = function(){
$scope.User_Role = $scope.rollist[0]
}

Using jQuery validate on select list

I have the following javascript:
var $step = $(".wizard-step:visible:last"); // get current step
var validator = $("#WizardForm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function ()
{
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
This is successfully validating all my input fields but upon trying to apply a similar method to the select type using code:
$step.find("select").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
My HTML is as follows:
<div class="wizard-step" id="step1" visibility="hidden" style="display: block;">
<div class="row">
<div class="col-md-6 column ui-sortable">
<div class="form-group">
<label class="control-label col-md-4" for="Tariff_Type">Tariff Type</label>
<div class="col-md-8">
<select style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="TariffType" name="TariffType" class="form-control input required">
<option value="">Please Select Tariff Type</option>
<option value="keypad account">Say Hello To Budget Extra Discount</option>
<option value="bill pay account">Standard 24H</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="TariffType" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
</div>
How can I ensure that a TariffType value is selected using this method?
Try the .valid() method instead...
if (! $(this).valid()) { ...

Dropdowns not bound to ng-model in Angular

Something very basic I am missing but I am not able to figure out . I have three fields in a view , two of them are dropdowns.
<div class="form-group row">
<label for="GroupName" class="col-sm-4 form-control-label">Group Name : </label>
<div class="col-sm-8">
<input ng-model="referenceEdit.groupName" id="GroupName" class="form-control" type="text">
</div>
</div>
<div class="form-group row">
<label for="GroupType" class="col-sm-4 form-control-label">Group Type : </label>
<div class="col-sm-8">
<select name="selGroupType" id="selGroupType" class="form-control" ng-change="referenceEdit.populateGroupTypeDetails(selGroupType)" ng-options="groupType.value for groupType in referenceEdit.groupTypes track by groupType.id" ng-model="referenceEdit.groupType"></select>
</div>
</div>
<div class="form-group row">
<label for="GroupAssignmentMethod" class="col-sm-4 form-control-label">Group Assignment Method : </label>
<div class="col-sm-8">
<select name="selGroupAssignmentMethod" id="selGroupAssignmentMethod" class="form-control" ng-options="assignmentMethod.id for assignmentMethod in referenceEdit.assignmentMethods track by assignmentMethod.value" ng-model="referenceEdit.assignmentMethod"></select>
</div>
</div>
Now in controller , I am getting the results for these drop downs in this way :
var row_details = GroupMembershipReferenceServices.getReferenceDataRow();
referenceDataDropDownService.getDropDown(REFERENCE_DATA_CONSTANTS.GROUP_TYPE).success(function (result) {
$scope.referenceEdit.groupTypes = result;
$scope.referenceEdit.groupype = row_details.grp_typ;
}).error(function (result) {
alert("Unable to retrieve dropdown values");
});
referenceDataDropDownService.getDropDown(REFERENCE_DATA_CONSTANTS.GROUP_ASSIGNMENT_METHOD).success(function (result) {
$scope.referenceEdit.assignmentMethods = result;
$scope.referenceEdit.assignmentMethod = row_details.grp_assgnmnt_mthd;
}).error(function (result) {
alert("Unable to retrieve dropdown values");
});
Problem is values are getting populated , like
and we are displaying the values accordingly. The results are like
[0] {id:"1",value:"Chapter Non-Event"}
[1] {id:"2",value:"NHQ Campaign"}
But the row_details.grp_typ is "NHQ Campaign".
Even though I assign it , the drop down option is not selected accordingly .
Have I to assign it to the value property only ? What am I missing ?
use ng-repeat instead of ng-options
eg:
<select name="selGroupType" id="selGroupType" class="form-control" ng-change="referenceEdit.populateGroupTypeDetails(selGroupType)" ng-model="referenceEdit.groupType">
<option value="-1">---</option>
<option ng-repeat="groupType.value for groupType in referenceEdit.groupTypes track by groupType.id" value="{[{groupType.id}]}"> {[{groupType.value}]} </option></select>

How to remove models that are no longer bound to dom

I have a form that has a bunch of logic about which elements to show using ng-if. For example I might have a country drop down and if USA is selected it will show the state drop down which was conditioned upon an ng-if for country. Perhaps this was not the best way to do it so if there are recommendations for a different approach for the next project that will be appreciated but I need to finish this project with few major modifications.
The problem is if a user selects a country say USA and then a state, and then selects a different country. The state is still selected within the model. So how would I go about removing the state field. There are deeply nested ng-if's (think about 4-5 levels).
Example
<div ng-if="root.originCountry == 'PAK'">
<div ng-if="root.productType == 'Custom Football Jersey' || root.productType == 'Sublimated Football Jersey'">
<div class="control-group">
<label class="control-label" for="productTypeType">{{root.productType}} Type</label>
<div class="controls">
<select ng-model="root.productTypeType" ng-options="type for type in pakJerseyTypeList" bs-select required></select>
</div>
</div>
<div class="ordered-container">
<div ng-if="root.productTypeType">
<div class="control-group">
<label class="control-label" for="bodyColor">Body Color</label>
<div class="controls">
<select ng-model="root.bodyColor" ng-options="color for color in bodyColorList" bs-select required></select>
</div>
</div>
<div ng-if="root.bodyColor == 'Other'">
<div class="control-group no-count">
<label class="control-label" for="bodyColorPmsCode">Body Color PMS Code</label class="control-label no-count">
<div class="controls">
<input type="text" ng-model="root.bodyColorPmsCode" name='bodyColorPmsCode' required>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
You can utilize the ng-change directive to your advantage; set one on a parent select box and implement its handler to clear the values of any child select box depending on it.
Here's a quick snippet illustrating how to achieve this:
<select
ng-model="selectedCountry"
ng-options="country for country in countries"
ng-change="clearCity()">
</select>
<select
ng-model="selectedCity"
ng-if="isJapanSelected()"
ng-options="city for city in japanCities"
ng-change="setCity(selectedCity)">
</select>
var app = angular.module('myModule', []);
app.controller('MainCtrl', function($scope) {
$scope.countries = ['Japan', 'Brasil', 'England'];
$scope.selectedCountry = 'Brasil';
$scope.selectedCity = '';
$scope.japanCities = ['Tokyo', 'Yokohama', 'Osaka']
$scope.isJapanSelected = function() {
return $scope.selectedCountry == 'Japan';
};
$scope.getCity = function() {
return $scope.selectedCity;
};
$scope.setCity = function(city) {
$scope.selectedCity = city;
};
$scope.clearCity = function() {
if (!$scope.isJapanSelected()) {
$scope.selectedCity = '';
}
};
});
Live demonstration on plunker

Categories

Resources