I am creating a webapp using vuejs 2.0. I have created simple select input using following code:
<select v-model="age">
<option value="" disabled selected hidden>Select Age</option>
<option value="1"> 1 Year</option>
<option value="11"> 11 Year</option>
</select>
and I have this in data of my Vue component:
data () {
return {
age: "",
}
},
watch: {
age: function (newAge) {
console.log("log here")
}
But I start to get this error when adding default value for select:
ERROR in ./~/vue-loader/lib/template-compiler.js?id=data-v-5cf0d7e0!./~/vue-loader/lib/selector.js?type=template&index=0!./src/components/cde.vue
template syntax error :
inline selected attributes on will be ignored when using v-model. Declare initial values in the component's data option instead.
# ./src/components/cde.vue 10:23-151
# ./~/babel-loader!./~/vue-loader/lib/selector.js?
type=script&index=0!./src/views/abcView.vue
# ./src/views/abcView.vue
# ./src/router/index.js
# ./src/app.js
# ./src/client-entry.js
# multi app
I tried to give default value in the data section of the component as well, but then nothing happened. I tried v-bind also but then watchers stopped working on age variable.
For others who may be landing on this question, there was an additional step for me to get the default option to appear. In my case, the v-model I was binding to was returning null and rather than an empty string. This meant that the default option was never selected once Vue bindings kicked in.
To solve for this, simple bind the value property of your default option to null:
<select v-model="age">
<option :value="null" disabled>Select Age</option>
...
</select>
http://jsfiddle.net/2Logme0m/1/
The only thing needed to work this was remove selected from default option:
<select v-model="age">
<option value="" disabled hidden>Select Age</option>
.....
</select>
For placeholder, you need to set the value attribute with the same value as in defined as initial value in your state.
Change your disabled option with
<option value="null" disabled selected hidden>Select Age</option>
and in state do something like this
data () {enter code here
return {
age: null,
}
}
To build upon Shivam Bisht, In case you can't access your default value.
Just add value="undefined" to your placeholder option tag.
Placeholder text
var demo = new Vue({
el: '#demo',
data: function() {
return {
param: undefined,
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<select v-model="param">
<option value="undefined" disabled>Placeholder text</option>
<option value="1">Dutch woman are beautiful.</option>
<option value="11">German Men are slow.</option>
</select>
</div>
The only way I got it working:
<select v-model="selectedTemplate" class="btn btn-default">
<option v-for="template in templates" v-bind:value="template.tasks"}{{template.name}}</option>
<option :value="this.selectedTemplate" disabled hidden>Select a template</option>
</select>
The key being the :value=this.selectedtemplate in the disabled hidden option.
To add up on other answers, as they all seem to be correct at a specific condition:
It depends on the data type expected by your v-model variable, for example if it is expecting an integer passing :value="null" or :value="undefined" would work, but if it is expecting an object for example, then you need to pass :value="{}".
//Example: data/v-model expects integer
<select v-model="param">
<option :value="undefined" disabled>Placeholder text</option>
<option value="1">1</option>
<option value="11">11</option>
</select>
//Example: data/v-model expects object
<select v-model="param">
<option :value="{}" disabled>Placeholder text</option>
<option
v-for="item in items"
:key="item.id"
:value="item"
>
{{ item.propery }}
</option>
</select>
For a string null or undefined values should work, but you could also just define a placeholder in you data object.
Related
If the cardSelect variable is true, just let [readonly]="cardSelect"
<select name="card-exp-month" #validateMonth formControlName="digiMes" class="form-
control" name="validade" id="validade" >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>
When is input text its works
<label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *
</span></label>
<input #nomeImpresso formControlName="digiNome" name="holder-name" id="nomeimpresso"
class="form-control col-lg-6" type="text" [readonly]="cardSelect" >
try [disabled]="cardSelect" or if that didn't work [attr.disabled]="!editable ? '' : null" as a workaround.
As stated by #rmjoia, my previous answer is dangerous and should be avoided (see below).
Updated answer
For disabling the whole "select" element you can use a boolean variable declared in your controller (isDisabled in my following example)
In the HTML:
<select [disabled]="isDisabled">
<option>a</option>
</select>
In the controller:
export class AppComponent {
…
// the variable declaration (at start the select is enabled)
isDisabled = false;
// later you may change the state of the select element.
onClick() {
this.isDisabled = true;
}
}
Some code implementing different solutions :
https://stackblitz.com/edit/angular-ivy-qkwier?file=src/app/app.component.html
Previous answer
For disabling the whole "select" element you can :
<select … [disabled]="isSelectDisabled()">
…
</select>
and decide in your controller the logic behind the isSelectDisabled method.
So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.
Have you tried assigning it an id and then changing it in your js file?
Something like this:
<option value='0' id='opt1' selected>Ver</option>
and in javascript:
document.getElementById("opt1").value = "1";
You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')
You can then change the value by reassigning it
opt.setAttribute('value', '1')
If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')
Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1, not 0
document.querySelector('select.form-control')
.addEventListener('change', function(e) {
console.log(this.value);
});
document.querySelector('select.form-control option[value="0"]')
.setAttribute('value', '1');
select {
min-width: 10em;
}
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
Hello you can assign the value with the following instruction
$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option";
reference in this url Set value of combobox or select
I have a select element
<select id="filter" v-model="filter" #change="changeFilter">
<option value="all">All</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
Then in my component I have
methods:{
changeFilter(){
var that = this
console.log(that.filter)
// this gives me the value from the last select
// If I then use Jquery
that.filter = window.jQuery('#filter').val()
console.log(that.filter)
// This gives the correct up to date value
}
}
Why is it that I ahve to use Jquery to get the most recent value of this element?
I thought Vue.js was supposed to be reactive? Why is it one tick behind then?? Why am I forced to use jQuery to get the currently chosen selection? Seems super counter intuitive to do that?
Your mistake is doing a two-way binding plus an event. The event is fired at the same time as the model update, therefore the change hasn't posted yet.
You'd be better off using a watch here.
First, remove the event:
<select id="filter" v-model="filter">
<option value="all">All</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
Then put the watch in your Vue object:
watch: {
filter: function (val) {
// use val here
}
}
More info here: https://v2.vuejs.org/v2/guide/computed.html
I was just replicating your code but it was just totally working fine.
Check the code below:
new Vue({
el: "#app",
data: {
filter: 'all'
},
methods: {
changeFilter: function() {
alert(this.filter)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.15/dist/vue.js"></script>
<div id="app">
<select v-model="filter" #change="changeFilter">
<option value="all">All</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
</div>
I try to set select option attribute to selected. But I try to avoid using nth-child in CasperJS because there are bugs in PhantomJS's nth-child.
So I try to use this as the subtitution of jQuery(css_path).
function setSelectedCountry(i){
window.__utils__.echo("i :"+i);
var query = "//*[#id='cboCountry']/optgroup[2]/option["+i+"]";
__utils__.getElementByXPath(query).setAttribute("selected","selected");
}
But, when I evaluate that code by this way
this.evaluate(setSelectedCountry, 5);
The select option is not changed.
Moreover, when I try to trigger onblur() using
document.getElementById("cboCountry").onblur();
inside setSelectedCountry() funtion, there were nothing happened.
Why this happened?
Also, when I try to call the function with XPath expression, and the other one is using CSS selector, I got undefined error returned from CasperJS.
I use this function :
function getCityName(i){
var query = "//*[#id='cboCity']/option["+i+"]";
return __utils__.getElementByXPath(query).innerText;
}
then I got the other one:
function setSelectedCountry(i){
var query = "#cboCountry > optgroup:nth-child(3) > option:nth-child("+i+")";
jQuery(query).attr("selected", "selected").blur();
}
When I try to run both of them, then this is what I've got
PAGE.ERROR: TypeError: 'undefined' is not an object (evaluating
'__utils__.getElementByXPath(query).innerText')
Can you give me suggestions?
[EDITED]
Here is my markup :
This one for cboCountry select option :
<select name="cboCountry" id="cboCountry" onkeypress="return selectItem();" onkeyup="event.cancelbubble=true;return false;" onkeydown="return handleKey();" onfocus="activeList=this;this.enteredText='';" onchange="//hs.DropCity();" onblur="hs.DropCity();"
class="txtBox">
<option value="">-- --Select-- --</option>
<optgroup label="Popular Destinations">
<option value="MA05110065">Indonesia</option>
<option value="MA05110067">Malaysia</option>
<option value="MA05110069">Singapore</option>
<option value="MA05110001">Thailand</option>
</optgroup>
<optgroup label="Other Destinations">
<option value="MA05110083">Afghanistan</option>
<option value="MA05110124">Albania</option>
<option value="MA05110133">Algeria</option>
<option value="MA05110186">American Samoa</option>
<option value="MA05110103">Andorra</option>
<option value="MA05110014">Angola</option>
<option value="MA05110135">Anguilla (UK)</option>
<option value="MA05110136">Antigua and Barbuda</option>
<option value="MA05110171">Argentina</option>
<option value="MA05110206">Armenia</option>
<option value="MA05110183">Venezuela</option>
<option value="MA05110070">Vietnam</option>
<option value="MA05110013">Western Sahara</option>
<option value="MA05110082">Yemen</option>
<option value="MA05110027">Zambia</option>
<option value="MA05110028">Zimbabwe</option>
</optgroup>
</select>
And this one for cboCity select option :
<select name="cboCity" id="cboCity" onkeypress="return selectItem();" onkeyup="event.cancelbubble=true;return false;" onkeydown="return handleKey();" onfocus="activeList=this;this.enteredText='';" onchange="//hs.DropLocation();" onblur="hs.DropLocation();"
class="txtBox">
<option value="">-- --Select-- --</option>
<option value="">-- Select --</option>
<option value="MA02022810">Ambarawa</option>
<option value="MA09090008">Ambon</option>
<option value="MA08090042">Anyer</option>
<option value="MA02022861">Wonosobo</option>
<option value="MA06060051">Yogyakarta</option>
</select>
The problem is the distinction between property and attribute. Browsers usually don't re-evaluate attributes when you change them in the DOM. In those cases, you would need to change the property behind that attribute on the DOM element.
In this case, you need to change the selected index. The select element has the selectedIndex property that you can change to the intended option which you can get through option.index:
function setSelectedCountry(i){
__utils__.echo("i :"+i);
var opt = "//*[#id='cboCountry']/optgroup[2]/option["+i+"]";
var select = document.getElementById('cboCountry');
select.selectedIndex = __utils__.getElementByXPath(opt).index;
select.onblur(); // or `onchange()`
}
See this answer for more information on the option index.
"//*[#id='cboCity']/option["+i+"]" cannot work, because this expression will match options that are direct children of a #cboCity element, but you have an optgroup inbetween. Either use "//*[#id='cboCity']//option["+i+"]" or "//*[#id='cboCity']/optgroup/option["+i+"]".
is there anyway of getting the onchange to work with jquery? Right now i'm using prototype.js. What the onchange does is when either US, CA or GB is selected it shows the state dropdown box for it. basically a show / hide
<SELECT id='country' onchange="HandleStateApearence(this.selectedIndex,
null, $('state_'), $('state_3'), $('state_2'),
null, 1, 2, false)" name=add[country]>
<OPTION value="" selected>-- Select Country --</OPTION>
<OPTION value=US>United States</OPTION>
<OPTION value=CA>Canada</OPTION>
<OPTION value=GB>United Kingdom</OPTION>
</SELECT>
<span id='state_' style="display:none; font-weight:bold;">State:</span>
<SELECT id=state_2 style="DISPLAY: none" name="c_state">
<OPTION value="" selected>-- Select Province --</OPTION>
<OPTION value=AB>Alberta</OPTION>
<OPTION value="BC">British Columbia</OPTION>
</SELECT>
<SELECT id=state_3 style="DISPLAY: none" name="u_state">
<OPTION value="" selected>-- Select State --</OPTION>
<OPTION value=AL>Alabama</OPTION>
<OPTION value=AK>Alaska</OPTION>
<OPTION value=AZ>Arizona</OPTION>
</SELECT>
You haven't shown the definition of HandleStateAppearence(), so I'm not sure what its parameters' expected types are, but in jQuery the $('someselectorhere') function returns a jQuery object that you can treat as if it is an array elements that matched the selector (potentially an empty array, though it won't be in your case). Also, to select an element by ID you use "#", e.g., $('#state_') - jQuery selectors (mostly) follow the syntax of CSS selectors.
So putting those two points together, if your function is expecting direct references to the select elements you need to say $('#state_')[0]:
<SELECT id='country' onchange="HandleStateApearence(this.selectedIndex, null,
$('#state_')[0], $('#state_3')[0], $('#state_2')[0], null, 1, 2, false)"
name=add[country]>
EDIT: Here's a complete jQuery-based method to handle the show/hide of applicable state select elements.
<script>
$(document).ready(function() {
$("#country").change(function() {
$(".state").hide();
var stateSelect = $("#state_" + $(this).val());
if (stateSelect.length === 0)
$("#state_label").hide();
else {
$("#state_label").show();
stateSelect.show();
}
});
});
</script>
<SELECT id='country' name=add[country]>
<OPTION value="" selected>-- Select Country --</OPTION>
<OPTION value=US>United States</OPTION>
<OPTION value=CA>Canada</OPTION>
<OPTION value=GB>United Kingdom</OPTION>
</SELECT>
<span id='state_label' style="display:none; font-weight:bold;">State:</span>
<SELECT id="state_CA" class="state" style="DISPLAY: none" name="c_state">
<OPTION value="" selected>-- Select Province --</OPTION>
<OPTION value=AB>Alberta</OPTION>
<OPTION value="BC">British Columbia</OPTION>
</SELECT>
<SELECT id="state_US" class="state" style="DISPLAY: none" name="u_state">
<OPTION value="" selected>-- Select State --</OPTION>
<OPTION value=AL>Alabama</OPTION>
<OPTION value=AK>Alaska</OPTION>
<OPTION value=AZ>Arizona</OPTION>
</SELECT>
I've removed the inline onchange handler and instead assigned the change handler via jQuery, done inside the document.ready handler so that we can be sure the country element has already been parsed. This is the standard way to assign event handlers.
In your html, I've given each state select element a class of "state" so that we can easily select them all at once to hide them with a single statement.
I've also changed the ID attribute of the select elements to be "state_{countrycode}", e.g., "state_CA", where the codes match exactly with the corresponding values in the country option elements. That way we can reference them in JavaScript by concatenating the currently selected country code to the end of "state_" and if you later add more countries to the list with their own corresponding state drop-down you won't need to change the JavaScript at all. The most important line of code is probably this one:
var stateSelect = $("#state_" + $(this).val());
Which declares a variable stateSelect that will be assigned to a jQuery object containing all elements that match a selector that is an element ID of "state_{currentcountrycode}". Depending on which country option is selected that stateSelect jQuery object will contain exactly 0 or 1 elements, so I then test the length of the object and if it is 0 I hide the state label (I changed its ID too, to be more descriptive), or if the length is 1 I show the state label and the select element.
I'm not well versed with prototype.js, but what it looks like you're doing is passing in elements to your change handler function.
In jQuery, if you're going to be selecting using IDs, you have to prepend the id value with a #.
HandleStateApearence(
this.selectedIndex, null,
$('#state_'), $('#state_3'), $('#state_2'),
null, 1, 2, false
)