Catching a textbox value which is stored in a variable - javascript

This is my controller.
public class HomeController : Controller
{
public static string commString = "";
public HomeController()
{
FWUtility.connString = "data source=.;initial catalog=northwind;uid=sa;password=123";
}
public ActionResult Index()
{
return View();
}
public static DataTable GetData(string customerID)
{
string strFilter = "'" + customerID + "%'";
commString = "select * from customers where CustomerID like " + strFilter;
return FWUtility.GetDataTable(commString);
}
This is the view.
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
alert('#HomeController.GetData("D").Rows.Count.ToString()');
}
</script>
<input type="text" id="text1" value="A" />
<input type="text" id="text2" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
I want to catch the value which is stored in the textbox and display it in the alert box, where I have mentioned "D". In my controller I have a sql query assigned.And here I am calling the controller. My out put will be suppose I put "A" inside the text box and click the button, i will get the count of all the names starting with letter "A". Like this

It's not clear from the question, but assuming you want more than a simple alert(value), then:
I suggest that you add an additional action to go with the GetData function to return row count directly:
public ActionResult GetDataRowCount(string id)
{
var count = GetData(id).Rows.Count;
return new JsonResult
{
Data = new { count },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
then you can use jquery ajax to get this value from the controller:
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.get({
url: '#Url.Action("GetDataRowCount", "Home")',
data: { id = value },
success: function(result) {
alert(result.count);
}
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />

Well, done it at last. Here is the solution.
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.ajax({
url: '../Home/GetData',
method: 'POST',
data: { customerID: value },
success: function (data) {
result = data;
alert(result);
},
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />

Related

Javascript function keeps retrieving data from last item in Model list in MVC

I am trying to create functionality that will update a product's quantity in the users shop cart. I am able to populate the ViewModel with the relevant data and display it in a table in the View.
In the script tags, I have two functions, one to increase the quantity of the product and the other to decrease the quantity in increments of 1. Now all works well if there is one product in the list. I receive the correct values. As soon as there are two or more products in the list, whenever the increase or decrease functions are fired, the values (quantity and productId) of the last item in Model.Products are sent to the 'UpdateQuantity' ActionMethod, instead of the values from the inputs in the selected table row.
For example: If there are two products in the list. Product A (Id:1 and Quantity: 3) and Product B(ID:2 and quantity:5), If I click on either the increase or decrease buttons next to Product A's quantity input, the relevant function will pass Product B's values (2 and 5) to the Action Method instead of Product A's values (1 and 3).
I'm assuming that there is a naming convention issue, but I'm unable to figure out why this is happening. Any help would be highly appreciated.
Below is what I have so far:
ViewModel:
public class ShopCartViewModel : BaseViewModel
{
public List<OrderDetail> OrderDetailList { get; set; }
public List<Order> OrderList { get; set; }
public List<Product> Products { get; set; }
}
Controller:
public List<Order> orderList = new List<Order>();
public List<OrderDetail> orderDetailList = new List<OrderDetail>();
public List<Product> productList = new List<Product>();
public ActionResult Index()
{
ShopCartViewModel vm = new ShopCartViewModel();
ConnectToDatabase();
User u = Helpers.GetUser.GetUserDetails();
orderList = GetAllOrdersForCustomer(u.Id);
GetOrderDetails();
vm.OrderList = orderList;
vm.OrderDetailList = orderDetailList;
vm.Products = productList;
return View(vm);
}
[HttpPost]
public ActionResult UpdateQuantity(string quantity, string productId)
{
//do stuff here
}
View:
#foreach(var product in Model.Products)
{
string class_quantity = "quantity_" + product.Id;
string class_productId = "productId_" + product.Id;
<div class="quantity">
<button class="dec-btn p-0" type="submit"><i class="fas fa-caret-left" onclick="q_dec()"></i></button>
<input name="quantity" id="#class_quantity" class=" form-control" type="text" value="#product.Quantity" />
<button class="inc-btn p-0" type="submit"><i class="fas fa-caret-right" onclick="q_inc()"></i></button>
<input name="productId" id="#class_productId" class=" form-control" type="text" value="#product.Id" style="visibility:hidden" />
<script type="text/javascript">
function q_inc(e) {
var p_quantity = $("##class_quantity").val();
var final_quantity = parseInt(p_quantity) + 1;
var p_productId = $("##class_productId").val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Increase Success");
}
})
}
function q_dec(e) {
var p_quantity = $("##class_quantity").val();
if (p_quantity >= 2) {
var final_quantity = parseInt(p_quantity) - 1;
}
var p_productId = $("##class_productId").val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Decrease Success");
}
})
}
</script>
</div>
}
The problem with your code is that in your loop you are duplicating functions q_inc(e) and q_dec(e)
You should fix your code with something like this:
#foreach(var product in Model.Products)
{
string class_quantity = "quantity_" + product.Id;
string class_productId = "productId_" + product.Id;
<div class="quantity">
<button class="dec-btn p-0" type="button" onclick="q_dec('#class_productId', '#class_quantity")'><i class="fas fa-caret-left"></i></button>
<input name="quantity" id="#class_quantity" class=" form-control" type="text" value="#product.Quantity" />
<button class="inc-btn p-0" type="button" onclick="q_inc('#class_productId', '#class_quantity')"><i class="fas fa-caret-right"></i></button>
<input name="productId" id="#class_productId" class=" form-control" type="text" value="#product.Id" style="visibility:hidden" />
}
<script type="text/javascript">
function q_inc(id, quantity) {
var p_id = $("#" + id);
var p_quantity = $("#" + quantity);
var quantity_val = p_quantity.val()
var final_quantity = parseInt(quantity_val) + 1;
var p_productId = p_id.val();
$.ajax({
url: '#Url.Action("UpdateQuantity","ShopCart")',
type: 'POST',
data: {quantity: final_quantity, productId: p_productId },
success: function () {
alert("Increase Success");
p_quantity.val(final_quantity);
}
})
}
function q_dec(id, quantity) {
// change this function accordingly
</script>

Javascript Select Child With Id Formatting

Programming a ASP.net webapp to insert an entry into a database on form submit.
I've tried numerous configurations of find() and children() and they either
1) error
2) pass empty strings instead of what I type
This one errors like this:
Whats the correct way to select the individual children of myform?
Javascript (the first block here is the code I'm asking about)
var entry_array = [];
entry_array[0] = $('#myform').children('#01').css().text();
entry_array[1] = $('#myform').children('#02').css().text();
entry_array[2] = $('#myform').children('#03').css().text();
entry_array[3] = $('#myform').children('#04').css().text();
$(document).ready(function () {
$("#myform").submit(function () {
alert("Function ran");
$.ajax({
url: 'Home/SubmitEntry', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
datatype: 'json',
traditional: true,
data: { 'entry_array': entry_array },
success: function(response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
alert("Function finished running");
});
});
Controller
[HttpPost]
public ActionResult SubmitEntry(List<String> entry_array)
{
String firstname = entry_array[0];
String lastname = entry_array[1];
String town = entry_array[2];
String order = entry_array[3];
knightsEntities db = new knightsEntities();
int nextiD = 0;
nextiD = db.Apprentenceship_Sheet.ToList().Last().id + 1;
var newApprentenceship_Sheet = new Apprentenceship_Sheet();
newApprentenceship_Sheet.first_name = firstname;
newApprentenceship_Sheet.last_name = lastname;
newApprentenceship_Sheet.hailed_town = town;
newApprentenceship_Sheet.order = order;
newApprentenceship_Sheet.id = nextiD;
db.Apprentenceship_Sheet.Add(newApprentenceship_Sheet);
db.SaveChanges();
return View();
}
View
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="~/scripts/custom.js"></script>
#{
ViewBag.Title = "Home Page";
}
<div>
<form id= "myform" method="post">
First_name:<br>
<input type="text" id="01" name="firstname"><br>
Last_name:<br>
<input type="text" id="02" name="lastname"><br>
Town:<br>
<input type="text" id="03" name="town"><br>
Order:<br>
<input type="text" id="04" name="order"><br>
<br>
<input type='submit' id="05" name="Submit">
</form>
</div>
You can get the values of the text boxes directly by using $('#01').val(), or if you want refer it with reference to your form. You can use $('#myform').find('#01').val(). It will give the value of the text-box. Here is the jsfiddle for u.
$('#myform').find('#01').val()
$('#01').val()
http://jsfiddle.net/71weztcn/

grails button to do ajax call to change textbox

I have a method in my controller
def returnJames = {
JSONObject jsonObject = new JSONObject()
jsonObject.put("name","James")
return jsonObject
}
and then I have a view:
<html>
<!--import gsp that has all the jquery imports-->
<script>
function changeName()
{
$.ajax({
url:"<g:createLink url="[action:'returnJames',controller:'mycontroller']" />",
dataType: "json",
asnyc: false,
success: function(data) {
$('mytextbox').val(it.name)
}
});
}
</script>
<g:form controller="mycontroller" method="post" >
<g:textField name="mytextbox" value="" />
<button name = "mybutton" id = "mybutton" onclick="changeName()">change name</button>
</g:form>
</html>
However it just tries to change the page to the index view of the mycontroller controller which doesn't exist. How can I get it to just fill in the textbox with "James"?
User render instead of return
render jsonObject
and change in jQuery
success: function(data) {
$('#mytextbox').val(data.name)
}
change button to
<input type="button" id = "mybutton" onclick="changeName()" value="change name"/>

why when my action returns a view - it passes first through a javascript function

In the Index view I just have a button with a javascript function for when it's clicked:
<script>
function AddCat() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategory")',
data: {},
});
}
</script>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name", Session["langID"] ?? "1"), new { id = "ddlLanguages" })
<div id="categoriesPlace"></div>
<input type="button" id="btnAddCategory" onclick="AddCat()" value="AddCategory" />
When I click on the button, as you see I should be redirected to the AddCategory action, which adds a record in the database and returns the AddCategory view. The problem is that when it reaches the drop-down in my AddCategory view, it goes straight to the Addbtn_CLick() function as if it's clicked and then it redirects me to the Index action. Can you explain this behavior?
So, here is my CategoryController:
public class CategoryController : Controller
{
public ActionResult AddCategory()
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddNewCategory();
return View(vm);
}
public ActionResult AddCategoriesLanguages(int catID, int lanID, string title, string shrtDescription, string description)
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddCategoriesLanguages(catID, lanID, title, shrtDescription, description);
return RedirectToAction("Index");
}
}
And, here is my AddCategory view:
#model Onion.Web.ViewModels.CategoryViewModel
#{
ViewBag.Title = "AddCategory";
}
<h2>AddCategory</h2>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name",#HttpContext.Current.Session["langID"]),new { id = "ddlLanguages" })
<br />
<label for="txbTitle">Title:</label>
<input type="text" id="txbTitle"/>
<br />
<label for="txbShortDescription">Short Description:</label>
<input type="text" id="txbShortDescription" />
<br />
<br />
<input type="button" id="btnAdd" onclick="btnAdd_Click" value="Add" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
function btnAdd_Click() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategoriesLanguages")' + '?catID=' +#Model.newCategoryID +'&lanID=' + $("#ddlLanguages").val() + '&title=' + $('#txbTitle').val() + '&shrtDescription=' + $('#txbShortDescription').val() + '&Description=' + $('#txbDescription').val(),
data: {}
});
}
</script>
In your AddCategory view, try changing your button's onclick attribute to include the function name and parenthesis as shown below:
<input type="button" id="btnAdd" onclick="btnAdd_Click()" value="Add" />
I am not 100% sure if that is the issue, but it stood out to me.

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/

Categories