My div contains records which are added dynamically. When I click on the 'Remove' link it generates a confirm box 3 times if I have 3 record, 5 times if I have 5 records and so on.
I want to display the confirm box for that particular row only. How can I do that?
```
<script type="text/javascript">
$(document).ready(function () {
$("#<%= imagehs.ClientID %>").on("click", function (event) {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
var values = new Array();
var x = event.pageX;
var y = event.pageY;
//$(".marker").remove();
$("body").append(
// $('<div class="marker"></div>').css({
//$('<div class="marker m_' + x + '_' + y + '" divdata-marker="m_' + x + '_' + y + '"></div>').css({
$('<div class="marker m_' + x + '_' + y + '"></div>').css({
position: 'absolute',
top: y + 'px',
left: x + 'px',
//top: event.pageY + 'px',
//left: event.pageX + 'px',
width: '10px',
height: '10px',
background: '#dd4b39',
'border-radius': '10px'
})
);
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var $r = $('<button />', { type: 'button', text: 'Refresh Data', id: 'btn_refresh' });
var $cancle = $('<button />', { type: 'button', text: 'Cancle', id: 'btn_cancle' });
$("#divSaveDynamicDis").append($r);
$("#divSaveDynamicDis").append($cancle);
$r.on('click', function () {
if ($('input#txtName').val() == "") {
alert('Please complete the field');
$('input#txtName').focus();
return false;
}
//var NewData = '<div cla-ss="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' <a href="javascript:void(0);" class="remCF" data-atrib=' + x +'>Remove</a> </div>';
//var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
$('.marker').on('click', function () {
$(this).remove();
// div_ref = $(this).attr('divdata-marker')
// $('#divdynamicData.' + div_ref).remove()
});
//$("#divdynamicData").live('click', '.remCF', function () {
//$("#divdynamicData").on('click', '.remCF', function () {
// //if (confirm("Are you sure?")) {
// marker_ref = $(this).attr('data-marker')
// $('.marker.' + marker_ref).remove()
// $(this).parent().remove();
// //}
// //return false;
//});
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
$cancle.on('click', function () {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
});
});
```
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#divdynamicData").on('click', '.remCF', function() {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6">
<asp:Image id="imagehs" name="imagehs" runat="server" Height="500" Width="500" />
<div id="textboxX"></div>
<div id="textboxY"></div>
<div id="textboxBPart"></div>
<div id="divSaveDynamicDis"></div>
<div id="divdynamicData"></div>
</div>
You're short circuting your code by returning the value of the confirm. In other words, once you return the value of confirm, none of the code below it will fire. Instead, you want to check what the user has chosen from the confirm via a conditional and place your removal code in the proceeding block:
$("#divdynamicData").on('click', '.remCF', function() {
if (confirm("Are you sure you want to delete?")) {
var marker_ref = $(this).attr('data-marker');
$('.marker.' + marker_ref).remove();
$(this).parent().remove();
}
});
I assume you are using this code inside a loop or inside another event. The code below should be removed from this loop/event and only be used one time in your page:
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
Because it is a delegate click, each time you declare this code, a new event listener will be attatched to your div listening to clicks on .remCF so multiple events will be fired on your click.
See more: JQuery API .on()
Related
I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.
Hare is my current function
var listItems = $("#list_li").children();
var count = listItems.length;
var i;
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
If is clicked.
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
}
My code adds up styles to it on click, it works fine, how ever, I need to make it so it would know if its clicked or not, I am using loop, because its news feed and it can get more and more, so without the struggle automatically know what to align.
I need something like this
var autoIncresingVar.i = 0;
so when it comes to the 1st one on loop, it would set it to 1 and on click check with "if" its clicked or not.
Let me try to explain Note that I know its not real code
each(i > 5) {
var newEl_"i" = 0;
on first element click
if {newEL_1 == 0) {
addClasses
newEL_i = 1;
} else if)newEl_1 == 1) {
removeClasses
newEL_i = 0;
}
}
You can use .hasClass() function for check if the current node has the 'active' class. If yes, remove it. Else, add it.
Example :
$("#news_" + the_i + " h2").click(function () {
if (!$('#news_' + the_i).hasClass('active'))
{
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
}
else
{
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
One approach would be to use .data() to set a property at an object where value is toggled between 0 and 1 at each click event
$("#news_" + the_i + " h2").data("clicked", 0)
.on("click", function() {
if (!$(this).data().clicked) {
// do stuff with `$(this).data().clicked` : `0`
} else {
// do stuff with `$(this).data().clicked` : `1`
}
// set `$(this).data().clicked` to `1` or `0`
$(this).data().clicked = !$(this).data().clicked ? 1 : 0;
})
Use below code.
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').toggleClass('active');
$('#news_' + the_i + ' h2').toggleClass('active');
$('#news_' + the_i + ' img').toggleClass('active');
$('#news_' + the_i).toggleClass('active');
}
});
}
you can use the add attribute function to add an on click event to each element
http://coursesweb.net/jquery/add-change-remove-attribute-jquery
I have foreach loop:
objects.forEach(function(object) {
var button = '<tr><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$(button).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
but this can't work. I have one object listed only in each forEach cycle.
How can I correctly write onclick event for each point of loop.
You can append each item into your div inside the forEach loop:
objects.forEach(function(object) {
var button = $('<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + '</td></tr>');
button.mouseup(function(e) { if(e.which === 1) { runObject(object); } });
$(mydiv).append(button);
});
Try this
objects.forEach(function(object) {
var button = '<tr class="test_' + object.object.code + "'><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$('.test_' + object.object.code).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
you have to resolve syntax error
Here is one of the ways:
//Create an empty container
var $result = $();
[1,2,3,4].forEach(function(object) {
//Create TRs as jQuery objects (as opposed to strings), append whatever
var $button = $('<tr/>').append('<td>[' + object + ']: </td><td>' + ("this is " + object) + '</td>');
//Bing events, mouseup, click or whatever
$button.on("mouseup", function(e) {
//Add whatever conditions you like
if (e.which === 1) {
alert (object);
}
});
//Keep adding the TR to the container
$result = $result.add($button)
});
//Append all at once, outside the loop
$("#mydiv").empty().append($result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
I have a page with a table and when I click edit I change the table elements into inputs using jQuerys html() function.
I then want to have the user edit the values of the inputs and save these to database, problem is when I try and grab the data I get undefined for all the inputs that are created with the html() function.
I am sure it is something to do with this.. Any help would be great! Here is my code:
$('[name="edit"]').click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $(this).attr('data-invoice-number'),
'count': $(this).attr('data-count')
};
var description_text = $('[data-description-' + data.count).text();
var rates_text = $('[data-rates-' + data.count).text();
var quantity_text = $('[data-quantity-' + data.count).text();
console.log(description_text);
$('[data-description-' + data.count + ']').html('<input type="text" name="description" value="' + description_text + '" />');
$('[data-rates-' + data.count + ']').html('<input type="text" name="rates" value="' + rates_text + '" />');
$('[data-quantity-' + data.count + ']').html('<input type="text" name="quantity" value="' + quantity_text + '" />');
$(this).css('display', 'none');
$('[name="save"][data-count=' + data.count + ']').css('display', 'inline-block');
$('[name="cancel"][data-count=' + data.count + ']').css('display', 'inline-block');
});
$('[name="save"]').unbind().bind().click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $('[name="save"]').attr('data-invoice-number'),
'description': $('[name="description"]').val(),
'rates': $('[name="rates"]').val(),
'quantity': $('[name="quantity"]').val(),
};
console.log(data); // this outputs undefined for values above generated using html() method
if (data.description == '') {
append_alert('danger', 'Please enter a <b>Description</b>');
} else if (data.rates == '') {
append_alert('danger', 'Please enter your <b>Rates</b>');
} else if (data.quantity == '') {
append_alert('danger', 'Please enter a <b>Quantity</b>');
} else {
$.post('edit_invoice_item', data, function() {}).done(function() {
append_alert('success', 'Item Edited!');
setTimeout(function() {
location.reload();
}, 2000)
});
}
});
Regards
For dynamically added elements use event delegation
Change
$('[name="edit"]').click(function(e) {
To
$(document).on('click', '[name="edit"]', function(e) {
AND
$('[name="save"]').unbind().bind().click(function(e) {
To
$(document).on('click', '[name="save"]', function(e) {
i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it