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
Related
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();
}
});
So I have a page with several modes drawn based on a php variable (view, edit, add). I have some jquery adding info to td tags, but it would always post to the ajax target php file (and block some links/behavior). So to fix it, I had to add a check to only show on view mode.
However, now the edit mode for some reason also shows view for the same variable I am checking and I can't change the class that does it. What I'd like to do is execute my code by default, except when any link is pressed (so it will always follow the link). How can I do that?
<script>
$(document).ready(function(e){
var msg ='<?php echo $mode; ?>';
if(msg == 'view'){
//get all appointment numbers
count=0;
appointment_nums = [];
$('.mgrid_table > tbody > tr').each(function() {
appointment_nums.push($(this).find('td').eq(3).find('label').html());
});
appointment_nums = appointment_nums.filter(function(n){ return n != undefined });
appointments = appointment_nums.length;
function ajax() {
return $.ajax({
type:"post",
url: "../testrequest.php",
data : {appointment_nums:appointment_nums},
dataType:'json',
});
};
ajax().done(function(result){
$('table:nth-of-type(2) > tbody > tr > td:nth-of-type(2)').each(function() {
if($(this).children().length < 1){
if (result[count] == false){
$(this).append('Schedule Appointment ');
}else{
$(this).append('<span>Waiting For Doctor to Schedule</span>');
}
}
count = count + 1 ;
});
});
}
});
</script>
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?
});
I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.