Getting the value inside a textbox ng-model using javascript .value - javascript

I'm currently confuse in trying to obtain the value inside a text box using jquery .value
<input class="input referral-code" disabled="true" ng-model="account.referral_code_string" id="input-refcode">
I tried using document.getElementById('input-refcode').value to try to obtain the value but it comes out as empty on my console.
But if I tried binding it onto a on-click event, it manages to obtain the value stored inside the ng-model
$('.trigger').on('click', function(){
console.log(document.getElementbyId('input-refcode'))
});
As you can see there is a value inside the text box itself. But when you tried inspecting it, this is what came out.
<input class="input referral-code" disabled="true" ng-model="account.referral_code_string" id="input-refcode">
If you look at there is no value inside the input textbox. I'm not sure if it has something to do with angular.js

You can get the scope object using element
var scope = angular.element(document.getElementById('input-refcode')).scope();
var desiredValue = scope.account.referral_code_string;

This might help you.
inject $timeout service in controller
$timeout(function(){
console.log(document.getElementById('input-refcode')); },200);
Note: Use capital B in getElementById not getElementbyId.

var app = angular.module('todoApp', []);
app.controller('TodoListController', function($scope){
$scope.$watch('referral_code_string'), function(){ console.log($scope.referral_code_string)};
console.log(document.getElementById('input-refcode').value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="todoApp" ng-controller="TodoListController as todoList">
<input class="input referral-code" disabled="true" ng-model="referral_code_string" ng-init="referral_code_string = 'abc'" id="input-refcode" value="abc">
</div>

Related

AngularJS passing data to Javascript variables and opposite

I am looking for a solution on passing data from a specific input text field to AngularJS. it may be a Javascript variable too. If the variable is changed from inside a javascript code it is not updating on AngularJS side. If i take the same variable and in the text field add at least one character or modify something i see variable updating and everything working as it should.
I tried something with angular.element(document.getElementById('ControllerElementID')).scope().funct(); but still no luck. When i update at least one field from the keyboard, all text fields that are related to "ng-model="sig.sigBase6422"" are updating properly as it should. If i call this updates through a JavaScript function i see updates only on specific text field and no updates at all on ng-model happening. How to make it updating as simple as possible? Below i will post a small example. I was able to store data from variable to a external file and in AngularJS read it from file and use it. this is way too long, complicated and ridiculous. I am sure there should be a better way.
Thank you!
<script type="text/javascript">
function addtext1() {document.getElementById("myID1").value = "1111111111111111";}
function addtext2() {document.getElementById("myID2").value = "2222222222222222";}
</script>
<div>
<form action="#" name="FORM1">
<TEXTAREA NAME="sigData" ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" ><br>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" ><br>
<p>Value {{sig.sigBase6422}}!</p>
</div>
<!-- test field -->
Add text 1
Add text 2
Indeed if you want to use AngularJS for what it was created, you have to rewrite your code completely using directive or controller. You variables and functions accessible from the view should be attached to the $scope too.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
$scope.addtext1 = function () {
$scope.sig.sigBase6422 += "1111111111111111";
};
$scope.addtext2 = function () {
$scope.sig.sigBase6422 += "2222222222222222";
};
$scope.sig = {
sigBase6422: ""
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form action="#" name="FORM1">
<TEXTAREA ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br/>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" /><br/>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" /><br/>
<p>Value {{sig.sigBase6422}}!</p>
<!-- test field -->
<button ng-click="addtext1()">Add text 1</button>
<button ng-click="addtext2()">Add text 2</button>
</div>
You seem to have misunderstood how angular works. What you're trying to do is not how angular works. What you're trying to do with native JavaScript can be done with angular. Angular can update dom and Dom updates angular as it's responsible for causing updates.... anyway without getting any deeper. You need to read more on how angular works and try sticl within the bounds of angular instead of mixing.
That being said :
Tigger change on the Dom element after you have updated its value. Or better yet get access to scope variable on the Dom and call a function in angular with the value you're and set they value from inside of a angular.
Use this code while updating the value.
pick the controller first using
var scope = angular.element(document.getElementById('yourControllerElementID')).scope();
scope.<variablename> = <your operation>;
then
scope.$apply();
the remaining thing will be taken care by Angular.

getting values from sessionStorage

I am trying to get the value from sessionStorage and map it to my ng-model, but
when i do that in my ng-init its not working.
The problem is in my actual code i am inside a ng-repeat so my sessionStorage becomes like below:
sessionStorage.getItem(item.itemId)
HTMl Code:
<div ng-app="">
<div ng-controller="MyCtrl">
Not Working <input ng-init = 'name = sessionStorage.getItem("SavedString")' type="text" ng-model="name" >
Working <input type="text" ng-model="name1" >
</div>
</div>
Controller:
function MyCtrl($scope) {
sessionStorage.setItem("SavedString","I'm a value saved with SessionStorage");
//RETRIEVE VALUE
$scope.name = "test"
$scope.name1 = sessionStorage.getItem("SavedString");
$scope.hi = 'Hello World';
}
Fiddle:
http://jsfiddle.net/393revrn/
i too tried in your way but i didn't find a the requirements to achieve this ......so i tried with making a function call with in init and appended session data to that model then i can see the proper output by making ng-init ='some()' here is the working plunker
UPDATE
From some source i found that HTML cannot understand session variables directly.
The sessionStorage, when accessed from the ng-init directive, is not understood by Angular; it will be parsed and interpreted as if it were a $scope function (which, I assume, is not).
So, in order for your example to work, you should do something like this in your controller:
$scope.sessionStorage = sessionStorage;

HTML input has both {{}} and ng-model

I have a form which contains two input fields, I want to sync the next input field when user is typing in the first input field by default, and user can edit the second field as they like, below code works fine:
<input type="text" ng-model="name">
<input type='text' value='{{name}}'>
<button ng-click='submit()'>submit</button>
However, to be able to get the value of second field, I need to put ng-model to the second field, and once I put ng-model, it won't sync anymore.
This is the example
How should I get the second field's value if I don't put a ng-model to it.
Thank you.
You can use ng-change. When user changes input 1 the ng-change method will be called and input2 will be updated .but when user change input 2 nothing will be called .
<DIV ng-app='app'>
<form ng-controller='myController'>
<input type='text' ng-model='name' ng-change="callMe()"/>
<input type='text' ng-model="name2" />{{name2}}
</form>
</DIV>
and controller js
var app = angular.module('app', []);
app.controller('myController', function($scope){
$scope.callMe =function(){
$scope.name2=$scope.name;
}
//$scope.name
//$scope.name2
})
update fiddle example
You could use the $scope.$watch Method for your needings.
I have updatet your fiddle.
What i did is easy, everytime the model changes, the $watch will be called with the new value of the model, then you just need to copy the value into the second model.
First approach that came to my mind was to ng-bind a property with a setter that would do what you want:
<input type='text' ng-model='nameModel' />
then
app.controller('myController', function($scope) {
Object.defineProperty($scope, 'nameModel', {
get: function() { return $scope.name1; },
set: function(x) { $scope.name1 = $scope.name2 = x; }
});
});
This causes any edit to nameModel to affect both name1 and name2.
Fiddle
You could do a similar wrapper around name2 to track whether it has ever been modified (dirty/pristine), and have nameModel only change scope.name2 if it is pristine.
Fiddle with better user experience
(If you're using Angular forms, it tracks the field status for you, so you could directly look at form.name2.$pristine.)
It seems that what you need is to set the value to the scope variable.
So your code would then look like this:
<input type="text" ng-model="name">
<input type='text' value="{{name}}" ng-model="somethingelse">
<button ng-click='submit()'>submit</button>
Hope that helps.

cannot get value of inputs wrapped by ng-if

I can not get value of input wrapped by ng-if
this is html code
<div ng-controller="Home">
<form ng-submit="startChat(visitor)" >
<div class="lkv_getting">
<div ng-if="formsetting.name == true">
<input required ng-class="lkv_name_class" ng-model="visitor.name" id="lkv_name" name="lkv_name" type="text" class="lkv_input" placeholder="Nhập họ tên" />
</div>
<textarea required maxlength="100" placeholder="Gõ tin nhắn!!" ng-model="visitor.msg" id="message_input" name="lkv_message_input"></textarea>
<button class="lkv_button" type="submit" id="lkv_start" title="Message">Bắt đầu</button>
</div>
</form>
</div>
and controller
$scope.startChat = function (visitor) {
var user = visitor.name; // the value is undefine
var msg = visitor.msg; // but this one has value
};
Any one can help me? Thanks in advance
When using ng-if the DOM elements won't get rendered if formsetting.name ever equals false. That means you won't be able to get your input values back since they won't be rendered to the DOM. Check to see that formsetting.name is indeed true or initialized to true in your controller if that makes sense for you. If formsetting.name can change values you probably want to use ng-show instead. Using ng-show draws the elements to the DOM but hides them so you can still access them.

Setting HTML textbox value using javascript function?

I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');

Categories

Resources