vue.js select v-model value not in $(element).val() - drop-down-menu

I'm trying to load form values from a cache on route load so if someone navigates from one route to another they don't lose their settings. Checkboxes and text inputs are working correctly. Only selects seem to have an issue.
Here's the element:
<select id="client" name="client[]" multiple="" v-model="chosen_clients">
<option v-for="client in clients" v-bind:client="client" :value="client.id">#{{ client.name }}</option>
</select>
First, I check the cache and update the address bar:
beforeCreate: function(){
if(sessionStorage.getItem('invoiceable')){
router.push({ path: '/invoiceable?'+sessionStorage.getItem('invoiceable')});
}
},
Then I bind the data to the address bar:
data: function(){
return {
chosen_clients: this.$route.query['client[]'] ? (Array.isArray(this.$route.query['client[]']) ? this.$route.query['client[]'] : [this.$route.query['client[]']]) : [],
}
},
Later, after mounted, I want to fetch data and update the address bar, but there's a problem:
var data = $('#invoiceable-form').serialize();
//This information does not match
console.log(this.chosen_clients); //This is correct
console.log($('#client').val(); //This is empty, even though visually, the select has selected options
Eventually, $('#client').val() has the correct value (meaning the visibly selected options appear as part of the serialized form. I know this because I have console.logs set up on beforeUpdate less than a second after the value is not present in .serialized it shows up without any interaction with the select. Even if I manually set $('#client').val([2,12]); before I .serialize() the correct values aren't there. I can force the issue by manually adding data to the result of .serialize, but that feels hacky.

#Roy J was right. The select options weren't loaded yet.

Related

Node RED custom node, populate dynamic values in dropdown. Show selected value on opening node. Support for same type of multiple nodes

Node red custom node, 1 drop-down field shows values dynamically from a database.
User can select any value & save the node.
When user reopens same node, drop-down should show the previously selected value.
It works in one node only.
But if we put multiple nodes of same type it shows same value in all nodes.
The reason is to store the selected value global variable is used outside oneditprepare function.
When user wants to use many same types of nodes then the global variable shows same value in different nodes because of the global variable.
How to solve this issue?
I looked at How to show the previously selected values(dynamic) on a dropdown after oneditsave in Node-Red? as well.
The other way, I think to solve this issue is below.
Node shows value in side bar info. We can get value from that and assign it to dropdown. But the problem in that case is we have to write code in oneditprepare to assign value to dropdown.
And Side bar property gets value after complete execution of oneditprepare.
Thanks.
Code for above description:
<div class="form-row">
<label for="node-input-toolId"><i class="fa fa-tag"></i> Tool Id</label>
<select id="node-input-toolId" style="width:125px !important" required>
<option value=""></option>
</select>
</div>
<script type="text/javascript">
var globalToolId;
defaults:{
toolId: {value:"", required:true} // along with some other fields
}
oneditprepare:
// ajax call to database to fetch values
$.ajax({
url: solrUrl,
method: 'GET',
dataType: "json",
contentType: "application/json",
success: function(data) {
for(var i=0;i<list.length;i++) // Assume list has all values fetched from db
{
var dbVal = list[i];
var newOption = $('<option value="'+dbVal+'">'+dbVal+'</option>'); // Add all values to the dropdown list
$("#node-input-toolId").append(newOption);
}
// This will show default toolId selected previously
if(globalToolId != null && globalToolId != '')
{
$("#node-input-toolId").val(globalToolId);
}
}
});
// On change of toolId2, save selected Tool Id in global variable.
$('#node-input-toolId2').change(function(e){
globalToolId = $('#node-input-toolId').val();
});
The normal way to solve this would be to define a regular node property to store the selection in. That way each node can have its own selected value.
Yes that means you need to have some code in oneditprepare in order to set the selected value from the dynamically generated list - but that's just how its done; it is not a 'problem'. Besides, if you're doing it with a global variable, you must have some code to do the same task.

How to initialize select2 that uses a query for data when I already have a value

I have a view with 2 select boxes which are "cascading". A user selects a value from the first box and the second is populated based on the new value. This is done with Select2's query option, and works fine on the first load of the page. However, when I post the page and then render it, both select boxes already have values (say A and 1), but the dependent checkbox is not initialized. I have done a few things with initSelection and it didn't help much, sometimes just getting me into an loop.
What I am trying to do is this:
Link the two boxes
When the first box changes, reset the data in the second box and clear the value
When the page is re-drawn, and a value has already been selected (e.g. response to POST)
Go to server and get the data
Show the correct value for the existing <input type='hidden' value='xxx'>
if that value exists in the list, of course
if not, set value to blank (optionally fire jquery validation
Searching/constant querying is not needed. Just load once on change
I am thinking about changing this entire, so if this is really the wrong way to go about this, I'd be happy to know.
// caches ajax result based on `data`
// if data has been requested before, retrieves from the cache (nothing special)
// based on other code that did it all inside the `query` function directly
var locationsCache = new AjaxCacheClassThing( {
url: '...',
data: function() { return { masterId: $('#ParentBox').val(); } }
});
$(function() {
$('#ParentBox').change(function () {
$('#ChildBox').select2('data', null);
});
$('#ChildBox').select2({
query: locationsCache.queryCallbackHandler,
selectOnBlur: true,
});
});
The HTML uses the standard MVC helpers, and the HTML is rendered just fine.
#Html.DropDownListFor(m => m.ParentBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.ChildBox)
Here is how this scenario goes:
ParentBox is required (no empty option)
First Load: there is no value selected
Open the DependentBox
Ajax query issues correctly
Dropdown populates as expected
Second Load
Master box selects value just fine
ChildBox hidden input has value="xx" just fine
It does not show a selected item
Clicking dropdown populates the box as expected (from cache)
After some time spent, and lots of time on here and other places, I figured out how this all works (at least some parts of it!). Way simpler than I thought it was, but still surprised this isn't supported out of the box in some way. Seems like a really common request.
query and ajax and initselection aren't that useful in this scenario
They query each time a the search box changes (not desired)
They complicate everything
You need to init the select2 manually
If you use { data: ... } then you don't need query or ajax
Set the "value" on your hidden input if you have one, so the item gets selected
You have to recreate the box when you get new data
It is really simple. This is the simplest case, using no extra features or attributes
Javascript:
$(function() {
$('#ParentBox').change(createChildSelect2);
createChildSelect2();
});
function createChildSelect2() {
makeAjaxRequest( function( newData ) {
$('#ChildBox').select2( { data: newData } );
});
}
function makeAjaxRequest(callback) {
// calls a.jsp?parentId={?} and then the callback when done.
jQuery.ajax({
url: 'a.jsp', dataType: 'json',
data: function() {
return { parentId: $("#parentBox").val() };
}
})
.done(function (data) {
callback(data);
});
}
The HTML is all the same. A type=text and type=hidden both work:
<select id="ParentBox">
<option ... >
<option ... >
<select>
<input id="ChildBox" type="hidden" class="input-medium" value="1"/>
Or using Razor:
#Html.DropDownListFor(m => m.MasterBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.DependentBox)

Form select box in Backbone Marionette

I'm trying using Backbone.Marionette to build an application. The application gets its data through REST calls.
In this application I created a model which contains the following fields:
id
name
language
type
I also created an ItemView that contains a complete form for the model. The template I'm using is this:
<form>
<input id="model-id" class="uneditable-input" name="id" type="text" value="{{id}}"/>
<input id="model-name" class="uneditable-input" name="name" type="text" value="{{name}}" />
<select id="model-language" name="language"></select>
<select id="model-type" name="type"></select>
<button class="btn btn-submit">Save</button>
</form>
(I'm using Twig.js for rendering the templates)
I am able to succesfully fetch a model's data and display the view.
What I want to do now is populate the select boxes for model-language and model-type with options. Language and type fields are to be restricted to values as a result from REST calls as well, i.e. I have a list of languages and a list of types provided to me through REST.
I'm contemplating on having two collections, one for language and one for type, create a view for each (i.e. viewLanguageSelectOptions and viewTypeSelectOptions), which renders the options in the form of the template I specified above. What I am not sure of is if this is possible, or where to do the populating of options and how to set the selected option based on data from the model. It's not clear to me, even by looking at examples and docs available, which Marionette view type this may best be realized with. Maybe I'm looking in the wrong direction.
In other words, I'm stuck right now and I'm wondering of any of you fellow Backbone Marionette users have suggestions or solutions. Hope you can help!
Create a view for a Select in my opinion is not needed in the scenario that you are describing, as Im assuming that your languages list will not be changing often, and the only porpouse is to provide a list from where to pick a value so you can populate your selects in the onRender or initializace function of your view using jquery.
you can make the calls to your REST service and get the lists before rendering your view and pass this list to the view as options and populate your selects on the onRender function
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function (options) {
this.languages = options.languages;
this.typeList = options.typeList;
},
template : "#atemplate",
onRender : function () {
this.renderSelect(this.languages, "#languagesSelect", "valueofThelist");
this.renderSelect(this.typeList, "#typesSelect", "valueofThelist")
},
renderSelect :function (list, element, value) {
$.each(list, function(){
_this.$el.find(element).append("<option value='"+this[value]+"'>"+this[value]+"</option>");
});
}
})
var languagesList = getLanguages();
var typeList = getTypesList();
var myItemView = new MyItemView({languages:languagesList,typeList :typeList });
Hope this helps.

How to combine onSelectChange() with queries - ColdFusion 9 - Ajax

I have a drop down list that list different options to the user. I need the list to populate a text area based on what the user selects. I have the data already in my database and I want to be able to run a query based the user's selection from the drop down list.
This is how my select tag looks like right now:
<select name="procedure" onChange="">
<option value="">Select Procedure</option>
<cfloop query="procedures">
<option value="#procedureId#">#procedureName#</option>
</cfloop>
</select>
And this is my text area:
<textarea name="procedureDescription" cols="80" rows="6">#the query output will go here#</textarea><br />
Is there a way to use onSelectChange function to control a server side query with Ajax?
I hope my thoughts are clear, if you need more info please ask.
Yes, unless I misunderstand, you should be able to do this using an Ajax request. The onchange method should look something like this:
function handleProcedureChange()
{
var selectedVal = $(this).val();
var url; // TODO set procedure URL here, using selectedVal as needed
$.get(url, function(procedureResult) {
$("#procedureDescription").text(procedureResult);
});
}
Then you'd need to set up the server-side method to run the procedure and return the result as plain text.

Select box populated dynamically with AJAX doesn't post on form submission

This is my first attempt at chaining select boxes in a web form using ajax and I I'm obviously missing something. I'm simply at a loss for what that is, exactly. Here is my issue:
A user selects a Country from one select box and an ajax request is made and options (containing names of States and Territories) are returned to a select box below. While the options are returned into the form select field, the user-selected option is NOT sent when the form is submitted.
Here is the code I've cooked up:
<script type="text/javascript">
jQuery(document).ready(function($){
$("select#state").attr("disabled","disabled");
$("select#country").change(function(){
$("select#state").attr("disabled","disabled");
$("select#state").html("<option>Loading States...</option>");
var id = $("select#country option:selected").attr('value');
$.post("http://example.com/terms.php", {id:id}, function(data){
$("select#state").removeAttr("disabled");
$("select#state").html(data);
});
});
});
</script>
You can see the live example here (see the Country/State section):
http://shredtopia.com/add/
Any ideas what is needed to get this working?
As far i can see, the user input is sent
input_32 79
input_29 alberta
Being 79 the country canada and alberta the state.
<select tabindex="11" class="medium gfield_select" id="input_1_32" name="input_32"></select>
<select tabindex="12" class="medium gfield_select" id="input_1_29" name="input_29" disabled=""></select>
Maybe i misunderstood the issue?
Try .live( eventType,handler )
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
http://api.jquery.com/live/
Add to your code and try it~
$('select#state').live('change', function() {
var id = $("select#state option:selected").attr('value');
alert(id);
});
Or try this:
add a hidden in form:
<input type="hidden" id="hiddenValue">
alter your select#state like this:
<select onchange='innerValue(this.options[this.options.selectedIndex].value)'></select>
and create a javascript function
function innerValue(value){
$("#hiddenValue").val(value)
}
then,click submitbutton,$("#hiddenValue").val() is you need
$("#submitbutton").click(function(){
alert($("#hiddenValue").val())
})
but,I think this is not the best solution...

Resources