Value Binding On Select With Static Options - javascript

is it possible use the value binding on a select that contains static options like this?
<select data-bind="value: optionValue">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Actually the bind is writing the value, if I select an option the value will change, but I am not able to read it when the select is initialized. When the page is loaded the first option is always setted.

Related

Get Select value from dropdown in Vanilla JS

I'm learning JS and can't seem to be able to make this one work:
HTML code:
<select name="colors">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
JS:
var select = document.getElementsByName("colors")[0];
console.log(select.value); // ==> it should output selected color but is not.
Since you didn't post the full code, I'd suppose that you're running your JS code before the select element is being loaded (if your script is in the headsection for example).
Anyway, I'll provide some work arounds for this purpose and at the end of the answer I'll show you how to get the selected value whenever the selected item from the list has changed.
encapsulate your code in load event of the window :
<!-- just to simulate when your JS is placed in the head section -->
<script>
// attach a "load" event listener to the "window"
window.addEventListener('load', () => {
// select the "select" element
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
});
</script>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
place your code just before the body closing tag hence no need to listen for the load event
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
Anyway I think that your final goal is to get the selected value whenever the selected item is being changed :
// select the "select" element
var select = document.getElementsByName("colors")[0];
// attach a "change" event listener to the "select" element
select.addEventListener('change', () => {
// log the selected value whenever it changes
console.log(select.value);
});
<p>choose an option from the list first</p>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
BTW, I don't recommend selecting elements based on their name attributes, using classes or IDs (if the element is unique in the page or has unique functionnality) would be a better choice.
Also, using getElementsBy* (Elements not just Elment) methods is not recommended in most situations, querySelector or getElementById(for unique elments) is better.
you should create a id of that value then use const example = document.getElementById("id")
the var should be changed to const;
and the name is the string not the value
and always use id;
Try this..
function myFunction(){
var e = document.getElementById("MySelectOption");
var strUser = e.options[e.selectedIndex].value;
console.log(strUser);
}
<select id="MySelectOption" name="colors" onchange="myFunction()">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

jQuery Select2 placeholder doesn't work when defined inline?

I have the following multiple drop-down lists defined using select2 but the placeholders don't work?
<select class="js-select2" multiple="multiple" placeholder="Select State">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</select>
<select class="js-select2" multiple="multiple" placeholder="Select Fruits">
<option value="Apples">Apples</option>
<option value="Oranges">Oranges</option>
</select>
<script>
$(".js-select2").select2({
// placeholder: 'Select an option...'
});
</script>
It only works if I define the placeholder inside the select2 option list (commented out above) but I want to use a single class to initialize all select2 multiselects drop-downs and display different placeholders.
Is it possible to achieve this?
For a quick workaround, you can pass the value of the attribute to the placeholder option:
$(".js-select2").each(function() {
$(this).select2({
placeholder: $(this).attr('placeholder')
});
});
This does not work when using $(".js-select2").select2() directly, I assume in that context this doesn’t point to the right object (or something like that). But if you use an each loop to initialize it on each element separately, it works.
https://jsfiddle.net/84whaced/
Alternatively, it should work if you use data-placeholder in the HTML (amazing what we can find out once we check the documentation, right?), see https://select2.github.io/options.html#data-attributes - https://jsfiddle.net/84whaced/1/
This would be the preferred option, I think.
It will work as:
If we just set the attr e.g. $("#state").attr('data-placeholder', 'Select State'), there will no effect.
However, if we set the attr and then call $("#state").select2() with no arguments, then the placeholder updates.
$("#state").attr("data-placeholder","Select State");
$("#state").select2();
You can use the data-placeholder for different placeholder for every select
$('select').select2({
placeholder: function(){
$(this).data('placeholder');
}
});
<select class="js-select2" multiple="multiple" data-placeholder="Select State">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</select>
<select class="js-select2" multiple="multiple" data-placeholder="Select Fruits">
<option value="Apples">Apples</option>
<option value="Oranges">Oranges</option>
</select>
You can check the Demo as well.
Maybe you have similar ids on your page. JS'll select latest id by default. Try to change them.

AngularJS blank default in select

I have a select element with six options, the first being a blank option:
<select name="method-rcvd" class="form-control" ng-model="workRequest.ReceiveMethod" required >
<option value="" ng-selected="true"></option>
<option value="1">Phone</option>
<option value="2">Email</option>
<option value="3">Fax</option>
<option value="4">Mail</option>
<option value="5">Other</option>
</select>
On the scope is the object property bound to this select:
$scope.workRequest.ReceiveMethod = "";
For some reason, the select ALWAYS defaults to "Phone", instead of blank. I want it to default to blank. When I remove the model binding it works, so I know it has something to do with that, but it needs to be bound. This seems to me that it should be relatively straightforward, but I am having a very difficult time getting this simple thing working.
When I spit out the value of ReceiveMethod below the select:
Receive Method: {{workRequest.ReceiveMethod}}
It always defaults to "1". How can I get this to default to the first option, the blank option?
Thanks.
Are you setting a default value in the controller?
What happens if you set default value to 0 instead of ''?
That should work but something must be setting another value on workRequest.ReceiveMethod
I got this working by using the ng-init directive, like so:
<select name="method-rcvd" class="form-control"
ng-model="workRequest.ReceiveMethod"
ng-init="workRequest.ReceiveMethod = ''" required >
<option value=""></option>
<option value="1">Phone</option>
<option value="2">Email</option>
<option value="3">Fax</option>
<option value="4">Mail</option>
<option value="5">Other</option>
</select>
You also don't need the
ng-selected="true"
in the first (blank) option.

Trigger event in HTML <select> box when the same entry is selected again

In a HTML form, I use a drop-down list like this:
<select onchange="send()">
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
</select>
When the user changes the selected entry, send() is called, which basically uses jQuery.ajax(...) to send the new value to the server. This works fine.
When the transmission fails for some reason, the user is informed about the error. Most users will then select the same entry again to retry. Now the problem is that this will not trigger the onchange event again because the value hasn't changed. What would be the best way to deal with this?
Try this
HTML
<select id="chg">
<option>a</option>
<option selected>b</option>
<option>c</option>
</select>
Script
$("select#chg").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
alert($(this).val());
}
$(this).data("isopen", !open);
});
DEMO
You can create a empty value option
<option value=''></option>
Which is by default selected as first load, When error occurs for any selection you can select 'empty' option from select box. So for next time user will need to selection option and your 'send()' function will call.
// Selection empty option by code
$('#selectBoxId').val('');
maybe you can use onclick event

Select/disselect only a single option on click in a select (with the multiple attribute) form element

I'm trying to modify a select element with the 'multiple' attribute to only select/disselect the one option selected, instead of disselecting all options and selecting the one target.
Let's say we got this:
<select name="somename[]" multiple="multiple">
<option selected="selected" value="val1">Val1</option>
<option selected="selected" value="val2">Val2</option>
<option value="val3">Val3</option>
</select>
What I want to happen when you select an option is:
<select name="somename[]" multiple="multiple">
<option selected="selected" value="val1">Val1</option>
<option value="val2">Val2</option> <!-- Disselected -->
<option value="val3">Val3</option>
</select>
Instead of:
<select name="somename[]" multiple="multiple">
<option value="val1">Val1</option>
<!-- All other values are disselected except the one option selected -->
<option selected="selected" value="val2">Val2</option>
<option value="val3">Val3</option>
</select>
I hope that made sense. If not please let me know.
I've tried using jQuery and hooking a click function on the select element, hoping to intersect the selected option but that failed. Appearently the selections are made before the event is triggered.
Thanks.

Categories