how to map index using jquery to repair indexes when remove - javascript

Problem
when remove any course from table list html his position in center or first it make problem
in index in database
Details
IF I have list of courses as following :
Delphi
Flash
Photoshop
IF I remove flash by JQUERY remove button then click save button
it delete flash and Photoshop
because there are wrong in delete courses by using remove function in jquery
if i remove php it is working without any problem because it is last item
suggestion
using map function when remove but how to do that
if there are any solution for that without using map no problem
i use model as following
public class Cusomemp2
{
public List<EmployeeCourse> empcourses { get; set; }
}
}
i use for edit httppost
var result = db.Employees
.Where(p => p.Id == custom.Id)
.Include(c => c.EmployeeCourses)
.FirstOrDefault();
if (custom.empcourses.Any())
{
foreach (var ec in result.EmployeeCourses.ToList())//to remove existing EmployeeCourses
{
db.EmployeeCourses.Remove(ec);
db.SaveChanges();
}
}
result.EmployeeCourses = custom.empcourses;
db.SaveChanges();
in model view my code as following by jquery
actually i need to modify
code below using map function if there are any function do that never mind
$(function () {
//add courses using drop down
var index = 0;
$("#CourseId").change(function () {
var id = $(this).val();
var txt = $("#CourseId option:selected").text();
$("#tb").append("<tr><td><input type = 'hidden' name='empcourses[" + index + "].CourseId' value='" + id + "'/></td><td>" + txt + "</td><td><input type='button' value='remove' class='r'</td></tr>")
index++;
});
$("#tb").on("click", ".r", function () {
// remove function
$(this).parent().parent().remove();
$(this).parent().prev().prev().remove();
});
// retrieve data in edit view using ajax
$.ajax({
url: "/Employee/getcoursesbyempid",
data:{x:$("#hid").val()},
success: function (res) {
$.each(res, function (i, e) {
$("#tb").append("<tr><td><input type = 'hidden' name='empcourses[" + index + "].CourseId' value='" + e.Id + "'/></td><td>" + e.CourseName + "</td><td><input type='button' value='remove' class='r'</td></tr>")
index++;
});
}
})
});
see image below to understand what i need

Related

Duplication in HTML datalist using JQuery with more than one clicks

I design a datalist on web page. And I want to fill this datalist using JQuery. Controller execute a query and get a list of facilities. Then pass this list to client side. This datalist can show all the facilities. When user click this textbox, the facilities will be listed in drop down list. But when user click more than once, there will be duplicates in datalist. That means, if you click twice, the result will be shown twice in datalist.
Here is code in MVC view
datalist:
<input type="text" list="facility" autocomplete="on" name="Facility" id="facilities" />
<datalist id="facility"></datalist>
JQuery Code:
$(document).ready(function () {
$('#facilities').click(function () {
//alert("Clicked");
var postData = $('#clientTxt').val();
$.ajax({
type: "POST",
url: '#Url.Action("FacilityCheck", "PCA")',
data: { clientTxt: postData },
success: function (result) {
//successful
for (var i = 0; i < result.facilities.length; i++) {
//alert(JSON.stringify(result.facilities[i]));
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
//I want to add an if judgement to avoid duplicates here
//Like contains() method in JAVA.
$('#facility').append(option);
}
},
error: function (result) {
alert('Oh no :(');
}
});
});
});
The duplicates image after clicking many times:
So please give me some advice. Thanks a lot!
It is because you are using the jQuery append() method and not replacing the HTML. Right now, you're just adding (appending) to it every time you iterate through your loop of result.facilities[i] instead of replacing the content.
Your best bet would be to add all of that source to a string and replace the $('#facility')'s innerHTML with the new content. You can use $('#facility').html(yourContentString); to do so.
Hope this helps!
For example...
success: function (result) {
var options = "";
//successful
for (var i = 0; i < result.facilities.length; i++) {
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
options = options + option;
} //end of loop
$('#facility').html(options); // replace the innerHTML of #facility with your new options string
},
Simply modify your success like this :
$('#facility').html('');
$('#facility').append(option);
Remove the items before appending them.
You can also use empty :
$('#facility').empty();

Calling function itself in jquery not works

function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"+json.province_info[i].province_id+"' value='Delete' /></td><td>"+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
$(":input").click(function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});
}//end loadProvinces
i have called loadprovinces function when user add a province for a particular country
as user adds a province it inserts into a province table so it is working , a problem is that loadProvinces function is not calling when user presses a delete button .
As you are adding delete button dynamically then you shuld use .on to bind click event. Also keep this bind click event code outside function :
function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"
+json.province_info[i].province_id
+"' value='Delete' /></td><td>"
+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}//end loadProvinces
// bind click event for dynamically generated element
$(document).on("click",":input",function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});
There is syntax error. Not sure if it is the main Problem, but it can not works without this.
Have you checked console? F12
function(data){ miss }
Why don't you just do it this way:
function loadProvinces (data) {
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i = 0; i < json.province_info.length; i++){
province += "<tr><td><input type='button' id='" + json.province_info[i].province_id + "' value='Delete' /></td><td>" + json.province_info[i].province_name + "</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}
;//end loadProvinces
$(":input").click(function (e) { // it would be nice to add some more identifiers e.g. class to fire only when needed
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url, {"getProvince": "delete_province", "province_id": "" + id},
function (data) {
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});

assign multiple value to javaScript array object

i have coded jQuery widget, which list all the record title in table which user can select of multiple records but with each record user to need to put value in text box.
now i want to built jQuery or JavaScript array where i can push record with each user click add and remove data if click remove against each button.
i want to push "recordId" & "ComponentSchemeMarks" to javaScript array selectedComponentList
var selectedComponentList = {
componentIndex: "",
componentMark:""
};
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
});
Your selectedComponentList is not an array... I guess you want something like this:
var selectedComponentArray = [];
$(document).ready(function () {
//click on Confirm Component Scheme
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMarks = $("#" + recordId + "_CM").val();
alert("recordId " + recordId + " ComponentSchemeMarks " + ComponentSchemeMarks);
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentArray.push({ComponentIndex: recordId, ComponentMark: ComponentSchemeMarks});
});
$("#ComponentSchemeTable").on("click", ".k-grid-Remove", function () {
$(this).hide();
$(this).siblings(".k-grid-Add").show();
var recordId = $(this).data("id");
selectedComponentArray = $.grep(selectedComponentArray, function(value) {
return value.ComponentIndex != recordId;
});
});
...
}
Moreover you should give the buttons IDs and use them for binding the click listeners...

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Using Ajax callback variable values in JQuery dynamic click handlers

I'm doing a simple ajax query which retrieves a variable-length list of values as JSON data. I'm trying to make a list based on this data which has click-functions based on the values I got from the JSON query. I can make this work just fine by writing the onClick-methods into the HTML like this:
function loadFooList() {
var list_area = $("#sidebar");
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' onClick='alert(\"" +
link_id + "\");'>" +
item.name + "</a></li>");
});
list_area.html(list_area.html() + "</ul>");
}
});
}
I don't like writing the onClick-function into the HTML and I also want to learn how to create this same functionality via JQuery click-function.
So the problem is obviously variable-scoping. My naive attempt here obviously won't work because the variables are no longer there when the click happens:
function loadFooList2() {
var list_area = $("#sidebar");
var link_ids = Array();
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' id='" + link_id + "'>"+item.name+"</a></li>");
link_ids.push(link_id);
});
list_area.html(list_area.html() + "</ul>");
for (link_index=0; link_index<link_ids.length; link_index++) {
$("#" + link_ids[link_index]).click(function() {
alert(link_ids[i]);
});
}
}
});
}
Obviously I'd like to do something else than just alert the value, but the alert-call is there as long as I can get that working and move forward.
I understand that I'll have to make some kind of handler-function to which I pass a state-variable. This works for a single value (I can store the whole link_ids array just fine, but then I don't know which of them is the right value for this link), but how would I do this for arbitrary-length lists?
Here is an example from JQuery docs which I'm trying to copy:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
And I quess the last example here, "if you need the context of the original handler..." would probably be what I want but I don't know exactly how to get there. I tried to store the current link_id value into this, use it from this in the applied function (using apply()) but I didn't succeed. The necessary values were still undefined according to FireFox. I'm using JQuery 1.3.2.
So what's the right solution for this relatively basic problem?
Use append instead of html():
function loadFooList() {
var ul = $('<ul>');
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
var a = $('<a>').attr('href','#').bind('click', function(e) {
alert(link_id,item_name);
e.preventDefault();
});
$('<li>').append(a).appendTo(ul);
});
ul.appendTo('#sidebar'); // this is where the DOM injection happens
}
});
}
So the problem appears to be getting the link id associated with the link so that your click handler has access to it. Note that if it's alphanumeric it will qualify for the id attribute and you can extract it from there. If it is purely numeric, it will be an illegal id attribute. In that case, you can either use an attribute, like rel, or the jQuery.data() method to store the link id with the link. You can also simplify by using append. I'll show both examples.
var link = $("<li><a href='#' id='" + link_id + "'>" + item.name + "</a></li>";
link.click( function() {
alert( $(this).attr('id') );
});
list_area.append(link);
or (if numeric)
var link = $("<li><a href='#'>" + item.name + "</a></li>";
link.data('identifier', link_id )
.click( function() {
alert( $(this).data('identifier') );
});
list_area.append(link);
Try this:
function loadFooList() {
var list_area = $("#sidebar");
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
var out = '<ul>';
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
out +="<li><a href='#' id='" + link_id + "'>"+item.name+"</a></li>";
});
out +="</ul>"
var $out = $(out);
$out.find('a').click(function(){
var link_id = this.id;
var item_name = $(this).text();
alert(link_id);
alert(link_name);
})
list_area.html($out);
}
});
}
Using multiple appends causing the browser to redraw multiple times in a row. You only want to modify the dom once.

Categories

Resources