I have this that takes the value and send it to my backend along with others in a form
<select
v-model="formData.account_bank"
id="branch"
#change="getbranch"
>
<option v-for="bank in selectBank" :key="bank.id" :value="bank.code">{{
bank.name
}}</option>
</select>
but before it is sent I need to get some data to populate a second selectbox using bank.id which I should have as :value = "bank.id" in the code above.
To get the value to make the api call that populates the second selectbox I just do
var branch = document.getElementById('branch').value;
and use it in the API call.
But here I need to get the bank.id to make the first api call that populates the selectbox and still have the bank.code there as form data to submit.
I have thought about getting the key using javascript which has the bank.id. But can not figure how or a different way it should work.
One solution to this problem is to bind the entire bank object to your <select> model.
Then you can use its id to populate your other select options and its code to construct your form data payload.
For example
<select
v-model="selectedBank"
id="branch"
#change="getbranch"
>
<option v-for="bank in selectBank" :key="bank.id" :value="bank">{{
bank.name
}}</option>
</select>
data: () => ({
formData: {
// whatever you originally had here
},
selectedBank: {} // empty object or perhaps a default bank
}),
methods: {
getBranch () {
const bankId = this.selectedBank.id
// make API call, etc
},
submitForm () {
// build form data
const formData = {
...this.formData,
account_bank: this.selectedBank.code
}
// submit form, etc
}
}
See https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings
Related
I need plain/regular html form with a dropdown input field, called TYPES.
Then I need the axios code I got from a codepen, to "receive" the TYPES value, that the user selected. I don't understand how the html form input field is sent to the axios code?
The next steps are working, but I can't pass in the TYPES value. THanks
I know how to make a form.
I know php code. (( fyi. example.com/getimages.php?cat=TYPES, this is working, but I need 'types' to be the passed in value))
I'm not good at axios or javascript.
***** HTML code *****
input: <input type="text" name="TYPES" id="TYPES">
<button onclick=“findimages()">Search</button>
***** AXIOS code from a codepen *****
(function($) {
.... <other code>
const fetchImages = (count = 10) => {
axios.
get(`https://example.com/getimages.php?cat=TYPES`).
then(res => {
setImages([...images, ...res.data]);
setIsLoaded(true);
console.log(images);
});
};
.... <other code>
};
ReactDOM.render(React.createElement(Collage, null),
document.getElementById("root"));
} )( jQuery );
If the search button on the html form can "call/send/pass" the axios code AND pass in the TYPES value... all will be great!
Looks like you have some formatting/character coding issues with your example. <button onclick=“findimages()"> is using incorrect quotes ("), and is also not calling fetchImages(). Also you mentioned "dropdown input", so I'm not sure if you meant a select dropdown, or are just referring to a normal input text box. I added both for example purposes.
You can change out the exampleURL variable to pass in type_select instead of type_input if you want. This axios request will just hit an example JSON API and return {"response" : 200}, but you should see the cat variable passed in the request URL with TEST as the value.
const fetchImages = (count = 10) => {
let type_input = document.getElementById('types_input').value;
let type_select = document.getElementById('types_select').value;
// URL: 'https://example.com/getimages.php?cat=' + type_input;
let exampleURL = 'https://api.myjson.com/bins/7yftn?cat=' + type_input;
axios.
get(exampleURL).
then(res => {
console.log(res);
// setImages([...images, ...res.data]);
// setIsLoaded(true);
// console.log(images);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<select name="types_select" id="types_select">
<option value="">-Select Type-</option>
<option value="Type 1">Type 1</option>
<option value="Type 2">Type 2</option>
</select>
<br/>
<input type="text" name="types_input" id="types_input" value="TEST" />
<br/>
<button onclick="fetchImages()">Search</button>
I have a search form which has some ajax querying the database as the user types and listing similar results in a datalist. The issue I was having is as a user typed, it would continuously append a match it already found. To illustrate:
User types: "d"
Datalist: <option value = "dog">
User types: "do"
Datalist: <option value = "dog"> <option value = "dog">
User types: "dog"
Datalist: <option value = "dog"> <option value = "dog"> <option value = "dog">
I solved the issue by emptying the existing data lists on every key-up event before re-appending the current matches. It works, except that it causes the results to appear to flash in the data list as you type as it is constantly toggling between having options in the data list, having no options, then having options again. What is the better way of handling this scenario?
Current JS:
$(document).ready(function() {
$(window).on('load', function(){
var search_input = $("#listing-search-bar")
if (search_input) {
search_input.keyup(function(e){
autocomplete(e);
});
};
function autocomplete(el) {
var input = el.target;
var min_chars = 0;
if (input.value.length > min_chars) {
$.ajax({
type: 'GET',
url: "/listings/search",
data: {"query" : input.value},
dataType: "json"
}).done(function(response) {
// Delete existing results to prevent same result appending multiple times
$("#cities").empty();
response.forEach( function(city) {
// Append all matching cities to drop down
$("#cities").append(`<option value="${city}"></option>`);
});
});
};
};
});
});
You can simply check if element exist before adding it to the DOM:
if ( !$('#cities option[value="'+city+'"]').length )
$("#cities").append(`<option value="${city}"></option>`);
I am trying to show the initial value of a array of objects like this:
tableStyes[
{Id: 1, style: "blabla1},
{Id: 2, style: "blabla2"}
]
basicly i am using a computer method to give me the array from vuex store
tableStyles () {
return this.$store.getters.getTableStyles
},
i am doing the select this way:
<select class="form-control" v-model="table.tableStyle">
<option v-for="(item,key) in tableStyles" :value="item.Id">
{{ item.style }}
</option>
</select>
i want to get the value based on the id, i mean i want to get the text associated to the id, and the id is table.tableStyle, that is 1 at the begin that should be the selected item, but somehow it doesn't work :/.
Any help?
You need no computed method to display data from vuex store.
v-model="table.tableStyle" sets the first displayed item, if it is initialized with anything that is not included in the array, no item will be selected before you select one manually.
Try:
data:{
return {
...
table.tableStyle: this.$store.getters.getTableStyles[0]
}
}
I dont know if this works in data section.
So I have the following code:
<div class="form-group">
<label for="backings_select">Backing Single</label>
<select class="form-control"
required
[(ngModel)]="selectedBacking"
name="backings_select"
(ngModelChange)="storeValueRedux($event, count)">
<option *ngFor="let backing of backings" [ngValue]="backing.id" [selected]="backings.length === 1">{{backing.name}}</option>
</select>
It populates a select box with results from a service call, if the array length is 1, it auto selects the only option available, this works fine.
However, by default the select box uses a value from the component as its default value.
So when the service call is made, if the array only has a length of one, the value of the model is changing, but because its being auto selected (not by user input) the storeValueRedux event is not firing.
However, if the array has more than one entry, and then is selected by a user, the function is called and works as required. Is there anyway to trigger ngModelChange in the instance that backings.length = 1?
You can't use a condition inside your method calls in HTML but you can use change and handle the condition inside your method as below
<select class="form-control"
required
[(ngModel)]="selectedBacking"
name="backings_select"
(change)="storeValueRedux($event, count)">
<option *ngFor="let backing of backings" [ngValue]="backing.id"
[selected]="backings.length === 1">{{backing.name}}</option>
selectedBacking:any{};
backings:any[]=[
{id:1, name:'a'},
{id:2, name:'a'}
]
storeValueRedux(a,b){
if(this.backings.length!=1){
console.log(this.selectedBacking);
console.log(a,b);
}
}
LIVEDEMO
The service that returned my backings was an observable, so I modified the subscribe from:
.subscribe(
results => {this.backings = results},
error => console.log(error),
);
to:
.subscribe(
results => {this.backings = results, this.testBackingLength()},
error => console.log(error),
);
And then added:
testBackingLength(){
/* If the length of the arrau is only one, the template auto selects it
and does not trigger ngOnChange, so we need to manually trigger it here,
this function is called from the subscribe a few lines up */
if (this.backings.length === 1) {
this.storeValueRedux(this.backings[0]['id'], this.count)}
}
So each time my service is called, it tests the length of the array. If the length of the array is 1, it will auto call my function.
I have a select list that looks like this:
<select class="form-control">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Once a user selects an option, I would like to display a comment only where db_Type = the value of the selected option:
foreach (var note in Model.GetNotes)
{
<div class="current-note-container">
<h5 class="note-comment"><b>Description:</b><br/> #note.db_Comment.Where(note.db_Type == /* Selected Index */)</h5>
</div>
}
I'm not really sure how I can accomplish this using razor, or how to mix javascript in to get the job done.
This is not exact, but I'm think you're looking for something like this
<select class="form-control" onchange="GetComment(this.value)">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Add this to the script of your razor view
function GetComment(ID)
{
var parameters = {};
parameters["ListID"] = ID;
$.ajax
({
type: "GET",
data: parameters,
url: "/MyController/GetComment",
success: function (message) {
$('#note-comment').val(message);
},
error: function () {
alert("error");
}
});
}
And finally something like this to your controller
[HttpGet]
public JsonResult GetComment(int ListID)
{
return Json(Mylist[ListID].Comment);
}
Razor is a server side code and so you can not combine it with client script like what you are planning to.
Instead use jQuery to listen to the selection changed event and pass (GET/POST) newly selected value back to controller and query database and get the required comment.
jQuery inside View (pseudo code):
$( "#ddlOptions" ).change(function() { //assuming ddlOptions is the Id of select list
var selectedOptionId= $(this).val();
$.get('#Url.Action("ActionName","ControllerName")', { id: selectedOptionId},
//You can use $.get(...) or $.post(...) based on action method type.
function (data) {
//Display/append the comment received to a container(div/span etc)
});
});
Controller code (pseudo code)
public JsonResult Get(int id)
{
//Query database here based on id to get the comment
//e.g: db_comment.where(com=>com.id==id).FirstOrDefault();
return Json(comment,JsonRequestBehavior.AllowGet);
}
Hope this provide you some idea.