How to pass value of textbox to a method in controller? - javascript

In Angularjs, I'm trying to pass a value from a textbox to method written in controller as below
#Try 1
<input type="text" ng-blur="isExists(this.value)">
and within my controller I have
$scope.isExists = function (theValue) {
alert(theValue);
};
It is not working.
#Try 2
<input type="text" ng-model="username" ng-blur="isExists()">
and within controller
$scope.isExists = function () {
alert($scope.username); // returns undefined
};
How to pass value from ng-blur to a method within a Controller?
Updates:
Any reason why the valueis not seen in the textbox?
<input type="text" ng-model="username" ng-blur="isExists()">
Fiddle

Try2 should not return undefined if the <input type="text"
is filled with at least one character.
You can append {{ username }} on the html page just for debug purporses to make sure it was well binded.

<input type="text" name="userId" id="txtid" />
<script type="text/javascript">
$(document).ready(function () {
$('#txtid').blur(function () {
debugger;
var id = $('#txtid').val();
window.location = "/Home/CreateSupplier/?userid=" + id;
});
});
</script>
In controller
public ActionResult CreateSupplier(string userid)
{
if (userid != null)
{
return Content("Received Username:" + userid);
}
return View(thesupplierList);
}

Related

cant get the value of input with oop js

Hello I am trying to get the input value from a form input using oop js.
When I get the username I want to validate it but I cant get the value of username.
when I console.log(username); I either get undefined or the html markup instead of the value. What am I doing wrong?
my form
<form action="" method="post">
<input type="text" name="username" id="username">
</form>
and my js
<script type="text/javascript">
validateForm = {
username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid : function() {
$('#username').on('keyup change', function() {
console.log(this.username);
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
alert('bad')
} else {
alert('good');
}
});
}
};
validateForm.checkUsernameValid();
</script>
Call either this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')); or this.username = $('#username').val(); inside your keyup event to set the value
validateForm = {
username : $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid : function() {
$('#username').on('keyup change', function() {
this.username = $.trim($('#username').val().toUpperCase().replace(/\s+/g, ''));
console.log(this.username);
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
// alert('bad')
} else {
// alert('good');
}
});
}
};
validateForm.checkUsernameValid();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input type="text" name="username" id="username">
</form>
I either get undefined or the html markup instead of the value.
As you have set the name and id attributes so it gets available in the global scope as a whole so, html element gets logged in console.
You should not bind the event in the method such way. You can call the method in the bound event and make the method to accept the value as an argument such as:
validateForm = {
username: $.trim($('#username').val().toUpperCase().replace(/\s+/g, '')),
checkUsernameValid: function(value) { // 2. get the value
this.username = value; // 3. set the value
if (/^[a-zA-Z0-9]*$/.test(this.username) == false) {
console.log('bad')
} else {
console.log('good');
}
}
};
$('#username').on('keyup change', function() {
validateForm.checkUsernameValid(this.value); // 1. pass the input value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input type="text" name="username" id="username">
</form>

validation in form not working

I don't know what im doing wrong, i have a form and using this function to check if the input is empty...what Iam trying to do is to highlight the field by adding a class to the text field...but if i add this line
name.addClass("empty");
to the function, the function dont work
function register()
{
if(document.myForma.userid.value == '')
{
name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required")
name.addClass("empty");
return false;
}
}
Declare your name variable as local, or use a different name for it, - global window.name already exists and is not changeable.
console.log(name);
function register() {
if (document.myForma.userid.value == '') {
var name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required");
name.addClass("empty");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForma" name="myForma" onsubmit="return register();">
<input id="userid" type="text" />
<div id="empty"></div>
<input type="submit" />
</form>

using $watch in angularjs

I have a form with 2 input fields and requirement is that once user enters valid data into these
fields, I need to pass the input data to the factory function and get the data from server.To achieve this I thought of using $watch function but stuck at how to know if form is valid in $wathc function and then call the factory function to get data from the server.Here is the code.
Any help would be highly appreciated.
//html
<html>
<body ng-app="myModule">
<div ng-controller="myCtrl">
Product Id: <input type="text" ng-model="myModel.id" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" /><br/>
</div>
</body>
</html>
//js
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', function($scope){
$scope.myModel = {};
var getdata = function(newVal, oldVal) {
};
$scope.$watch('myModel.id', getdata)
$scope.$watch('myModel.productname', getdata)
}]);
Wouldn't you just watch myModel, since the same function is called in both cases?
You could do this with ng-change just as easily.
<html>
<body ng-app="myModule">
<form name="productForm" ng-controller="myCtrl">
<div>
Product Id: <input type="text" name="idModel" ng-model="myModel.id" ng-change="validateID()" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" ng-change="validateProduct()" /><br/>
</div>
</form>
</body>
And your JS would look like this:
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', 'myFactory',
function($scope, myFactory){
$scope.myModel = {};
$scope.validateID = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
$scope.validateProduct = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
}
]);
Using ng-change saves you from having to add a $watch to your scope (they are expensive) and will fire when the user leaves the input box. If you need to catch each keystroke, I would recommend that you use UI-Keypress and run the same functions.
To know if form is valid you have to add a form tag and inside your controller check $valid, on your example the form is always valid becaus you do not have any required field.
See the below example on codepen
The HTML
<div ng-app="myModule">
<div ng-controller="myCtrl">
<form name="myform" novalidate>
Product Id:
<input type="text" ng-model="myModel.id" />
<br/>
Product Name:
<input type="text" ng-model="myModel.productname" />
<br/>
</form>
<br/>
<div>{{result}}</div>
<div>Form is valid: {{myform.$valid}}</div>
</div>
</div>
The JS
var myModule = angular.module('myModule', []);
myModule.controller('myCtrl', ['$scope', function ($scope) {
$scope.myModel = {};
$scope.result = "(null)";
var getdata = function (newVal, oldVal) {
var valid = null;
if ($scope.myform.$valid) {
valid = "is valid";
} else {
valid = "is INVALID";
}
$scope.result = "Changed value " + newVal + " form " + valid;
};
$scope.$watch('myModel.id', getdata);
$scope.$watch('myModel.productname', getdata);
}]);

How can send array as an data using ajax

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
<input type="text" id="txt11" name="txt11" value="name1" />
<input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
<input type="text" id="txt21" name="txt21" value="name3" />
<input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />
(function ($) {
$(document).ready(function () {
alert("serialize data :" + $('.myclass').length);
var mydata = null;
$('#button').on('click', function (e) {
$('.myclass').each(function () {
alert("serialize data :" + $(this).serialize());
if ((mydata === null) || (mydata === undefined)) {
mydata = $(this).serializeArray();
alert("My data is null");
} else {
mydata = $.merge(mydata, $(this).serializeArray());
alert("My data final data after merger " + test);
}
});
});
});
}(jQuery));
Try this:
var array = $('input[type="text"]').map(function() {
return $(this).val();
}).get();
alert(JSON.stringify(array));
Demo.
You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
formdata.push($(this).serialize());
});
var data = formdata.join('&');
http://jsfiddle.net/6jzwR/3/

Trigger NgChecked in Angular JS

I need to work out a way of triggering NgChecked to re-evaluate it's expression after a user submits a form (which reloads the data). Ideally the trigged would be after the data has been reloaded, so the checkbox state is in line with that of the data and the amendments that have been made.
I've tried calling the expression directly after loadData() is called, however to no avail.
Do I instead need to use something like NgUpdate?
Any suggestions would be very much appreciated. Please see my code below:
view.html
<form ng-submit="updateinfo(item.downloadID); showDetails = ! showDetails;">
<input class="form-control" style="margin:5px 3px;" type="text"
ng-model="item.title" value="{{item.title}}"
placeholder="{{item.title}}"/>
<div class="checkbox" style="margin:5px 3px;">
<label for="downloadLive">
<input name="downloadLive" type="checkbox" ng-model="item.dlLive" ng-checked="liveCheckBoxState(item.dlLive);" ngTrueValue="1" ngFalseValue ="0"> Download live
</label>
</div>
<input class="btn btn-default form-control" style="margin:5px 3px;" type="submit"/>
</form>
controllers.js
// a scope function to edit a record
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/'+id,
data : result
});
$scope.loadData();
};
//return correct state checkbox for downloadlive
$scope.liveCheckBoxState = function(dlLive) {
console.log(dlLive);
if (dlLive == 1) {
return true;
} else {
return false;
};
};
// a scope function to load the data
$scope.loadData = function () {
$http.get('/view1/downloadData').success(function (data) {
$scope.items = data;
});
};
$scope.loadData();

Categories