Scripts
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Field2").rules("add", { regex: "^[a-zA-Z0-9]{0,3}$" });
$.validator.addMethod(
'regex',
function (value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
}, "My Error Message");
$('#MyForm').validate(
{
rules: {
Field1: {
required: false,
range: [1, 9999999999]
}
},
messages: {
Field1: {
range: jQuery.validator.format("Please enter a value between {0} and {1}.")
}
}
,
highlight: function (element) {
$(element).closest('.MyForm').removeClass('success').addClass('error');
},
success: function (element) {
}
});
});
</script>
Form
<form action="#" id="MyForm" name="MyForm">
<table id="tblData">
<tr>
<td>
<label>
Field1</label>
<input id="Field1" name="Field1" type="text" value="" />
</td>
</tr>
<tr>
<td>
<label>
Field2</label>
<input id="Field2" name="Field2" />
</td>
</tr>
<tr>
<td>
<span id="submitButton" class="k-button">Next</span>
<input type="submit" class="button" name="submitButtonTest" id="submitButtonTest"
value="Validation Test">
</td>
</tr>
</table>
</form>
Issue
$.data(...) is undefined
Not validating Field1.
Not showing error messages
JSFiddle
Demo is here
You can't define a rule for a field before you enable validation for the form that contains it. So you need to put
$("#Field2").rules("add", { regex: "^[a-zA-Z0-9]{0,3}$" });
after
$("#myForm").validate(...);
FIDDLE
If you want to specify a message when adding the rule, you can do:
$("#Field2").rules("add", {
regex: "^[a-zA-Z0-9]{0,3}$",
messages: {
regex: "Must be 0 to 3 alphanumeric characters"
}
});
See the documentation of .rules()
Related
Controller code I have :
<?php
class Ajax_cntrl extends CI_controller{
public function index(){
$this->load->view('ajax_view');
$insert = array(
'name' => $this->input->post('name'),//<-- also not able to get this id from ajax post request
'pass' => $this->input->post('pass'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->db->insert('form',$insert);//<--insert item into cart
$query;// to insert into database
//redirect('shop');
}
}
?>
view code I have ::
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Pass</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
pass: $('#pass' + id).val(),
email: $('#email' + id).val(),
mobile: $('#email' + id).val(),
address: $('#email' + id).val()
};
$.ajax({
type:'post',
url:"<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
</script>
problem is that when i am submitting the form it refreshing the browser ajax not working where is the fault m not able to understand please help me related in this why ajax call is not working there and is that a gud way to implement ajax with codeigniter ?? if yes then y its not working
Use below code, this will fix your issue.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {//repair
name: $('#name').val(),
pass: $('#pass').val(),
email: $('#email').val(),
mobile: $('#mobile').val(),
address: $('#address').val()
};
$.ajax({
type: 'post',
url: "<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data,
dataType: 'json',
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
});
</script>
Let me know if it not works for you.
I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.
I have a very simply page at the moment. It has a first name input, last name input, and a list of names added. You can add your first and last name to the text box, press add. It adds it the peopleList I have and adds a new listItem with their name.
My issue is when I add to the peopleList in my code, it does not update the listView. I think I need to use observable, but I am not exactly sure how to do it. My list shows it has 25 items added to it after I click btnMany, which is how many it show have.
here is the body of my code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="ViewModel"
data-layout="default">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<a data-bind="click: setValues" data-role="button" id="btnMany">Add Many</a>
<div style="margin-top: 10px">
People List:
<ul data-template="people-l-template" data-bind="source: peopleList" id="pList"></ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
<li>
FirstName: <span data-bind="text: first"></span>
LastName: <span data-bind="text: last"></span>
<a data-bind="click: removeName" data-role="button" id="btnRemoveName">X</a>
</li>
</script>
And here is my script to go along with it
<script>
var ViewModel = {
firstName: '',
lastName: '',
peopleList: [],
addName: function (e) {
this.get("peopleList").push({
first: this.get("firstName"),
last: this.get("lastName"),
});
this.set("firstName", '');
this.set("lastName", '');
},
removeName: function (e) {
this.set("peopleList", jQuery.grep(this.peopleList, function (item, i) {
return (item.firstName != e.data.firstName && item.lastName != e.data.lastName);
}));
},
setValues: function (e) {
GetValueFromServer();
}
};
var GetValueFromServer = function () {
$.ajax({
type: "GET",
url: "GetPeopleService.svc/GetPersonById/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.forEach(function (person) {
ViewModel["peopleList"].push({
first: person.firstName,
last: person.lastName
});
});
alert(ViewModel.peopleList.length);
},
error: function (response) {
console.log(response);
}
});
};
var application = new kendo.mobile.Application(document.body);
</script>
There were a few things wrong with the code you provided, the most notably being that you didn't set the role for your <ul> element. You need to change it to have the attribute data-role="listview". You also can't use an <li> element as the root element for a listview template (KendoUI automatically takes care of this for you), otherwise you'll get an error when the list is bound.
Here's an example on JS Bin.
And here's the code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="viewModel"
data-layout="flat">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<div style="margin-top: 10px">
People List:
<ul id="pList"
data-role="listview"
data-template="people-l-template"
data-bind="source: peopleList">
</ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
FirstName: <span>#:first#</span>
LastName: <span>#:last#</span>
<a id="btnRemoveName"
data-role="button"
data-bind="click: removeName"
data-first="#:first#" data-last="#:last#">
X
</a>
</script>
...
var viewModel = {
firstName: null,
lastName: null,
peopleList: [],
addName: function (e) {
var me = this;
me.get('peopleList').push({
first: me.get('firstName'),
last: me.get('lastName')
});
me.set('firstName', '');
me.set('lastName', '');
},
removeName: function (e) {
var me = this;
me.set('peopleList', $.grep(me.peopleList, function (item, i) {
return item.first != e.target.data('first')
&& item.last != e.target.data('last');
}));
}
};
var application = new kendo.mobile.Application(document.body);
Hi Friends i am trying to use knockoutjs on one of my web pages in mvc
razor. From the following ViewModel i am achieving the "ADD MORE"
functionality.But My Problem is that how can we achieve the following
functionality:
(1) The second dropdown should be invisible when the dropdown for
"Type of Tobacco" is selected to "Choose..."
(2)When we choose some other value (other than "Choose") second
dropdown should be populated containing value 1 to 10....
(3) When we select "Others" instead of drop down a textbox should
appear
HERE IS MY ATTEMPT:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script type="text/html" id="ddlSelection">
<div><select></select> yrs.</div>
<div><input type="text" data-bind=""></input></div>
</script>
<div id="container">
#*<div data-bind="template:{name:'smoker'}"></div>*#
<table cellpadding="3" cellspacing="4">
<tbody data-bind="foreach: seats">
<tr>
<td>
Type of Tobacco/Nicotine consumed :
</td>
<td>
<select data-bind="options: $root.availabledrugs, value: Drug, optionsText: 'DrugName'"></select>
</td>
<td><select></select></td>
</tr>
<tr>
<td>
Quantity : <input data-bind="value: Name" />
</td>
<td>
Frequency : <select data-bind="options: $root.availablefrequency, value: Frequency, optionsText: 'frequency'"></select>
</td>
<td data-bind="text: FormatPrice"></td>
</tr>
</tbody>
</table>
<button data-bind="click:AddConsumption">Add New One</button>
</div>
<script type="text/javascript">
function setconsumption(name, initdrug,initfrequency) {
var self = this;
self.Name = name;
self.Drug = ko.observable(initdrug);
self.Frequency = ko.observable(initfrequency);
self.FormatPrice = ko.computed(function () {
return self.Drug().Price ? "$" + self.Drug().Price.toFixed(2) : "none";
});
}
function ConsumptionViewModel() {
var self = this;
self.availabledrugs = [{ "DrugName": "Choose...", "Price": 0 },
{ "DrugName": "Cigarettes", "Price": 10 },
{ "DrugName": "Cigar", "Price": 20 },
{ "DrugName": "Others", "Price": 30}];
self.availablefrequency = [{ "frequency": "Choose..." }, { "frequency": "freq1" }, { "frequency": "freq2"}];
self.seats = ko.observableArray(
[new setconsumption("", self.availabledrugs[0], self.availablefrequency[0])]);
self.AddConsumption = function () {
self.seats.push(new setconsumption("", self.availabledrugs[0], self.availablefrequency[0]));
};
}
ko.applyBindings(new ConsumptionViewModel());
</script>
Its hard to guess for me that what you are trying to achieve. But i think you are looking for visible binding in knockout.
The visible binding causes the associated DOM element to become hidden or visible according to the value you pass to the binding.
And second think should be the optionsCaption comes under options binding.
If you use optionsCaption with options binding than ko will prepend an extra option in the select list, which will be selected by default and contains value undefined.
By using this both i have create a fiddle according to your requirement. Check this:
Demo fiddle
Hope this is what you are looking for!
I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>