Use Select Element Without Dropdown - javascript

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.

Related

How do I create list the intended way I want

I have the following scripts:
Does calculation for me and lists them
function fromPortIdChange() {
fromportid = $('#fromPortId').val();
console.log(fromportid);
portIdRange(fromportid,toportid);
listOfNumbers=[];
}
function toPortIdChange() {
toportid = $('#toPortId').val();
console.log(toportid);
portIdRange(fromportid,toportid);
listOfNumbers=[];
}
function portIdRange(fromportid, toportid) {
fromportid = $('#fromPortId').val();
toportid = $('#toPortId').val();
fromportidlastvalueSliced = fromportid.slice(-5);
interfaceNameLength = fromportid.length-1;
interfaceName = fromportid.substring(0, interfaceNameLength);
console.log("length: " +interfaceNameLength);
console.log("interface name: " +interfaceName);
fromportidlastvalue = fromportidlastvalueSliced.split('/')[2]
console.log(fromportidlastvalue+ " FROM port id");
console.log("range is " +fromportid+ " to " +toportid);
toportidlastvalueSliced = toportid.slice(-5);
toportidlastvalue = toportidlastvalueSliced.split('/')[2]
console.log(toportidlastvalue+ " TO port id");
console.log(typeof(toportidlastvalue));
calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName);
}
function calculateRange(fromportidlastvalue, toportidlastvalue, interfaceName) {
fromportidlastvalue = parseInt(fromportidlastvalue);
toportidlastvalue = parseInt(toportidlastvalue);
console.log(fromportidlastvalue + " type is " + typeof(fromportidlastvalue));
console.log(toportidlastvalue + " type is " + typeof(toportidlastvalue));
currentValue = fromportidlastvalue;
while(currentValue<=toportidlastvalue)
{
console.log(currentValue);
listOfNumbers.push(interfaceName+currentValue);
currentValue++;
}
$('#port_range').val(listOfNumbers);
}
Here is the html involved:
The part it is on the page and the one I am going to clone
<div id = first>
<div class="port">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="subnet_bit">From Port ID</label>
<select id="fromPortId" class="custom-select mb-3" onchange="fromPortIdChange();">
<option selected>Select</option>
{% for items in righttable %}
<option value={{items.0}}>{{items.0}}</option>
{%endfor%}
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="subnet_bit">To Port ID</label>
<select id="toPortId" class="custom-select mb-3" onchange="toPortIdChange();">
<option selected>Select</option>
{%for items in righttable%}
<option value={{items.0}}>{{items.0}}</option>
{%endfor%}
</select>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<div class="text-sm-center">
<br />
<button type="button" class="btn btn-outline-success btn-rounded"><i class="dripicons-plus" onclick="addButton();"></i></button>
</div>
</div>
</div>
</div>
</div>
</div>
The additional div i created for the clone to be in
<div id="morerows"></div>
This part is for the textarea
<p style="color:red;">If certain interface not needed, delete it</p>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="port_range">Port range</label>
<textarea class="form-control" id="port_range" rows="5"></textarea>
</div>
</div>
</div>
righttable comes from my django view
This script does the following: User choose FortyGigabitEthernet2/0/1 from the drop down of From Port ID and FortyGigabitEthernet2/0/5 from the drop down of To Port ID, it will list all the possible interface in portrange such as shown in the diagram, it lists FortyGigabitEthernet2/0/1, FortyGigabitEthernet2/0/2,FortyGigabitEthernet2/0/3,FortyGigabitEthernet2/0/4,FortyGigabitEthernet2/0/5
As you can see, there is a add button at the side. This is intended to to clone the drop down box for user to select other ports. Such as TenGigabitEthernet1/0/1 for a cloned From Port ID and TenGigabitEthernet1/0/3. So the following TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2, TenGigabitEthernet1/0/3 is add on to the existing FortyGigabitEthernet2/0/1, FortyGigabitEthernet2/0/2,FortyGigabitEthernet2/0/3,FortyGigabitEthernet2/0/4,FortyGigabitEthernet2/0/5 in the text area of Port Range
For the cloning of the drop down box:
function addButton(){
$('#first .port').clone().appendTo('#morerows')
}
Here comes the issues:
1. The add button works but i dont know is it lag or what. Sometime i have to click the add button multiple times before the cloned dropdown box appear.
2. The cloned drop down box are not working out like i want it to be. Like in the below picture. In 1st row we have FortyGigabitEthernet2/0/1 and Forty GigabitEthernet2/0/2. This is listed in the Port Range. But for the 2nd row of FortyGigabitEthernet2/0/4 and FortyGigabitEthernet2/0/5, it is not listed in the Port Range
Sorry for a very long post but is there anyway for me to achieve what I need. Appreciate if someone can help. Thanks in advance!

how to push multivalues from many element with same class or id in ajax

I have created a form , that user can append the additional column that need to that form, for example I have column name in the form , if people want to add more column name , they just press the add button , and then select element for the column name and it will be added, so it will have 2 select element with same class, but the problem is , I dont know how to send the data with ajax so django views that can get the data.Every time that I try to print the result , it will print as [] which means: failed to push the data
here's the code
html
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="btn-group">
<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</select>
<select class="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input class="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
</div>
</form>
script to append the box
<script>
function appendBox()
{
$('#test').append('<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
return false
}
</script>
<script>
function appendFilterBox()
{
$('#filtbox').append('<select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:2px"></select><select class="operator" style="width:125px;background-color:white;height:3 0px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:3px"><option> > </option><option> < </option><option> ≥ </option><option> ≤ </option><option> = </option></select><input type="text" class="parameter" style="width:150px;background-color:white;height:30px;font-size:15px;"></input>')
return false
}
</script>
Ajax to send the data
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
condition = {
'column' : $(el).find('.conditionselect').val(),
'operator' : $(el).find('.operator').val(),
'value' : $(el).find('.parameter').val()
};
data.condition.push(condition);
});
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
is this the correct way to send multivalues with ajax? it seems the data didnt send properly when django want to get the data..
heres the view if you guys curious
def list_all_data(request):
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') #ip port and user and password i hide it for privacy
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
print(request.GET.getlist('condition'))
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column = request.GET.get('condition', {}).get('column', 1)
print(column)
operator = request.GET.get('condition', {}).get('operator', 1)
print(operator)
value = request.GET.get('condition', {}).get('value', 1)
print(value)
c.execute("select "+data_name+" from "+table_name+" where "+column + operator+"'"+value+"'")
c.rowfactory = makeDictFactory(c)
columnalldata = []
columnallname = []
for rowDict in c:
columnalldata.append(rowDict[data_name])
columnallname.append(data_name)
context = {
'obj4' : columnalldata,
'column_name' : columnallname
}
return render(request,'query_result.html',context)

Vue.js 2.0 Vee Validate plugin not clearing errors after ajax call

I am working on a vue.js 2.0 project. I am using the Vee-Validate plugin. I have a form and when it submits, it makes an ajax call to my api. After the api call returns successfully, I am trying to clear my vee-validation so that I can invite another user with the same form, but it's not working at all.
I tried the method this.errors.clear() as suggested in their documentation
I have also thought that maybe its happening too fast, so I added a set timeout function for a couple seconds, but it still doesn't clear the errors.
Here is my Vue file with all related code:
<template>
<div v-if="user.first_time_login == 0 && user.stripe_check == 1">
<div class="viv-modal-overlay">
<div class="container">
<div class="viv-modal green">
<span class="modal-title" id="setup-team-top">Now let’s set up your team.</span>
<p>Your plan allows up to {{this.user.company.max_users}} users. Would you like to shoot out some team invites before we send you to the dashboard?</p>
<div class="invited-users" v-bind:class="{ show: show_invites }" v-if="show_invites">
<p>You can invite up to 4 more team members. Upgrade to add more.</p>
<ul>
<li v-for="invite in invites">
<img src="/img/icons/checkmark.svg" width="20" height="20" alt="success">
You invited {{invite.email}}.
<span class="clearfix"></span>
</li>
</ul>
<div class="team-done-adding">
I'm done adding team members.
</div>
</div>
<div class="modal-form">
<form id="setup-stripe-form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Team Member's Email<span>*</span></label>
<input type="text" name="email" v-model="newUser.email" v-validate data-vv-rules="required" class="form-control" :placeholder="'user#'+user.company.company_name.replace(/[^A-Z0-9]+/ig, '').toLowerCase()+'.com'">
<span v-show="errors.has('email')" class="error">{{ errors.first('email') }}</span>
</div>
<div class="form-group">
<label>Access to Leads and Contacts<span>*</span></label>
<select name="access_leads" v-model="newUser.access_leads" v-validate data-vv-rules="required" class="form-control">
<option value="1">they can see leads and contacts they created</option>
<option value="2">they can see all leads and contacts</option>
<option value="0">no access to leads and contacts</option>
</select>
<span v-show="errors.has('access_leads')" class="error">{{ errors.first('access_leads') }}</span>
</div>
<div class="form-group">
<label>Access to Proposals<span>*</span></label>
<select name="access_proposals" v-model="newUser.access_proposals" v-validate data-vv-rules="required" class="form-control">
<option value="1">they can see proposals they created</option>
<option value="2">they can see all proposals</option>
<option value="0">no access to proposals</option>
</select>
<span v-show="errors.has('access_proposals')" class="error">{{ errors.first('access_proposals') }}</span>
</div>
<div class="form-group">
<label>Access to Invoices<span>*</span></label>
<select name="access_invoices" v-model="newUser.access_invoices" v-validate data-vv-rules="required" class="form-control">
<option value="1">they can see invoices they created</option>
<option value="2">they can see all invoices</option>
<option value="0">no access to invoices</option>
</select>
<span v-show="errors.has('access_invoices')" class="error">{{ errors.first('access_invoices') }}</span>
</div>
<div class="form-group">
<label>Access to Projects<span>*</span></label>
<select name="access_projects" v-model="newUser.access_projects" v-validate data-vv-rules="required" class="form-control">
<option value="1">they can see projects they created</option>
<option value="2">they can see all projects</option>
<option value="0">no access to projects</option>
</select>
<span v-show="errors.has('access_projects')" class="error">{{ errors.first('access_projects') }}</span>
</div>
</div>
<div class="col-md-12 text-center">
<div class="modal-btn-pad">
<button type="submit" v-bind:class="{ disabled: adding_team_member }" class="btn btn-lg btn-green" #click="submitInviteForm">
<span class="sending-invite" v-if="adding_team_member">Sending Invite <img src="/img/preloader.svg" width="20" height="20"></span>
<span v-else>Continue</span>
</button><br>
<a class="light-link" href="#" #click="skipInviteForm">Skip this for now.</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data() {
return {
newUser: {
email: '',
access_leads: 1,
access_proposals: 1,
access_invoices: 1,
access_projects: 1
},
users_invited: 0,
invites: [],
show_invites: false,
adding_team_member: false
}
},
computed: mapState({
appLoading: state => state.appLoading,
user: state => state.user
}),
methods: {
submitInviteForm: function(e) {
e.preventDefault()
this.$validator.validateAll()
if (!this.errors.any()) {
//There are no errors, move forward...
//Add the team member to the database...
//Grab the authorized user
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
//Create the payload...
var newTeamMember = this.newUser
//Were adding a team member now so show the loader!
this.adding_team_member = true
//Create the new company and add the owner...
this.$http.post('/api/team',
{
newTeamMember: JSON.stringify(newTeamMember)
},
{
headers: {
Authorization: 'Bearer ' + authUser.access_token
}
}).then((response) => {
if(response.status === 200) {
//Assign the user to a variable
var invitedUser = response.body
//Add the user to the list of invited users
this.invites.push({email: invitedUser.email })
//Show the invite list...
this.show_invites = true
//Jump to top
location.hash = '#setup-team-top'
//reset the new user
this.newUser.email = ''
this.newUser.access_leads = 1
this.newUser.access_proposals = 1
this.newUser.access_invoices = 1
this.newUser.access_projects = 1
//Were done adding a team member so hide the loader!
this.adding_team_member = false
//Clear the validation errors
this.errors.clear()
}
}).catch(function(error){
console.log(error);
})
}
},
skipInviteForm: function(e) {
e.preventDefault()
alert('skip invite!')
}
}
}
</script>
Try to have a look at this fiddle which was extracted from this issue.
Basically, you have to call this.$validator.clean(); after you have reset the input fields of your form.

how to display all menu and submenu item in a different drop down list?

I don't know what's going on ! this code not work me properly. i don't get the error. it shows menu properly but don't show any submenu under specific menu.
Here is my code:
##Table: menus##
id name parent_id
1 Dhaka 0
2 Chitagong 0
3 Chittagong University 2
4 Dhaka University 1
5 Barisal 0
6 Chittagong University 5
##route:##
Route::get('/', 'MenuController#index');
Route::get('/sub','MenuController#subMenu');
##Model:##
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Menu extends Model
{
protected $fillable = [
'id','name','parent_id'
];
}
##Controller :##
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Menu;
class MenuController extends Controller
{
public function index()
{
$menuItem = Menu::where('parent_id', '=',0)->get();
return view('index', compact('menuItem'));
}
public function subMenu()
{
$parent = Input::get('parentID');
$sub_menu= Menu::where('parent_id','=',$parent)
->select('id','name')
->get();
return response()->json($sub_menu);
}
}
##View:##
<!--/.start add menu section-->
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Menu </strong>
</div>
<div class="panel-body">
<div class="form-horizontal">
<div class="row">
<div class="col-xs-8">
{{ Form::open(['class' => 'form-horizontal', 'role' => 'form']) }}
<div class="form-group">
<label align="right" for="name" class="control-label col-xs-2">Menu :</label>
<select class="col-md-5 input-sm" name="menu" id="menu">
#foreach ($menuItem as $menu)
<option value="{{ $menu->id }}" placeholder="choose menu">{{ $menu->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label align="right" for="child_id" class="control-label col-xs-2">Sub Menu :</label>
<select class="col-md-5 input-sm" name="child_id" id="child_id" >
</select>
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-offset-2 col-md-6">
{!! Form::submit('Save', ['class' => 'btn btn-primary add-submenu']) !!}
</div>
</div>
</div>
</div>
</div>
</div>
{{ Form::close() }}
</div>
</div>
javascript:
-------------
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#menu').on('change',function(e){
console.log(e);
var parentID= e.target.value;
$.getJSON('/sub?parentID=' + parentID, function(data){
console.log(data);
$('#child_id').empty();
$.each(data,function(index, child){
$('#child_id').append('<option value="'+child.id+'">'+child.name+'</option>');
});
});
});
});
</script>
what is the problem in this code?
Try adding id as third parameter in your relations,
public function parent()
{
return $this->belongsTo('App\Menu', 'parent_id', 'id');
}
public function children()
{
return $this->hasMany('App\Menu', 'parent_id', 'id');
}
It was a simple missing in my js file. it was a '/' problem .
There are many mistakes in your code. You just copy and paste forgot to change those values.
For doing this, I am using a separate controller and javascript.
In my VIEW
<div class="form-group">
<label align="right" for="name" class="control-label col-xs-2">Course :</label>
<select class="col-md-5 input-sm" name="name" id="name">
#foreach ($menuItem as $menu)
<option value="{{ $menu->id }}" placeholder="choose menu">{{ $menu->name }}</option>
#endforeach
</select>
</div>
For getting sub menu items, I am using Javascript
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#name').on('change',function(e){
console.log(e);
var parentID= e.target.value;
$.getJSON('/your current url/sub?parentID=' + parentID, function(data){
console.log(data);
$('#child_id').empty();
$.each(data,function(index, child){
$('#child_id').append('<option value="'+child.id+'">'+child.name+'</option>');
});
});
});
});
in my route.php I have
Route::get('your current url/sub','MyJSController#loadchild');
In my MyJSController -> loadchild function has
public function loadchild()
{
$parent = Input::get('parentID');
$sub_menu= DB::table('menus')
->where('parent_id','=',$parent)
->select('id','name')
->get();
return response()->json($sub_menu);
}
Your sub menu drop down in your VIEW should be like this
<div class="form-group">
<label align="right" for="child_id" class="control-label col-xs-2">Sub Menu :</label>
<select class="col-md-5 input-sm" name="child_id" id="child_id" >
</select>
</div>
public function create()
{
$menuItem = DB::table('menus')
->where('parent_id','=',0)
->get();
return view('menu.createmenu', compact('menuItem'));
}
Make sure you imported
use Illuminate\Support\Facades\Input;
use DB; in your controller.
One additional thing Do not use {!! Form::close() !!} these,because of security vulnerabilities. Use {{ Form::close() }}

Load <select> AngularJs in form

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

Categories

Resources