Set 'value' input with AngularJS function - javascript

I'm kinda noob with AngularJS I have the next div:
<div ng-app="" ng-controller="telController">
Teléfono: <input type="text" ng-model="telefono.numero" ><br>
<input type="text" ng-model="telefono.tras" >
<br>
El telefono es: {{telefono.telefonoCodificado()}}
</div>
The angularjs function is:
function telController($scope) {
$scope.telefono = {
numero: "",
telefonoCodificado: function() {
var x;
x = $scope.telefono;
var parte1;
parte1= $scope.telefono.numero;
var telCodificado = parte1.substring(0, 3)+"-"+parte1.substring(3, 6)+"-"+parte1.substring(6, 10);
return "A) "+x.numero+" <<>> "+ telCodificado;
},
tras : function(){
var y;
y = $scope.telefono.numero;
return y;
}
};
}
I want the input with ng-model='telefono.tras' get filled with the value that have been typing in the input ng-model="telefono.numero" but that doesn´t happend, what am I doing wrong?

New Answer:
After being updated on the issue, its better to use a ng-change to update the other variable.
JSFiddle Demo
Old Answer:
Hi There is no need to write a separate function to copy the ng-model (telefono.numero) to the variable telefono.tras, you can just assign the same variable. Like so.
JSFiddle Demo
Suppose you need telefono.tras populated for some function, then before calling the function, assign the telefono.numero value to telefono.tras.
So if you want to populate telefono.tras you can use the $watch() method to do this!
$scope.$watch('telefono.numero', function(newValue, oldValue){
$scope.telefono.tras = newValue;
})
JSFiddle Demo
I hope this answer was useful, please let me know if there are any issues.
Suggestion: The input box is allowing numbers and text, to allow only numbers you need to add a directive, refer this link

Related

Unable to change a value inside a variable?

I am currently working on a project that I took over with the input reads from a barcode, currently iam having trouble with my output giving me a fix value which the code reads from and does not read from the actual input.
below is the html code for the scanner. it reads fine
<div class="section" id="instruction-3">
<p>Otherwise, scan your code at the bottom, or manually type it in here:</p>
<span>
<input type="text" id="IC-input" name="IC" onclick="openKeyboard()" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="9">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>
</div>
follow by the javascript (which i suspect is where the problem lies but am not sure)
<script>
var NRIC = '{"NRIC":"0"}';
function theButtonIsPressed(){
closeKeyboard();
console.log('button clicked');
NRIC = '{"NRIC":"123456789"}';
//var IcNum = document.getElementById("IC-input").value;
//NRIC = NRIC.replace("0", IcNum);
document.getElementById("IC-input").value = "";
doWork(NRIC)
}
</script>
function doWork(NRIC) {
// ajax the JSON to the server
$.post("receiver", NRIC, function(){
});
// stop link reloading the page
function update() {
setInterval(function(){$.post("receiver", '{"NRIC":NRIC}', function(){});}, 900);
It keeps giving me the value inside NRIC = '{"NRIC":"123456789"}'; which is 123456789, i realize this might be a simple fix but i am still learning and am unsure.
thank you in advance.
If I correctly understanded you want to have in the obj the input value, so try this:
function theButtonIsPressed(){
closeKeyboard();
console.log('button clicked');
var IcNum = document.getElementById("IC-input").value;
NRIC.NRIC = IcNum;
doWork(NRIC)
}
Why quotes around an object?
var NRIC = {"NRIC": 0};
function theButtonIsPressed() {
NRIC = {"NRIC": 123456789};
doWork(NRIC)
}
all but I have solved the problem, it was my fault that I did not mention I wanted to transfer the data to another webpage, and the problem with that was that the data was not transferred over to the other html.
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
function theButtonIsPressed(value){
closeKeyboard();
console.log('button clicked');
//NRIC = '{"NRIC":"123456789"}';
console.log(value)
doWork(value)
}
by doing this it read the value as accordingly from the input and worked after, sorry again for my confusing question and thanks to everyone who tried to help.

Make knockout listen to values changes which are not a result of a keystroke [duplicate]

This question already has an answer here:
Knockout.js bound input value not updated when I use jquery .val('xyz')
(1 answer)
Closed 6 years ago.
self.totalHours = ko.pureComputed(function() {
var start=self.num1;
var end=self.num2;
return start+end;
});
<input type="text" data-bind="textInput: start">
<input type="text" data-bind="textInput: end">
<input type="text" data-bind='text: totalHours()'>
The above first is part of my viewmodel and the second is part of my model. num1,num2 are observables. Every time I change manually the value inside the above first two inputs the third input is updated immediately; however, when the values change by code, knockout does not listen to the changes and total is not updated. How may I oblige knockout to listen to the changes provoked by code?
Quite some stuff you can fix and improve here:
A computed value will re-evaluate when an observable it uses in its method changes: self.num1 and/or self.num2 need to be observable and evaluated using ()
If you want to bind an <input>'s value, you have to use either the value or textInput data-bind; the text bind will not work.
If you want to write to a computed, you'll have to specify a write method. You'll have to tell knockout how to update the computed's dependencies to make sure all values add up. (e.g.: setting totalHours could set num1 to totalHours and num2 to 0)
You've bound to start and end, while your viewmodel properties are named num1 and num2.
When using value or textInput, user input will be returned as a string. You'll need to parse the strings to numbers if you want to use them in any math.
Now that all code should be working correctly, you can update your viewmodel's values via the inputs, or via code:
var ViewModel = function() {
var self = this;
self.num1 = ko.observable(0);
self.num2 = ko.observable(0);
self.totalHours = ko.pureComputed(function() {
var start = parseFloat(self.num1());
var end = parseFloat(self.num2());
return start + end;
});
};
var vm = new ViewModel();
ko.applyBindings(vm);
// Updating your values from code:
vm.num1(1);
vm.num2(2);
// Whenever the values need to be updated via js,
// you should change the source values, _not_ the
// <input>'s values. Worst case scenario, you'll
// have to do something like this:
var updateNum1ViaDOM = function() {
ko.dataFor(document.querySelector("input")).num1(5);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="textInput: num1">
<input type="text" data-bind="textInput: num2">
<span data-bind='text: totalHours'></span>
Note: it's probably better to use an extender to force num1 and num2 to be numeric: Live Example 1: Forcing input to be numeric
Not sure if it is a copy paste problem but the the code you posted will not work as intended. I've updated the example, when changing an observable value it must be passed as parameter so as not to overwrite the knockout observable
self.start = ko.observable();
self.end = ko.observable();
self.totalHours = ko.computed(function() {
return self.start() + self.end();
});
<input type="text" data-bind="textInput: start">
<input type="text" data-bind="textInput: end">
<input type="text" data-bind='text: totalHours()'>
//Then when changing the value by code
var newValue = 42;
model.start(newValue); //assuming you are making the change outside your viewmodel
*Just noticed this code will throw an exception when you edit the input bound to totalHours as it does not have a write handler defined. This is a separate issue though.

angular-tags: Reset the tags input value

index.html
<div class="modal-header" >
<button type="button" class="close" ng-click = "submit(information.add, information.subject, information.emailContent); close()">×</button>
<h3>Compose Email</h3>
</div>
<div class="modal-body">
<form name = "form.email">
<tags options="{addable: true}" typeahead-options="typeaheadOpts" data-model="information.add" data-src="toPerson as toPerson for toPerson in to"></tags>
<input type="text" placeholder="Subject" style="width:95%;" data-ng-model = "information.subject"><br />
<textarea style="width:95%;" rows="10" data-ng-model = "information.emailContent"></textarea>
</form>
</div>
emailViewController.js
$scope.information = {
add: [],
subject: [],
emailContent: []
};
$scope.clear = function() {
if ($scope.information.add !== "") {
$scope.information = null;
}
};
I am setting the value of $scope.information to null. After doing this, the input box value bound to information.subject and the textarea value bound to information.emailContent are reset. However, the tags input value bound to information.add does not reset. Does anyone know why this is being caused.
I think $scope.remove() in the angular-tags widget should be used to remove the tag. I am not sure how to implement it though. Angular-tags source code can be found here - https://github.com/boneskull/angular-tags/blob/master/src/tags.js
Here is a plunker - http://plnkr.co/edit/PaG1k5N37BTOflObnN7K?p=preview
Attempt 1
This is a plunker of what I have tried so far - http://plnkr.co/edit/jjE2bU8zkkyw36rtAymL?p=preview . I am redefining the value of $scope.info to null in a function wrapped inside $timeout. I thought maybe the changes I made to the $scope are not being applied to the view, so I tried to wrap it in a $timeout. Doing so did not fix the problem though.
This code $scope.information = null; is supposed to nuke all your information and clear the entire thing? This only sets the reference to the object containing the arrays to null. The arrays are still there and still referenced by your widget I expect - (I'm not sure how the library you are using for your tags is implemented)
The below code actually empties the arrays:
$scope.information.add.length = 0;
$scope.information.subject.length = 0;
$scope.information.emailContent.length = 0;

Unable to create a variable in javascript

I am creating an app that will tell you the price of a product when the barcode is scanned. Basically, when a barcode is scanned, it goes into the text field, and then based on which barcode it is, the textarea will have a price put into it via javascript. I've gotten this to work, but I can't seem to create a certain variable to save me from looking through tons of code later on.
Here is my javascript:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea').innerHTML;
if (userInput === "783466209834") {
price = "16.99";
} else {
price = "Not a valid barcode";
}
}
And here is my HTML:
<input type="text" name="text" class="textinput" id="barcode">
<input type="button" onclick="showPrice()" value="Submit">
<textarea name="" cols="" rows="" readonly="readonly" id="textarea"></textarea>
Right now, my code isn't working, but if I remove
var price = document.getElementById('textarea').innerHTML;
and replace "price" in the if statement respectively, then it works. I'm not sure why I can't create this price variable.
Because you're storing the value of the innerHTML as the variable, not storing a reference to it.
Change it to var textarea = document.getElementById('textarea'); and then textarea.innerHTML = "16.99" and so on.
If you want to work with the value of the textarea, you need to access document.getElementById('textarea').value, not innerHTML.
And, yes, as others have pointed out, you want to set the variable to reference to the element, not the value. Then you can retrieve or set the value of the element.
You are getting the innerHTML of the textarea and storing it in the variable price. Instead, you need to only store the element in the variable and then call price.innerHTML to place your result in the DOM. Like such:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}
}
EDIT: As talemyn correctly points out, you should use .value rather than .innerHTML for altering the contents of textareas. While it might look like it does the same thing, there are slight disadvantages that come with the use of .innerHTML.
You should not assign a value to price and then overwrite it... That's what your code is doing. I believe you think you are creating a storage location in the innerHTML?
Instead, just create the variable:
var price;
Run your code as you did; and then put the result into the page with
document.getElementById("text area").innerHTML = price;
You're setting the 'price' variable twice with two separate things. You're not actually changing the DOM. Instead use:
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}

empty value of option's element

I have a similar problem like old problem of mine.
my code:
function reset_admin()
{
a = document.getElementById('event').value;
t = document.getElementById('category').value;
document.getElementById('admin').reset();
document.getElementById('event').value = a;
document.getElementById('category').value = t;
}
<form id="admin" action="iframe_admin.php" onsubmit="" method="post" target="iframe_admin">
.....
<input type="button" class="filter_button" id="Clear" name="Clear" value="Clear"
onclick="reset_admin();document.getElementById('admin').submit(); />
the function is in external js file.
the propose is that after pressing on clear, the event and the category will stay the same before the clear.
In ff it's works. In IE the event and the category are empty and than the page get stacked.
I tried to do:
function reset_admin()
{
a = document.getElementById('event').options[getElementById('event').selectedIndex].value;
t = document.getElementById('category').options[getElementById('category').selectedIndex].value;
document.getElementById('admin').reset();
document.getElementById('event').value = a;
document.getElementById('category').value = t;
}
but this is not working as well.
thank you!
Store and restore the selectedIndex instead since you don't care about the actual value, like this:
function reset_admin()
{
var a = document.getElementById('event').selectedIndex,
t = document.getElementById('category').selectedIndex;
document.getElementById('admin').reset();
document.getElementById('event').selectedIndex = a;
document.getElementById('category').selectedIndex = t;
}
I also added var to the indexes your fetching, just to about the global variables there, but that's not the important change, setting selectedIndex instead is :)
You can give it a try here.

Categories