assign multiple value to javaScript array object - javascript

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...

Related

Pass parameters in window.location.href from an array

I have a datatable that on row click takes the value of a column of that row and should redirect to a page which takes that value as parameter.
This is the code :
var selected=[];
$('#example tbody').on('click', 'tr', function (){
var id = this.id;
var index = $.inArray(id, selected);
if (index === -1)
{
selected.push(id);
} else
{
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
$('#example').click(function (){
var dataArr = [];
var rows = $('tr.selected');
var rowData = table.rows( rows ).data();
$.each($(rowData),function(key,value){
dataArr.push(value["id"]);
});
window.location ='users.html?-HERE THE ID SHOULD BE PASSED,which is in the array';
});
And then I have to map accordingly in the Spring controller depending on the id.
But houw should I pass that parameter?
Thank you
Store the position in the array you need in a variable and just concatenate it into the window.location call
var getArrayItem = dataArr[the_position_you_require]
window.location("users.html?" + getArrayItem);

Append url and redirect onclick

I currently have a function used to get a list of 5 website names (title) as well as 5 urls
The code below is pulling the list of 5 titles but how would I go about append the title so that it will redirect to the url on click
function getFavorites() {
$.getJSON("/Home/UserFavorites", function (result) {
var options = $("#userfavorites");
List = "";
$('#userfavorites >option').remove();
$.each(result, function () {
options.append($("<option />").val(this.url).text(this.title));
List = List + "," + this.title;
});
}).complete(function () {
$.unblockUI();
});
}
$("#userfavorites").change(function(){
window.location.href = $(this).val();
});

how to map index using jquery to repair indexes when remove

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

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);
}

My table get duplicated rows with Jquery Table Sorter

I have search field in my project, which uses $.post for getting the results for the search query.
My problem: When a user click on the search button it works correctly, however when a user click on the search button again, and then click on my thead columns jquery sorter duplicates it with the previous search shows in the table.
How can I solve this so my sorter function does not duplicate?
this is the Jquery code for the search button click.
$(function () {
$('#submitfloat').click(function () {
$('#loading').show();
setTimeout(function () { $("#loading").hide(); }, 800);
var SubjectTypes = $('#SubjectTypes').val();
var Teams = $('#Teams').val();
var Companies = $('#Companies').val();
var Consultants = $('#Consultants').val();
var PlannedDates = $('#PlannedDates').val();
var CompletedDates = $('#CompletedDates').val();
var DateTypes = $('#DateTypes').val();
var data = {
Subjectypes: SubjectTypes,
Companies: Companies,
Teams: Teams,
Consultants: Consultants,
PlannedDates: PlannedDates,
CompletedDates: CompletedDates,
DateTypes: DateTypes
};
var fromDate = $('#PlannedDates').val();
var endDate = $('#CompletedDates').val();
if (Date.parse(fromDate) > Date.parse(endDate)) {
jAlert("End date must be later than start date", "Warning");
return false;
} else {
$('#GoalcardSearchResult tbody').hide();
setTimeout(function () { $("#GoalcardSearchResult tbody").show(); }, 800);
$.post('#Url.Action("Search", "SearchNKI")', data, function (result) {
$("#GoalcardSearchResult tbody").empty();
result.forEach(function (goalcard) {
$("#GoalcardSearchResult tbody").append(
$('<tr/>', {
click: function () {
id = goalcard.Id;
var url = '#Url.Action("AnswerForm", "AnswerNKI", new { id = "__id__"})';
window.location.href = url.replace('__id__', id);
},
html: "<td>" + goalcard.Name + "</td><td>" + goalcard.Customer + "</td><td>" + goalcard.PlannedDate + "</td><td>" + goalcard.CompletedDate + "</td>"
}));
});
$("#GoalcardSearchResult").tablesorter();
});
return false;
}
});
});
Your help is appreciated, thanks in advance!
I'm guessing tablesorter has already been initialized before the user clicks on the sort button. In that case, replace this code:
$("#GoalcardSearchResult").tablesorter();
with this:
$("#GoalcardSearchResult").trigger('update');

Categories

Resources