I want to make a simple pagination page. This is regarding delete function. I have a checkbox that user can choose to delete a row. May I know how to post/get the id of the row if user click on next link? In my case, the id will be duplicate if user click on the checkbox. Below are my codes,
jQuery
var cbNew = [],
cbAdd = [];
function addId(checkBox){
cbAdd = cbAdd.concat(checkBox);
console.log(cbAdd);
}
$(document).on("click", ".checkBox", function(){
var cb = [];
$('.checkBox:checked').each(function(){
cb.push($(this).val());
});
if(cb.length > 0) {
addId(cb);
$('#delete').fadeIn();
} else {
$('#delete').fadeOut();
}
});
//Link on Next Page
$(".nextPage").click(getFunct);
function getFunct(e){
e.preventDefault();
var url = $(this).attr('href'),
row = getURLParameter(url, 'startrow'),
cbNew = cbNew;
getParam(row,url);
}
function getParam(param1,param2){
$.ajax({
type: "POST",
url: url,
data:
{
row : param1,
url : param2,
cbNew : cbNew
}
}).done(function(data){
$('#result').html(data);
addId(cbNew);
});
}
This is the output if I click on multiple checkbox on same page console.log(cbAdd);
["25", "25", "26", "25", "26", "27"]
If I click one checkbox on page 1 and one checkbox on page 2, it get the id correcltly
["25", "59"]
You are maintaining two arrays, one capture all checked checkbox values ie cb and concatenating these to another array called cbAdd, here you are duplicating values.
lets use single array cbAdd as below -
$(document).on("change", ".checkBox", function(){
var value = $(this).val();
var index = cbAdd.indexOf(value);
if ($(this).is(":checked")) {
cbAdd.push(value); //put value
} else {
cbAdd.splice(index, 1);//remove value
}
if(cbAdd.length > 0) {
$('#delete').fadeIn();
} else {
$('#delete').fadeOut();
}
});
Related
I have an Invoice, when I want to edit I want to able to delete some rows, either that row is found in DB or is added but click Add button. so I have to delete this row base on this conditions
Delete Row if is found in DB
Delete/Remove row if you added a new one(no need to check in DB, because you add new one)
Below is My invoice which show rows has data from DB and one which has not data (added new)
so I have done to delete the row which is found in DB, and I want to apply the second condition as per my below code.
$(document).ready(function () {
$("body").on("click",".remove",function(e){
var last=$('#tdy tr').length;
if(last==1){
alert("you can not remove last row, Otherwise Delete The Order Number!");
}
//here i tried the second condition
else if(iddata=null){
$(this).parent().parent().remove();
}
else{
if(!confirm("Do you really want to delete this?")) {
return false;
}
e.preventDefault();
// var id = $(this).attr('data-id');
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
var url = e.target;
$.ajax(
{
url: "Loading/"+id, //or you can use url: "company/"+id,
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (response){
if ( data['success'] )
{
alert(data['success']);
location.reload();
}
}
});
return false;
}
});
how can i resolve this some can help me
Please change this
else if(iddata = null)
For this
else if(iddata === null) // or else if(!iddata)
Here you need to use the equality operator == or even better the identity operator === instead of assignment operator =
About reload the page when remove an item you can use
location.reload();
return false;
At the end of the function this because regardless of the type of deletion both operations end up refreshing the page
I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.
I have a problem, on the Telerik dropdownlist i have a function onchange selection. This function save a value with ajax call if an item from list is selected. If selection is not OK will show a confirm box, if the user press OK will be redirected on another page. If press Cancel need to populate a field with empty string.
The problem is: if the user press CANCEL button, the confirm-box fires twice...I tried to put return false after $('#Assessment').val(''); but does not work..
Any solutions please?
DropDownlist:
#(Html.Kendo().DropDownListFor(m => m)
.Name("Assessment").HtmlAttributes(new { #style = "text-align:center", onchange = "saveAssessment()" })
.OptionLabel("Select an assessment")
.DataTextField("DisplayName")
.DataValueField("Value")
.Value("DisplayName")
JS Function
function saveAssessment() {
var assessmentId = $('#Assessment').val();
var grid = $('#_gridProjectCheckList').data('kendoGrid');
var selectedItem = grid.dataItem(grid.select());
var ciId = selectedItem.Id;
var ciText = $("#Assessment").data("kendoDropDownList").text();
if (assessmentId !== null && (ciText === 'Ok' || ciText === 'NotApplicable')) {
$.ajaxSetup({ cache: false });
$.ajax({
url: 'UpdateProjectCheckItemAssessment',
type: "POST",
data: { assessmentId: assessmentId, id: ciId },
success: function (response) {
$('#Assessment').val(response.assessmentVal);
$('#_gridProjectCheckList').data('kendoGrid').dataSource.read();
}
});
}
else {
var msgRedir = confirm("You will be redirected to Assessment Page");
if (msgRedir) {
window.location.href = 'UpdateProjectCheckItem' + '/' + selectedItem.Id;
}
$('#Assessment').val('');
}
}
I'm testing MVC for a demo and I managed to scrap together some pieces but now I am having trouble with an Html.ActionLink. The intent is to present the user with a series of dropdownlists that they must select before the ActionLink is shown. To do that I've copied some JQuery to hide/show my dropdownlists (as selections are made) and the ActionLink. I added an alert to my JQuery to check my values and via the alert it all looks good. But if I debug the controller the parm values are defaulted to 0. I'm not sure what code to include but I will try to include the relevant parts. I think it's something basic.
Here are the dropdown lists and ActionLink.
#Html.DropDownListFor(m => m.selected_env_ID, new SelectList(Model.Environments, "env_ID", "env_DESC"), "*Select an environment")
#Html.DropDownListFor(m => m.selected_app_ID, new SelectList(Model.Applications, "app_ID", "app_DESC"), "*Select an application",new { #hidden = "hidden" })
#Html.DropDownListFor(m => m.selected_job_ID, Enumerable.Empty<SelectListItem>(), "*Select a job", new { #hidden = "hidden" })
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
Here is the convoluted JQuery to hide/show and fill the cascading dropdowns.
<script>
$(document).ready(function ()
{
//Dropdownlist Selectedchange event
$("#selected_app_ID").change(function () {
var id = $('#selected_app_ID').val(); // id value
if (id == 0) {
$('#selected_job_ID').hide();
} else {
$('#selected_job_ID').show();
$("#selected_job_ID").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("SelectJobs")',
dataType: 'json',
data: { id: $("#selected_app_ID").val() },
success: function (jobs) {
// jobs contains the JSON formatted list of jobs passed from the controller
$("#selected_job_ID").append('<option value=0>*Select a job</option>');
$.each(jobs, function (i, job) {
$("#selected_job_ID").append('<option value="'
+ job.job_ID + '">'
+ job.job_DESC + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve jobs.' + ex);
}
});
}
return false;
});
//ddl select change
$("#selected_env_ID").change(function () {
var name = $('#selected_env_ID option:selected').text(); //Item1
var id = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
$('#selected_app_ID').hide();
$('#selected_job_ID').hide();
} else {
$('#selected_app_ID').show();
}
});
//ddl select change
$("#selected_job_ID").change(function () {
var name = $('#selected_job_ID option:selected').text(); //Item1
var id = $('#selected_job_ID').val(); // id value
var envid = $('#selected_env_ID').val(); // id value
if (id == 0) {
$('#divSubmit').hide();
} else {
$('#divSubmit').show();
alert("envid=" + envid + " jobid=" + id);
}
});
}); // end document ready
</script>
My controller has this and id and envid end up being 0:
public ActionResult Submit(int id = 0,int envid = 0) {
If I need to include something else just let me know.
Here is the method that fills the job dropdown list. This works without issues. It's the Html.ActionLink call to Submit that fails to include the parameters.
public JsonResult SelectJobs(int id)
{
db.Configuration.ProxyCreationEnabled = false;
IEnumerable<t_job> jobs = db.t_job.Where(j => j.app_ID == id).ToList();
return Json(jobs);
}
Your link
#Html.ActionLink("Submit", "Submit", new { id = Model.selected_job_ID, envid = Model.selected_env_ID }, new {id = "lnkSubmit" })
is rendered on the server side before you make any selection in the dropdowns. If the initial values of selected_job_ID and selected_env_ID are zero or null, then those values will be passed to the controller (have a look at the rendered html).
If you want to pass the values selected in you drop downs, you could either modify the links href attribute in the drop down change events, or create a button instead of a link, and do a redirect in the buttons click event based on the dropdown values.
You need to use JSON.stringify():
data: JSON.stringify({ id: $("#selected_app_ID").val() }),
I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});