This is front end,
<div class="uk-width-1-4 ">
<table class="uk-table uk-table-striped uk-table-hover" id="tabledata">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>Site ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chkall" value="<%= d.siteid%>">
</td>
<td><%=d.siteid%></td>
</tr>
<% });
} %>
</tbody>
</table>
</div>
This is backend,
var user_id=req.query.user_id;
var siteid=req.query.chkall;
console.log("chkall =="+siteid);
sql="UPDATE site SET userid='"+user_id+"' WHERE siteid IN('"+siteid+"')";
}
getSQLData(sql, function(resultsets){
console.log("user...sql"+sql);
userresults = resultsets;
});
You can use it like this:
$("input[type='checkbox']").val();
Hope will help you.
If you are doing form submit, and if the check-box un-checked the false value will not go to the back-end. You should have some hidden value if check box un-checked.
If it is ajax call, you can get checkbox value as like below
$("input[type='checkbox']").val();
or
$("#checkboxid").val();
If you submit form then write name tag. And if you send data from ajax then get value by element id then send to server.
You do like this..
var chk = document.getElementById(checkboxid).checked;
if (chk == true) {
var chkval=$("#checkboxid").val();
}
If you have in list then do loop and add to a global variable and use that variable.
//check box
<asp:CheckBox ID="chkpermission" runat="server" onclick="checking(this.id);" Checked='<%# Convert.ToBoolean(Eval("permission")) %>' />
<script type="text/javascript">
function checking(id) {
$('#ctl00_ContentPlaceHolder1_lblresponce').val('');
if (id) {
ids = id.split('_');
var chkval = document.getElementById(id).checked;
var TitleId = "ctl00_ContentPlaceHolder1_grdpermissions_" + ids[3] + "_hdntitleid"; //here i am getting the value from the grid
var pagePath = window.location.pathname;
var param = JSON.stringify({ "TitleId": itleId,"chkval":chkval });
$.ajax({
type: "POST",
url: pagePath + "/updatevalue",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var result = data.d;
$('#ctl00_ContentPlaceHolder1_lblresponce').text('Updated successfully');
}
},
error: function () {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
}
</script>
in the back end code
[WebMethod]
public static Boolean updatevalue( string TitleId, string chkval)
{
Boolean flag = false;
if ( TitleId != "" && chkval !="")
{
//Update your your query here with single id...
flag=true;
// return flag if updated
}
return flag;
}
I hope it works in your case.
Related
I am having a simple table which shows basic details about cusotmers. Each customer belongs to one of available customer groups. I also have a dropdown on the top of it where I can toggle between available customer groups and want to update the table with customers belonging to that particular group. Right now everything happens using page reload which is quite inefficient I know. Is there a way to use js here and make only the table section refresh without reloading the entire page.
#GetMapping(WebControllerConstants.RIDER_MAPPING)
public ModelAndView riderMapping(#RequestParam(value = "groupId", required = false) String groupId) {
String group = "1";
if (groupId != null) {
group = groupId;
}
ModelAndView model = new ModelAndView("riderGroupDetails");
model.addObject("list", riderService.findRiderByGroupId(group));
model.addObject("riderGroupList", riderGroupService.findAllGroups());
return model;
}
<select id="category" name="category" onchange="GetAllDetails(this.value);">
//some options here
</select>
<table class="table table-striped table-bordered zero-configuration dataTable">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Mobile No</th>
</thead>
<tbody>
<c:set var="id" value="${1}" />
<c:forEach var="rider" items="${list}">
<tr>
<td>
<c:out value="${id}" />
</td>
<td>
<c:out value="${rider.firstname}" />
</td>
<td>
<c:out value="${rider.lastname}" />
</td>
<td>
<c:out value="${rider.mobile}" />
</td>
</tr>
<c:set var="id" value="${id + 1}" />
</c:forEach>
</tbody>
</table>
<script>
$(window).on(
'load',
function() {
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
if ($.urlParam('groupId') == false) {
} else {
var groupId = $.urlParam('groupId');
console.log('groupId ' + groupId);
$("#category").val(groupId);
}
});
function GetAllDetails(value) {
groupvalue = value;
console.log(groupvalue);
var url = "${context}/rider/mapping?groupId=" + value;
//AJAX works here to send a request but table doesn't refresh.
window.location = url;
}
</script>
//AJAX works here to send a request but table doesn't refresh.
Here your AJAX could listen to a response code. If the code says transaction happened correctly you could create a js function that updates the page info while not refreshing it. The new info can be handled from js from the begining or on the response you can pass the info to be updated and pass it to the redrawing function.
Example:
function updateDBService(request){
var dataStr = JSON.stringify(request);
var url = '/updateDBService';
$.ajax({
url: url,
contentType: "application/json",
data: dataStr,
type: "POST",
statusCode: {
403: function () {
},
404: function () {
},
500: function (data) {
}
},
//This is your response object (data), which you can use to update the onscreen info
success: function (data) {
redrawInfo();
},complete: function(data) {
}
});
}
For this I usually create a controller different from the views controller so I can handle response classes, request classes and all sorts of stuff. Here a controller that uses POST method would be required.
Hopefully this helps you!
As for my below code i am not able to get sectionID from tr, i need to get dynamic id of sectionID on each delete button click but it is always giving me null
Here is the Jquery Script :
<script>
$(function () {
$('.btnDelete').click(function () {
var sectionID = $(this).closest('tr').find('.sectionID');
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'CheckSectionIDagainststudentID',
data: JSON.stringify({ sectionID: sectionID.html() }),
success: function (data) {
if (data == true) {
$.alert("Cannot delete | Students exsisting in this
Section!");
}
else if (data == false) {
var secCode = JSON.parse(this.data);
var code = sectionid['sectionid'];
window.location.href = "SectionDelete?Page=data§ionid="
+ code;
}
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
and here is Razor Page
#foreach (var item in Model)
{
<tr class="sectionID">
<td >
#Html.DisplayFor(modelItem => item.sectionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td class="secCode">
<button style="width:49.5%" ID="Button2" type="button" onclick="location.href='#Url.Action("SectionEdit", "Section",new { id = item.sectionID, name = item.name })'">Edit</button>
<button style="width:49.5%" ID="deletebtn" runat="server" type="button" onclick="location.href='#Url.Action("SectionDelete", "Section",new { id = item.sectionID, name = item.name })'">Delete</button>
<button class="btnDelete">Delete</button>
</td>
</tr>
}
This is Controller Which i need to pass data to
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
return Json(sectionID);
}
As per your question you are not able to get value from var sectionID = $(this).closest('tr').find('.sectionID');
therefore here is a way you can achieve your result
//Your Dynamic Button should look like this
//in value Bind your sectionID # MVC
<button class="btnDelete" value="5" onclick="AjaxDelete(this)">Delete</button>
//For Function
function AjaxDelete(values) {
//Write this in Ajax
//Fetch Value from attribute value
var sectionID = $(values).attr("value"); // you will get 5 as value
//Your Ajax Call with SectionId as Parameter
}
Edit :
as you have got value
U can split the value by below code
where string is your var of sectionID
if ((~string.indexOf('\n '))) {
string= string.split('\n ')[1].split('\n')[0];
}
Use string array :
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string[] sectionID)
{
return Json(sectionID);
}
I am trying to do inline editing by cell, not by row, upon a double click. This much works but it won't update the record- the "SaveCustomer" call to controller isn't made. What is it that I'm doing wrong?
here is my index view file (part of it, the rest is irrelevant)
#foreach (var item in Model.Drivers)
{
<tr id="#item.ID">
<td id="id">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td id="lastName">
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td id="firstName">
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td id="seniority">
#if (item.Seniority != null) {#Convert.ToDateTime(item.Seniority).ToShortDateString()}
</td>
<td>
<td> //more go here </td>
Then here is the javascript file- sorry for the formatting, happens everytime I copy&paste
$("td").dblclick(function () {
if (!$(this).hasClass("edit")) {
var value = jQuery.trim($(this).html());
$(this).html("<input id=\"txtEdit\" type=\"text\" class=\"textbox\" value=\"" + value + "\" onblur=\"SaveValue(this, '" + value + "')\" onfocus=\"PutCursorAtEnd(this)\" />");
$(this).addClass("edit");
$("#txtEdit").focus();
}
});
function PutCursorAtEnd(obj) {
if (obj.value == obj.defaultValue) {
$(obj).putCursorAtEnd(obj.length);
}
}
function SaveValue(obj, oldValue) {
var value = $(obj).val();
$(obj).parent().removeClass("edit");
if (value != oldValue) {
var property = $(obj).parent().attr("id");
var id = $(obj).parent().parent().attr("id");
$.ajax({
type: "POST",
url: '#Url.Action("SaveCustomer", "save")',
data: { ID: id, Property: property, Value: value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: SaveCustomer_Success,
error: Error
});
}
else {
$(obj).parent().html(oldValue);
}
}
function SaveCustomer_Success(data, status) {
$(data.d.ID).parent().html(data.d.NewValue);
}
and lastly here is the controller method
public object SaveCustomer(int ID, string Property, string Value)
{
Driver driver = unitOfWork.DriverRepository.GetByID(ID);
switch(Property) {
case "id":
driver.ID = Convert.ToInt32(Value);
break;
case "firstName":
driver.FirstName = Value;
break;
case "lastName":
driver.LastName = Value;
break;
case "seniority":
driver.Seniority = Convert.ToDateTime(Value);
break;
}
unitOfWork.DriverRepository.Update(driver);
unitOfWork.Save();
return new
{
ID = ID,
NewValue = Value
};
}
Much help appreciated, thanks!
Remove following line from your ajax options because you are not sending json type data.
contentType: "application/json; charset=utf-8"
Since you are sending a POST request you have to add HttpPost attribute to controller. And also you are expecting json result, so your controller should be like below.
[HttpPost]
public JsonResult SaveCustomer(int ID, string Property, string Value)
{
/// ...
return Json(new { ID = 1, NewValue = 1 }, JsonRequestBehavior.AllowGet);
}
Try removing data, contentType and dataType from Ajax call and change the url to:
url: 'save/SaveCustomer?ID=' + id + '&Property=' + property + '&Value=' + value,
put a break point in the controller to see if the call hits it. There is no reason why it will not.
Use Chrome browser and open JavaScript console. You will see why it doesn't work, if it doesn't work after this change.
What I have here is a ajax checking the availability of information in database. But what my problem is I want to disabled the submit button if the others inputs/textboxes are empty. I add the disable function in my ajax but when one of the textbox has a value the disabled isn't working. Any help will appreciate.
Index.php
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="text"]').change(function()
{
var pr = $("#pr").val();
var msgbox = $("#status");
var txtbxs = $('.inputs').val();
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK' && txtbxs !== '')
{
msgbox.html('<img src="css/available.png" align="absmiddle">');
$("#save").prop("disabled",false);
}
else
{
$("#save").prop("disabled",true);
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
<tr>
<td>PR #</td>
<td><input type="text" name="pr" id="pr" autocomplete="off"></td>
</tr>
<tr>
<td></td>
<td><span id="status"></span></td>
</tr>
<tr>
<td>Date1</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<tr>
<td>Date2</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<input type="button" value="Save" id="save">
Check_ajax.php
<?php
if(isset($_POST['pr']))
{
$pr = $_POST['pr'];
$sql = $mysqli->query("select id, pr from pr_list where pr='$pr'");
if(($sql->num_rows)>= 1)
{
echo '<STRONG>'.$pr.'</STRONG> is already in use.';
}
elseif($pr == '') {
echo 'Fund is Empty';
}
else
{
echo 'OK';
}
}
?>
ajaxcomplete isn't really the right thing to use here, ajaxcomplete adds an event listener for every ajax call you make but you only need to check the message when this ajax call is successful.
It would still work though but for the msg variable having no scope whithin the ajaxcomplete function. Here is one way I would do it.
<script type="text/javascript">
$(document).ready(function()
{
// I've moved these variables here to give them global-ish scope
// I've also added a variable to assign your save button to
var msgbox = $("#status"),
saveButton = $("#save");
$('input[type="text"]').change(function()
{
var pr = $("#pr").val(),
txtbxs = $('.inputs'),
empty = true;
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
// loop through the txtbxs and check for emptiness :)
$.each(txtbxs, function(key, box) {
if (box.val() != "") {
empty = false;
} else {
empty = true;
}
});
if(msg == 'OK' && !empty) {
msgbox.html('<img src="css/available.png" align="absmiddle">');
saveButton.prop("disabled",false);
} else {
saveButton.prop("disabled",true);
msgbox.html(msg);
}
} // END OF SUCCESS FUNCTION
});// END OF AJAX CALL
});
});// END OF DOCUMENT READY
Another thing I'm not sure about is that when you do your if statement and have txtbxs != '' are you trying to check that the boxes aren't empty or that the variable is not empty.
The way you have it set that the you are checking for the variable to be empty, if you are wanting to check that the txtbxs have a value then you want a some different code
I have wrote a function in javascript which takes title attributes of <tr> calls ajax then after some operation it retreive some title attributes from them. depending on that title attribute i want to remove those <tr> rows
function currentTicketStatus() {
var ids = '';
$('tbody tr[title]').each(function() {
ids += ((ids == '') ? '' : ',') + $(this).attr('title');
});
$.ajax({
url: 'ajaxExecute.aspx?Fn=CTS',
type: 'POST',
context: document.body,
cache: false,
data: 'Tickets=' + ids,
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
sTickets.each(function() {
$(this).parent().parent().remove();
});
}
}
}
});
}
Example : at the time of ajax call ids="100,101,102,103,104" after ajax call sTickets="101|102" . Now remove those rows with attributes of sTickets
HTML (Not Exactly )
<tbody>
<tr title="100"> some data part </tr>
<tr title="101"> some data part </tr>
<tr title="102"> some data part </tr>
<tr title="103"> some data part </tr>
</tbody>
the this in the each is a "title" (a string), you need the DOM element (the <tr>) instead
sTickets.each(function() {
$('tbody tr[title="'+ this +'"]').remove();
});
demo
try this code in your success function :
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
$.each(function(i,v){ $('tr[title=' + v + ']') }).remove();
}
}
Explanation:
1- SELECT DOM element by attribute :
$('[ATTRIBUTE=VALUE]') // $('[title="myTitle"]')
you can find more in this link http://api.jquery.com/attribute-equals-selector/
2 - $.each Iteration
which can be used to seamlessly iterate over both objects and arrays.
more : http://api.jquery.com/jquery.each/