Trigger ng-change function without keyup or keypressed in AngularJS - javascript

I have applied ng-model and ng-change directives on input type text, that shows color in hexa that can be changed from color panel as shown.
<input type="text" ng-model="colors.primary_color"
ng-change="colorChanged()" class="input-control"
placeholder="Primary Color"
color-picker
color-picker-model="primaryColorModel"
color-picker-position="{{colorPickerPosition}}">
<button class="btn-sidebar">
<svg width="20px" height="21px">
<path ng-style="{fill: primaryColorModel}" d="M10.000,3.429 C5.865,3.429 2.500,6.793 2.500,10.928 C2.500,15.063 5.865,18.427 10.000,18.427 C10.000,14.550 10.000,7.089 10.000,3.429 M10.000,0.929 C15.523,0.929 20.000,5.406 20.000,10.928 C20.000,16.450 15.523,20.927 10.000,20.927 C4.477,20.927 -0.000,16.450 -0.000,10.928 C-0.000,5.406 4.477,0.929 10.000,0.929 L10.000,0.929 Z"
/>
</svg>
</button>
Now when I open color panel and change colors, new hexa code shows up in input type text, but colorChanged function doesn't trigger. It only triggers when I click on text box and write some thing.
I want it to be triggerd when I remove any character or value is changed from color panel.
I have tried with $watch like so
$scope.colors = {
primary_color: "#008fff",
secondary_color:"#008fff",
text_color: "#008fff"
}
$scope.$watch('colors', function (nval, oval) {
console.log(nval);
});
$scope.colorChanged = function() {
$rootScope.$broadcast('color-change', {colors: $scope.colors});
}
But it doesn't trigger either.
If I use $apply, it says you are already in digestive cycle.

If you place the relevant markup inside a <form> element and give the <input> a name :
<form name="form">
<input name="primary_color" type="text" ng-model="colors.primary_color"
ng-change="colorChanged()" class="input-control"
placeholder="Primary Color"
color-picker color-picker-model="primaryColorModel"
color-picker-position="{{colorPickerPosition}}">
...
</form>
Then you can programmatically trigger the ng-change directive by using $setViewValue() with no params :
$scope.form.primary_color.$setViewValue()
Will trigger ng-change as the ng-model was changed without actually changing it.
demo -> http://plnkr.co/edit/PmthIfblkPkbKgRInLBc?p=preview

If you are using this plugin, then the variable you specify in color-picker-model attribute is treated as the binding variable for the color picker. So to detect changes to the color picked, you can watch that variable. In your case:
$scope.$watch('primaryColorModel', function(nval, oval) {
//your code here
});

I can't tell which plugin you used for, but regardless unless it was built with angular you'll likely have to wire up a callback that runs a $rootScope.$apply(). The reason being is that the piece of code is happening outside angulars eco-system and it needs to be notified to re-run. See my similar answer here: AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Related

how to copy a text of span

I copy need the dynamic text of a spam that is generated by a slider that the user sets. It must be copied to a value of an input.
I tried that, and didnt work:
<h4>Valor do consórcio: <span class="slider-value quote-form-element valor-carro1" data-name="Valor | Automóvel" name="Valor" data-slider-id="consorcio-auto">R$ <span id="THAT_VALUE"></span></span>
</h4>
<div class="slider" data-slider-min="20000" data-slider-max="100000" data-slider-start="23192" data-slider-step="1000" data-slider-id="consorcio-auto"></div>
<h4>Seus dados:</h4>
<input type="hidden" id="THAT_FIELD" name="THAT_FIELD" value="" />
<h4>Seus dados:</h4>
<input type="hidden" id="valorcarro" name="valorcarro" value="" />
script
$(function(){
var valorcarro = $('#THAT_VALUE').html();
$('#THAT_FIELD').val(valorcarro);
});
example in this page in the button on menu "Simulação".
The script just does not copy because the value is generated later and the user can still change
You need to use an event to fire your code after the slider value has changed. This is how you do it with a bootstrap slider.
$('.slider').on('slideStop', function () {
var valorcarro = $('#THAT_VALUE').text();
$('#THAT_FIELD').val(valorcarro);
});
To get the text of an element, use text()
For example
$("span").text();
you can try this code.
jQuery(function(){
var valorcarro = jQuery('#THAT_VALUE').text();
jQuery('#THAT_FIELD').val(valorcarro);
});
Actually, #Pamblam's response is better than mine. I was assuming the .slider class was for regular range inputs, which fire the 'change' event when their value changes, but it looks like it is in fact a bootstrap slider, which fires the slideStop event instead. Regardless, the code here listens for a change in the slider value, and when it is triggered, takes the text from the #THAT_VALUE span (from op's code) and sets the value of the #THAT_FIELD field to whatever it is :
$(".slider").change(function(){
var valorcarro = $('#THAT_VALUE').text();
$('#THAT_FIELD').val(valorcarro);
});

ng-model inside radio input refresh

I'm using a jQuery library of radio/checkbox components (yeah, I know using jQuery is bad with angular, but that was not my choice to use that library and I cannot change that) and I got a problem with refreshing ng-model data (radio component in library does a simple click trigger event when radio value change).
I noticed, that while one click trigger does nothing to model, triggering it twice solves the problem (but that is not the way I would like to solve this problem). I prepared a simple fiddle- a little example of what is my problem. First click (executing changeInput(1, 1) in the code below) on a button does a change in DOM, but does nothing to angular model - while clicking just on the radio button is doing just fine. Executing changeInput(1,2) does exacly the same as clicking the radio element.
function changeInput(obj, num){
for(var i = 0; i < num; i++){
$('input').eq(obj).click();
}
}
What else can I do? While reading stackoverflow I have noticed that people say that triggering 'input' solves the problem - but not in that case (JSFiddle). Is triggering click twice is the only way to solve this problem?
In Angular things don't work the way you might be used to. Once you get used to it, you will enjoy the much more straightforward and declarative nature of you code.
You said:
"in this question I would like only to know how to make model changes"
Nevertheless, in your attempts your are trying to make model changes by changing the view (programmatically). This is both unintuitive and a nightmare in terms of maintainability.
In Angular you should worry about your data (model) and watch the views adapt automagically.
So, if you want to make model changes, then all you need to do is to...well, change the model:
<input type="radio" name='test' ng-model="value" value="0" />
<input type="radio" name='test' ng-model="value" value="1" />
<button ng-click="changeInput(0)">Change value to 0</button><br/>
<button ng-click="changeInput(1)">Change value to 1</button><br/>
function Ctrl($scope) {
$scope.value = 0;
$scope.changeInput = function (newValue) {
$scope.value = newValue;
}
}
In order for Angular to do its magic and update the view you need to perform the action within the Angular context (ng-click instead of onclick takes care of that). If for whatever reason you can't use ng-click, you need to let Angular know something changed by wrapping your code in the changeInput() function in $scope.apply().
See, also, this short demo.
I had a similar issue once using only angular. The ng-binding of your input must be a property of an object defined in your controller. I think that otherwise, the input value is binded to a variable defined in the input own scope.
That wouldn't work :
<input type="checkbox" ng-model="selected"></input>
But that would :
<input type="checkbox" ng-model="someObject.selected"></input>
with for example in you controller :
$scope.someObject = {
selected: false
};

The trouble with $scope

I have an input file element within an angular view/form. I'm using ng-upload like this:
<input id="img" type="file" name="image" onchange="angular.element(this).scope().setFile(this)">
<input id="imgname" type="hidden" value=""></div>
Since I can't tell angular to listen for changes on input[type="file"] element, I've created the method that updates the hidden input that just holds the current filename. That way I can run my validator on the second field.
Another field I have has some sort of validator, like this:
<input ng-model="other" ng-change="chg()"/>
Now, the trouble is, if I trigger the validator, $scope.chg(), from setFile() method, I think I don't get the same scope - chg() runs, but it's as if the validator is in another scope and doesn't set my actual submit button to enabled. I tried logging from the chg() - it shows different scope then what I actually see on the view.
And if I later trigger the ng-change by changing the regular input field ("other"), it picks up the changes, or actually, it sets the submit button state correctly.
Now, I suspect this has to do with me calling the angular.element(this).scope().setFile(this) from my form instead of direct, $scope-bound method. But I cannot call $scope-bound method because it does not trigger - if I understood correctly, that's due to Angular not (yet) working with input type=file fields.
What can I do here?
I simply want to detect if there is a file or not so I can enable/disable the submit button appropriately.
I used followed flow that works for me:
<input type="file"
ng-model="upFile"
onchange="angular.element(this).scope().setFileEventListener(this)"
/>
From controller:
$scope.setFileEventListener = function(element) {
$scope.uploadedFile = element.files[0];
if ($scope.uploadedFile) {
$scope.$apply(function() {
$scope.upload_button_state = true;
});
}
}
Hope it will help.

html <input type="text" /> onchange event not working

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange is only triggered when the control is blurred. Try onkeypress instead.
Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
HTML5 defines an oninput event to catch all direct changes. it works for me.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input
The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event) with <select>.
With <input> you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event
you can use oninput
The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
<input type="text" id="input"> oninput: <span id="result"></span>
<script>
input.oninput = function() {
console.log(input.value);
};
</script>
If we want to handle every modification of an <input> then this event is the best choice.
I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.
useEffect(()=>{
document.title='fix onChange with onkeyup';
const box = document.getElementById('changeBox');
box.onkeyup = function () {
console.log(box.value);
}
},[]);
Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod.
In the functional component where you have the <Input/> for the <form/>write this
<form onSubmit={handleLogin} method='POST'>
<input
aria-label= 'Enter Email Address'
type='text'
placeholder='Email Address'
className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
id='changeBox'
/>
</form>
Resulting Image :
Console Image
try onpropertychange.
it only works for IE.

Dojo: dojo onblur events

I have a form setup with dojo 1.5. I am using a dijit.form.ComboBox and a dijit.form.TextBox
The Combobox has values like "car","bike","motorcycle" and the textbox is meant to be an adjective to the Combobox.
So it doesn't matter what is in the Combobox but if the ComboBox does have a value then something MUST be filled in the TextBox. Optionally, if nothing is in the ComboBox, then nothing can be in the TextBox and that is just fine. In fact if something isn't in the Combobox then nothing MUST be in the text box.
In regular coding I would just use an onBlur event on the text box to go to a function that checks to see if the ComboBox has a value. I see in dojo that this doesn't work... Code example is below...
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
Descriptor:
<input type="text"
dojoType="dijit.form.TextBox"
value=""
class=lighttext
style="width:350px;height:19px"
id="filter_value_1"
name="filter_value_1"
/>
My initial attempt was to add an onBlur within the Descriptor's <input> tag but discovered that that doesn't work.
How does Dojo handle this? Is it via a dojo.connect parameter? Even though in the example above the combobox has an id of "vehicle_1" and the text box has an id of "filter_value_1", there can be numerous comboboxes and textboxes numbering sequentially upward. (vehicle_2, vehicle_3, etc)
Any advice or links to resources would be greatly appreciated.
To add the onBlur event you should use dojo.connect():
dojo.connect(dojo.byId("vehicle_1"), "onBlur", function() { /* do something */ });
If you have multiple inputs that you need to connect this to, consider adding a custom class for those that need to blur and using dojo.query to connect to all of them:
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
class="blurEvent"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
dojo.query(".blurEvent").forEach(function(node, index, arr) {
dojo.connect(node, "onBlur", function() { /* do something */ });
});
In the function that is passed to dojo.connect you could add in some code to strip out the number on the end and use it to reference each filter_value_* input for validation.
dojo.connect()
Combobox documention
onBlur seems to work just fine for me, even in the HTML-declared widgets. Here's a very rudimentary example:
http://jsfiddle.net/kfranqueiro/BWT4U/
(Have firebug/webkit inspector/IE8 dev tools open to see console.log messages.)
However, for a more ideal solution to this, you might also be interested in some other widgets...
http://dojotoolkit.org/reference-guide/dijit/form/ValidationTextbox.html
http://dojotoolkit.org/reference-guide/dijit/form/Form.html
Hopefully this can get you started.

Categories