angular 2 select element trigger onchange - javascript

I have a select element defined as follows:
<form #empForm="ngForm" novalidate>
<div>
<label>Role</label>
<select name="role" [(ngModel)]="user" (ngModelChange)="get1($event)" (change)="get($event)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
</form>
And in the .ts,
Since the select html is bounded to the property user, setting it to different values programmatically as follows does not trigger the ngModelChange or change event which i believe is triggered solely based on user intervention
set(input: any) {
this.user = "3";
}
I wish to trigger those events when the model changes programatically. Is that possible?
Thank you,
Ashley

Try adding value Attributes like <option value="1">

When the page loads and you set the default value, take it from there and do the logic. No need to read it via your element after you set it.

Related

Setting browser autofill values in dropdown JavaScript angular

I have an address form having Name, Address, Country and state, where country and state is dropdown.
Now User can autofill the form, but it does not work for dropdown. Is there any way that I can listen autofill event and then get the complete object of browser autofill values and then manually set the dropdown values?
I am not able to find anything related to this, any help?
Usually for a browser to autofill a select, input and textarea elements there needs to be:
a name and id attribute on the element
be a child of a form element
the form needs a submit button
You can find all these requirements here
You would then need to add the autocomplete="country" attribute for the country element and autocomplete="address-level1" for the state element.
Example:
<form>
<select id="country" name="country" autocomplete="country">
<option>Choose your country</option>
</select>
<select id="state" name="state" autocomplete="address-level1">
<option>Choose your state</option>
</select>
<button type="submit">Submit Form</button>
</form>

Indenting Text in the select box when something is entered into the input field

I have figured out that dir="rtl" will make the text to position on the right side; however I want that to happen conditionally when something is written in an input element.
I was thinking of disabling dir="rtl" until something is entered into the input element and only then enable rtl. However, the problem with that is the "refresh page" requirement that the change implies.
Here is the simple drop down box with the text.
<Select class="textToRight" dir="rtl">
<div class = "toRight">
<option class="this1"> TEXT1</option>
<option class="this2"> TEXT2</option>
<option class="this3"> TEXT3</option>
</div>
</select>
<input class ="dontChange" placeholder="dontChange"></input>
<input class ="change" placeholder="change"></input>
To answer your question, yes, you can modify an attribute of one element while an event is triggered in other by attaching an event handler.
In your case you can attach it to the focusin and focusout events.
var selectBox = document.querySelector(".textToRight");
var changeInput = document.querySelector(".change");
changeInput.addEventListener("focusin", function() {
selectBox.dir = "rtl";
});
changeInput.addEventListener("focusout", function() {
selectBox.dir = "ltr";
});
<select class="textToRight">
<div class="toRight">
<option class="this1"> TEXT1</option>
<option class="this2"> TEXT2</option>
<option class="this3"> TEXT3</option>
</div>
</select>
<input class="dontChange" placeholder="dontChange"></input>
<input class="change" placeholder="change"></input>
But as David Thomas has said you, to have a div inside a select is not valid HTML.
Also, I think you are misusing the dir attribute, which is meant to indicates the directionality of the element's text (like in English vs Arabic languages).
This is what i figured out once I found out about the onkeyup(). But I am still having one trouble.
JS
function check(){
document.getElementById("textToRight").dir = "rtl";
<select class="textToRight">
<option class="this1"> TEXT1</option>
<option class="this2"> TEXT2</option>
<option class="this3"> TEXT3</option>
</select>
<input class="dontChange" placeholder="dontChange"></input>
<input class="change" placeholder="change" onkeyup='check()'></input>
I dont know how to do the snippet, but by testing it, it works. However, the problem I am having now is that I cant revert it back. So can I put a condtion on the length of the text ? if == 0 do ltr .. else dir = rtl.

Grabbing select value using regular javascript DOM

I was working on a script that grabs the value from the selected option in a drop down select list and assigns it to an object. The only problem I'm having is that it's saying I have a null object.
The .js is as follows:
var s = document.getElementById('mode');
alert(s.options[s.options.selectedIndex].value);
function selectValue(){
yo.newSelect(s.options[s.options.selectedIndex].value);
return true;
}
The HTML is as follows:
<div id="text_editing">
<form action="javascript:;" method="post" onsubmit="editHomePage()">
<select name="CYD" id="mode" onchange="selectValue()">
<option value="Home">Home</option>
<option value="About">About</option>
<option value="Contact">Contact</option>
</select>
<textarea name="sexyText" row="500" col=500">
</textarea>
<input value="submit" name="text_submit" type="submit" onclick="selectValue()">
</form>
I'm just looking for a solution in plain js. I not interested in using jQuery for such a small site.
If all your options have a value, you can simply write:
alert(s.value);
which will return the value of the first selected option (so not suitable for multiple selects with more than one selected).
Incidentally, from your listener you could do:
<input type="submit" onclick="selectValue(this)">
then in the function:
function selectValue(el) {
alert(el.form.mode.value);
}
It looks like initially, none of the options are selected; therefore, s.options[s.options.selectedIndex] would be null when the page first loads.
I would recommend using the Firebug plugin for Firefox to step through your code; you can easily identify these kinds of issues using the debugger.

Javascript: Get selected option from list and paste it on a label tag

I have a list of countries, html, they have numeric ids and country name:
Ex:
<select name="userDto.nationality" id="userDto.nationality">
<option value="">Seleccione</option>
<option value="1">Alemania</option>
<option selected="selected" value="2">Argentina</option>
<option value="8">Australia</option>
<option value="9">Austria</option>
<option value="10">BĂ©lgica</option>
<option value="11">Bolivia</option>
</select>
Im trying to use a jquery script to get the country of the list, not the value, the name and paste it inside of a label.
$(document).ready(function() {
$("#userDto\\.nationality option:selected").click(function() { $("#nationalityLabel").html(this.value); });
});
And the HTML that should get the country name is:
<div name="userLabelDiv" id="nationalityUserLabelDiv">
<label class="required">Nacionalidad :</label>
<label id="nationalityLabel"></label>
</div>
Could someone guide me through the problem? I cant find where is my error in the JS code.
Thank you
Two little things:
change selector from $("#userDto\\.nationality option:selected")
to $("#userDto\\.nationality")
change event handler from click to change
Done.
$(document).ready(function() {
$("#userDto\\.nationality").change(function() {
$("#nationalityLabel").html(this.value);
});
});
Why:
Your current code would have worked, but only for "Argentinia" since it is selected by default. With your selector option:selected you bound the event handler only to selected option elements, which is, Argentinia.
So you need to add an event handler to the select element itself. The change handler fires whenever you change the selection. I guess that is your desired result.

How to ensure a <select> form field is submitted when it is disabled?

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.
The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
Disable the fields and then enable them before the form is submitted:
jQuery code:
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name is the name that you would normally give the <select>.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
I faced a slightly different scenario, in which I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect').find(':not(:selected)').prop('disabled',true);
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
Same solution suggested by Tres without using jQuery
<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">
<select id="mysel" disabled="disabled">....</select>
<input name="submit" id="submit" type="submit" value="SEND FORM">
</form>
This might help someone understand more, but obviously is less flexible than the jQuery one.
The easiest way i found was to create a tiny javascript function tied to your form :
function enablePath() {
document.getElementById('select_name').disabled= "";
}
and you call it in your form here :
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
Or you can call it in the function you use to check your form :)
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Just add a line before submit.
$("#XYZ").removeAttr("disabled");
Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled.
This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well.
Using jQuery:
jQuery(function($) {
$('form').submit(function(){
$('select option:not(:selected)', this).remove();
});
});
<select id="example">
<option value="">please select</option>
<option value="0" >one</option>
<option value="1">two</option>
</select>
if (condition){
//you can't select
$("#example").find("option").css("display","none");
}else{
//you can select
$("#example").find("option").css("display","block");
}
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements may be successful.
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

Categories

Resources