I'm doing the following:
$('.document-content').on('input', function() {
var headers;
headers = $('.document-content > h2').each(function() {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$('.document-outline').empty().append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
In order to avoid duplication, I added empty() but now only the last item in the each loop is being appended to .document-outline.
How can I fix this?
You need to empty it before the loop, else before adding any item you are removing the previous contents meaning all the previous items are removed thus only the last item in the loop is kept
$('.document-content').on('input', function () {
var $ct = $('.document-outline').empty();
var headers;
headers = $('.document-content > h2').each(function () {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$ct.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
You need to empty() the containing element outside of the loop, otherwise it is being cleared on each iteration.
$('.document-content').on('input', function() {
var $headers = $('.document-content > h2'),
$outline = $('.document-outline').empty()
$headers.each(function() {
var headerId = $(this).attr('id'),
headerText = $(this).text();
$outline.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
Note that I shortened the logic slightly by setting the values as the variables are declared.
Empty it outside loop otherwise you will end with appending last elements only as everything before it will get emptied
$('.document-content').on('input', function() {
var headers,
var outlineDoc = $('.document-outline').empty()
headers = $('.document-content > h2').each(function() {
var headerId, headerText;
headerId = $(this).attr('id');
headerText = $(this).text();
$(outlineDoc).append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
});
});
Related
I have a "todo" application that I've added a delete button to. The application is already set up to post via an ajax request, but the delete button causes a page re-load after it is clicked. I feel like preventDefault should... well prevent that from happening, but it doesn't. Any advice would be much appreciated!
function to list tasks
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id + '" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' + " data-id='" +
task.id + "'" + checkedStatus + ' /><label>' + task.title +
'</label><a class="destroy" rel="nofollow" data-method="delete" href="/tasks/' + task.id +
'"></a></div></li>';
return liElement;
}
delete task function
function deleteTask(e) {
e.preventDefault();
var itemId = $(e.target).data("id");
$.ajax("/tasks/" + itemId, {
_method: "DELETE",
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith('');
});
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
$('.destroy').click(deleteTask);
});
Remove the href from the <a> tag. I will recommend to change this to a <button> since you are not taking the user to any other page.
I also suspect this will not work:
var itemId = $(e.target).data("id");
Try changing it to:
var itemId = $(this).parent().data("id");
I'm trying use this function to prevent the duplicate but only work for prevent not to break action. How to make this function work not only for prevent but for break action too ?
function AddTipeTruk() {
var form = $("#formtruk");
var contents = {},
duplicates = false;
$("#table-custtiptruk td").each(function () {
var tdContent = $(this).text();
if (contents[tdContent]) {
duplicates = true;
return false;
}
contents[tdContent] = true;
});
if (duplicates) {
alert("There were duplicates.");
}
if (form.valid()) {
var markup = "";
markup = "<tr><input id='TipTrukId' name='TipTrukId' type='hidden' value='1'><td style='display:none;'><input value='" + 1 + ";" +
+$('#JenisTruck option:selected').val() + ";" + $('#Alias').val() + ";" +
"' name='TipTrukData'/> </td><td class='no'></td><td>" + $('#JenisTruck option:selected').text() + "</td><td>" + $('#Alias').val() + "</td>" +
"<td><a href='#' data-toggle='modal' onclick='EditTipTrukRow($(this))'>Edit</a> | <a href='#' onclick='RemoveTipTrukRow($(this));'>Delete</a></td></tr>";
$("#table-custtiptruk tbody").append(markup);
updateRowNumberTipTruk();
$('#modal').modal('hide');
}
}
You are jumping from inner loop. You need to jump from function too.
See below.
$("#table-custtiptruk td").each(function () {
var tdContent = $(this).text();
if (contents[tdContent]) {
duplicates = true;
return false;
}
if(duplicates ==true){
return !duplicates;
}
contents[tdContent] = true;
});
i got javaScript array hold elements records with unique elementIndex in it now what I have to add single or multiple components in same javaScript array for that particular element (same elementIdex).
this array can have as many elements as required and each element may have one or multiple components associated to that element.
I have managed to do first part, how i do second part ... that is add components records associated to single element.
note element and component are in separate javaScript function but i have global array
this is what i want to achieve (may be JSON)
QualificationElemenetsAndComponents[0] = {
Element [
ElementIndex : "",
ElementMarkingSchemeTitle : "",
ElementAvailableMark: "",
ElementPassMark: "",
ElementDistinctionMark: "",
Component[0]= [
componentIndex="",
componentMark =""
],
Component[1]= [
componentIndex="",
componentMark =""
],
Component[2]= [
componentIndex="",
componentMark =""
],
}
global array
var selectedComponentList = [];
var selectElementList = [];
element
$("#ElementTable").on("click", ".k1-grid-confirm", function () {
var E_RecordId = $(this).data("id");
var E_MarkingSchemeTitle = $("#" + E_RecordId + "_EMST").val();
var E_AvailableMark = $("#" + E_RecordId + "_AM").val();
var E_PassMark = $("#" + E_RecordId + "_PM").val();
var E_MeritMark = $("#" + E_RecordId + "_MM").val();
var E_DistinctionMark = $("#" + E_RecordId + "_DM").val();
alert("elementRecordId " + E_RecordId + " E_MarkingSchemeTitle " + E_MarkingSchemeTitle + " E_AvailableMark " + E_AvailableMark + " E_PassMark " + E_PassMark + " E_MeritMark " + E_MeritMark + " E_DistinctionMark " + E_DistinctionMark);
//add data to array//
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });
}
});
Component
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMark = $("#" + recordId + "_CM").val();
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
//push array to Selected Element
?????????????????????????????????????
}
});
Many thanks
Define a function to refresh the global list:
// Elements
selectElementList.push({...});
refreshGlobalList();
// Components
selectedComponentList.push({...});
refreshGlobalList();
And the function:
var globalList = [];
function refreshGlobalList() {
globalList = selectElementList.concat(selectedComponentList);
}
arrayNum.push.apply(arrayNum, arrayValuTwo);
arrayNum.push.apply(arrayNum, arrayValuThree);
you can try this or you can try this
arrayNumber.push.apply(arrayNumber, arrayValueTwo.concat(arrayValueThree));
This is my all script, I know this is long, but just one line is important and I add all it for insurance:
//Add new Addable div
$('.AddNewE').click(function () {
var RemoveAddableButton = $('<input type="button" class="RemoveE button red" value="remove" />');
$(RemoveAddableButton).click(function () {
$(this).closest('.Addable').remove();
});
var TargetId = $(this).attr('id');
TargetId = TargetId.substring(3);
var Target = $('.Addable#' + TargetId + ':first');
var Count = $('.Addable#' + TargetId).size();
var CloneTarget = $(Target).clone();
CloneTarget.find('input').val('');
CloneTarget.insertAfter('.Addable#' + TargetId + ':last'); // ***importantOne
var TargetName = $(Target).find('input').attr('name');
if (Count == 1) {
var CloneName = TargetName + '[1]';
TargetName = TargetName + '[0]';
$(Target).find('input').attr('name', TargetName);
$(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName);
$(CloneTarget).find('input').attr('name', CloneName);
$(CloneTarget).append($(RemoveAddableButton));
if ($(CloneTarget).find('span[class*="field-validation"]').size() > 0) {
$(CloneTarget).find('span[class*="field-validation"]').remove();
$(CloneTarget).append(
$('<span class="field-validation-valid invalid-side-note" data-valmsg-replace="true" data-valmsg-for="' + CloneName + '"></span>')
);
}
} else {
var indx = TargetName.length - 3;
var CloneTargetName = TargetName.substring(0, indx);
CloneTargetName = CloneTargetName + '[' + Count + ']';
$(CloneTarget).find('input').attr('name', CloneTargetName);
$(CloneTarget).append($(RemoveAddableButton));
if ($(CloneTarget).find('span[class*="field-validation"]').size() > 0) {
$(CloneTarget).find('span[class*="field-validation"]').remove();
$(CloneTarget).append(
$('<span class="field-validation-valid invalid-side-note" data-valmsg-replace="true" data-valmsg-for="' + CloneTargetName + '"></span>')
);
}
}
(function ($) {
$.fn.updateValidation = function () {
var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
return this;
};
})(jQuery);
$(Target).updateValidation();
$(CloneTarget).updateValidation();
});
If I click the .AddNewE button then a new div added, but as my script I want to add this new div to the end of the divs so I use
CloneTarget.insertAfter('.Addable#' + TargetId + ':last');
but always the new div added as a second div it means always the :first and :last div is same and is first one also I checked by:
$('.Addable#' + TargetId).css('border', '');
$('.Addable#' + TargetId + ':last').css('border', '3px dotted green');
$('.Addable#' + TargetId + ':first').css('border', '3px dotted red');
So where is the problem? why the jQuery can't recognize last div ?
The problem is in the jQuery selector: $('.Addable#' + TargetId + ':last')
It is not valid HTML when you have multiple elements with the same id (#TargetId). ID is unique and you're not supposed to have more than 1 element with the same ID.
The jQuery selector assumes you use valid correct HTML markups, so it doesn't bother to collect all your elements with that ID. As soon as jQuery found the first element in the DOM with that ID, it stops and appends your new element right after that.
Try updating your jQuery selectors to simply: $('.Addable:first') and $('.Addable:last') and see if it works.
I am trying to add a hidden input field to a form when a span with class="checkbox" is clicked, and remove that same field when span with checkmark is clicked.
I am able to add the input, but I cannot remove it.
My HTML:
<span title="Here's My Title" class="wishlistcheck checkbox">1</span>
<form id="wishlistform"></form>
My Javascript:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input id=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input#" + appName).remove();
}
});
});
I guess you have to put the appNum-- after the .remove() method calling. Try it:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input class=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input[class=" + appName + "]").remove();
}
});
});
You probably have multiple DOM elements by that id tag, and so it may be removing an element matching that id but not the right one.
Try giving it a class name instead and getting more specific in your jQuery parameters by adding parent elements, i.e.
$('#wishlistform input#' + appName).remove();