I have the below code.
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
elem = $(this);
part = $(this).attr("data-part-name");
//alert(part);
selected_options = "";
$('.' + part).each(function () {
if ($(this).is(":checked")) {
selected_options += $(this).attr("data-option-name") + ' <b>,</b> '
}
});
$("#part_child_" + elem.attr("data-part-id")).html(selected_options);
});
});
If you see I am adding a "comma" to selected options.
Now problem is it adds comma even after the last element.
How can I remove the last comma
.map() will a perfect fit for this. Also you can filter the checked items using :checked and filter
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
var elem = $(this);
var part = $(this).attr("data-part-name");
//alert(part);
var selected_options = $('.' + part).filter(':checked').map(function () {
return '<b>' + $(this).attr("data-option-name") + '</b>'
}).get();
$("#part_child_" + elem.attr("data-part-id")).html(selected_options.join(', '));
});
});
You can use the index of iteration to compare with length of parts element and do the decision whether a comma needs to be added or not.Modify the code to:
var totalparts=$('.' + part).length;
$('.' + part).each(function (i) {
if ($(this).is(":checked")) {
selected_options += $(this).attr("data-option-name") + totalparts!=(i+1) ?' <b>,</b> ':'';
}});
Just remove last , substring from the string,
if(selected_options.length > 0){
selected_options = selected_options.slice(0,-1)
}
$("#part_child_" + elem.attr("data-part-id")).html(selected_options);
replace this line
$("#part_child_" + elem.attr("data-part-id")).html(selected_options.replace(/[\<\>\,b\/\s]+$/,''));
Related
I am not able to create an edit in place feature with JavaScript/ jQuery. I could not use the plugin editinplace, because I need to put a datepicker on it. My code below does not work for some strange reason:
function editImpfDatumImpfung1Clicked(sender)
{
var sText = $(this).text();
var sId = $(this).attr("id");
$(this).attr("id", "tobechanged");
$(this).after('<input type="text" id="' + sId + '" value="' + sText + '" />');
$(this).remove();
bImpfung1Clicked = true;
$("#" + sId).focus();
$("#" + sId).datepicker(datepickerOptions);
if (bFirstRegisterImpfung1 === true)
{
firstRegisterImpfung1();
bFirstRegisterImpfung1 = false;
}
}
$(document).ready(function()
{
$elem = $("span[id^='impfung_1['");
if ($elem.length > 0)
{
bFirstRegisterImpfung1 = true;
$elem.click(editImpfDatumImpfung1Clicked);
}
});
Edit:
No Errors in console.
console.log($("#" + sId).val()); causes undefined
Edit 2:
Just needed to escape the id like this:
sId = sId.replace(/[[]/g,'\\[');
sId = "#" + sId.replace(/]/g,'\\]');
Thanks for your advice.
I imagine you have a typo in the following line:
$elem = $("span[id^='impfung_1['");
try this instead:
$elem = $("span[id^='impfung_1']");
I have a click function to make a list of chosen items. Also, I push the chosen items to an array. There is no problem in that part, here is the function.
$('#addToCartButton2').click(function(){
var toAdd=$("#chooseItem2 option:selected").text();
var itemNbr2=$("#itemNbr2").val();
if(toAdd !== defaultSelectFormText && itemNbr2 >=1){
$('#defaultText').remove();
$('.col-md-5').append('<p id="items">' + itemNbr2 + ' Adet ' + toAdd + '<span class="extra">Sipariş listesinden çıkarmak için tıklayın!</span>' + '</p>');
ordersArray.push(itemNbr2 + ' Adet ' + toAdd);
alert(ordersArray.toString());
};
});
But I also have a function to remove the clicked item from that list. So I want to remove that item also from array when it is clicked. I tried to use splice method but I can not get the index of the clicked item. Here is the remove function.
$(document).on('click', '#items', function() {
$(this).remove();
var index = ordersArray.indexOf($(this).val());
alert(index);
if (index > -1) {
ordersArray.splice(index, 1);
}
});
How can I get the index of the clicked item in the list?
Firstly, either you make id of items unique or use class instead of id as I done in this solution.
$('#addToCartButton2').click(function(){
var toAdd=$("#chooseItem2 option:selected").text();
var itemNbr2=$("#itemNbr2").val();
if(toAdd !== defaultSelectFormText && itemNbr2 >=1){
$('#defaultText').remove();
$('.col-md-5').append('<p class="items"><span>' + itemNbr2 + ' Adet ' + toAdd + '</span><span class="extra">Sipariş listesinden çıkarmak için tıklayın!</span>' + '</p>');
ordersArray.push(itemNbr2 + ' Adet ' + toAdd);
alert(ordersArray.toString());
};
});
$(document).on('click', '.items', function() {
var index = ordersArray.indexOf($('span:first', this).text());
alert(index);
if (index > -1) {
ordersArray.splice(index, 1);
}
$(this).remove();
});
In function to remove the clicked item from that list, make the following changes:
$(document).on('click', '#items', function() {
var index = ordersArray.indexOf($(this).text());
alert(index);
if (index > -1) {
ordersArray.splice(index, 1);
}
$(this).remove();
});
It seems like you're way of deleting the item is a little to complex.
Why not just use a uniqe ID for each item you're appending and just delete
the item by it's ID ?
This question already has answers here:
Clone <div> and change id
(4 answers)
Closed 9 years ago.
I'm trying to clone a div and the input elements inside it. When I clone it, I would like all the ids to increment by one. I've made a fiddle to show you what I'm doing.
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
});
jsFiddle
So far I've cloned the whole div itself and the ids increment but the elements inside remain the same. How would I get all elements inside the div to increment by one?
You have cloned the entire div without modifying it's contents. Try something like:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount).find('input').each(function (i, e) {
$(e).attr('id', $(e).attr('id').replace(amount, new_amount));
});
});
DEMO
You can recursively replace all id's using find / replace:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount).clone();
cloned_div.insertAfter('#class-' + amount);
cloned_div.find('[id$="-' + amount + '"]').andSelf().each(function(index, child) {
child.id = child.id.replace("-" + amount, "-" + new_amount);
});
});
See jsFiddle
cloned_div.find('[id$="-' + amount + '"]') will search for all child elements having an id attribute ending on "-" + amount, .andSelf() will include the cloned div as you want to change the id there also. Then simply replace the number part in the id of each child (and self).
Try adding this:
$('#class-' + new_amount + ' input:nth-child(1)').attr('id', 'name-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(2)').attr('id', 'number-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(3)').attr('id', 'book-class-' + new_amount);
just below your $(cloned_div).clone() statement.
See it in action:
http://jsfiddle.net/ZHHcA/1/
These other answers are close, but the problem with their solutions is the original ID prefixes are being lost: number-class-1 is becoming class-1 which is not ideal.
Here is a better option:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
var $cloned = $(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
$cloned.children().each(function(){
var $child = $(this);
var oldID = $child.attr('id');
var newID = oldID.replace(/[0-9]+$/, new_amount); // replace just the number, leave the rest of the ID name in tact
$child.attr('id', newID);
})
});
And a working example
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 have the following code,
<script type="text/javascript">
$(document).ready(function () {
var dataAnalysisDataFileTableIDs = $("#dataAnalysisDataFileTable tr[id]").map(function () { return this.id; }).get();
//for(var key in dataAnalysisDataFileTableIDs) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//}
//$.each(dataAnalysisDataFileTableIDs, function (index, value) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//});
$("#dataAnalysisDataFileTable tr[id]").each(function (i, elem) {
$(elem).click(function () { alert("[" + i + "][" + this.id + "]"); });
});
$("#aaa").click(function () {
alert("meow");
});
});
</script>
and it doesn't work i also tried the one in the comments section which does the same as "for in" it doen't work but when i attach click to the id #aaa it works fine how do i approach this problem when i have all the ids in the array and i want to be able to attach events to them?
How about just using each ? Like so:
<html>
<head><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script></head>
<body>
<table id="dataAnalysisDataFileTable">
<tr id="foo"><td>foo</td></tr>
<tr id="bar"><td>bar</td></tr>
</table>
<script type="text/javascript">
$(document).ready(function () {
$("#dataAnalysisDataFileTable tr[id]").each(function(i, elem) {
$(elem).click(function() { alert("[" + i + "][" + this.id + "]") } );
});
});
</script>
</body>
</html>
I've patched the possible errors. I cannot resolve the value variable though.
for(var index=0, length=dataAnalysisFileTableIDs.length; index++) {
var key = dataAnalysisFileTableIDs[index];
var id = "#" + dataAnalysisFileTableIDs[key];
$(id).click(function () {
/* Value ? It's not defined*/
alert("[" + index + "][" + /*value +*/ "]");
});
}
dataAnalysisFileTableIDs is an array. To loop through an array, you have to use the for ( init_index ; condition ; increment ) loop. The key can be obtained through name_of_array[index].