Click function by Enrr - javascript

i have click function:
$("#but").on('click', function(){
$.post('/chat/send/', {
id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"),
}, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
});
When i try to add function of submiting an input by Enter key it nothing happend. This function with Enter submit:
$('#text').keypress(function(e){
if(e.which == 13){
$("#but").on('click', function(){
$.post('/chat/send/', {
id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"),
}, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
});
}
});
In HTML i have:
<input id="text" type="text" name="message-text" size="63">
<input id="but" type="submit" name="Send" value="Send">

you are attaching the keypress event with the click inside, so to solve this issue ; here is a suggestion
1st try to factorise repeated code , so that if there is any edit you'll have to do it just once :
function sendReq(data){
$.post('/chat/send/', data, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
}
so now you are having a function that send your request, now you'll handle the event where you function will be fired , it's simply by typing
$('#text').keypress(function(e){
if(e.keyCode == 13){
var data = {id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id")}
sendReq();
}
});
and you do the same thing for the click .

Related

Delete Confirmation dialog in jQuery on dynamic content

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()

How to access form fields in jquery using variable reference to the form?

Learning jquery, in chrome console created form:
var $form1 = $("<form/>", { id: 'form1' });
$div1.append($form1);
Then tried to access the fields during form submission:
This works:
$('#form1').submit(function(e) {
e.preventDefault();
$('#form1 input, #form1 select').each(function(index){
var input = $(this);
console.log('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
});
});
Output:
Type: textName: name1Value: hello world
Type: submitName: submit1Value: submit
But this does not:
$($form1).submit(function(e) {
e.preventDefault();
$($form1).each(function(index){
var input = $(this);
console.log('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
});
});
Output:
Type: undefinedName: undefinedValue:
How do I access the form fields using the variable $form1 instead of the actual element #form1?
Thanks for answer.
You can use children with selector to filter needed ones.
var $div1 = $('body');
var $form1 = $("<form>", { id: 'form1' });
$div1.append($form1);
$form1.append('<input name="test" type="text"/> <input value="go" name="whattodo" type="submit" />');
$($form1).submit(function(e) {
e.preventDefault();
$form1.children('input').each(function(index){
var input = $(this);
console.log('Type: ' + input.attr('type') + ' Name: ' + input.attr('name') + ' Value: ' + input.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Getting values of inputs generated using jQuerys html() function

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) {

Triggering change events in a loop results in loss events

I am triggering a change event on a combo box for multiple values but unfortunately events are getting lost. Is there a way to wait for one event to complete before triggering the next event. Sample code is shown below
for (i = 0; i < contextFilters.length; i++)
{
var contextFilter = contextFilters[i];
if (contextFilter != "")
{
var cfData = contextFilter.split(":");
var cfName = cfData[0];
var cfVal = cfData[1];
if (cfName != null)
{
//alert("cfName : " + cfName);
//alert("cfVal : " + cfVal);
$('#context_filter').val(cfName);
$('#context_filter').trigger('change', cfVal);
}
}
}
When the event is triggered a new select box is added to the DOM but not all select boxes are getting added.
Also the change event handler is a s shown below
$('#context_filter').change(function(event, selectValues)
{
if ($(this).prop("selectedIndex") > 0)
{
populateDateValues();
var contextFilterComboObject = $(this);
var selectedVal = $(contextFilterComboObject).val();
var validate = $('#collapsiblePanel :input').attr('disabled') == null;
if (!validate)
{
$('table[id*=OtherOptions] :input').attr('disabled', false);
$('#collapsiblePanel :input').attr('disabled', false);
}
var formInput = decodeURIComponent($('#rptInputParams').serialize());
formInput += "&validate=" + validate;
$('#ajaxBusy').show();
$.getJSON('GetContextFilterData', formInput, function(data)
{
var selectBox = '<tr><td class="celltoppad"><b>' + selectedVal +
' : </b></td> <td class="celltoppad"><select multiple="multiple" name="' +
selectedVal.toLowerCase() + '" id="' + selectedVal.toLowerCase() + '" >';
var errorMsg = '';
var errorCount = 1;
errorMsg += '<html>';
$.each(data.errorMessageList, function(index, value)
{
errorMsg += errorCount + ') ' + value + '</br></br>';
errorCount++;
});
errorMsg += '</html>';
if (errorCount > 1)
{
$('#ajaxBusy').hide();
showErrorDialog(errorMsg, errorCount * 20);
$(contextFilterComboObject).prop("selectedIndex", '0');
return;
}
$.each(data.contextFilterDataList, function(index, value)
{
selectBox += '<option value="' + value + '">' + value + "</option>";
});
selectBox +=
'</select></td><td class="celltoppad"><a href="#"><img id="removeCF" ' +
'src="../images/remove.png"/></a></td></tr>';
$('#ajaxBusy').hide();
// If the context filter has not been already added.
if ($('#' + selectedVal.toLowerCase()).length == 0)
{
$('a[id*=_showDialog]').hide();
toggleDatePickerLink();
$('img#removeDate').hide();
$('table[id*=OtherOptions] :input').attr('disabled', true);
$('#collapsiblePanel :input').attr('disabled', true);
$('table#context_filter').append(selectBox);
$(contextFilterComboObject).prop("selectedIndex", '0');
}
if (selectValues != null)
{
$('#' + selectedVal.toLowerCase()).val(selectValues.split(","));
}
$('#' + selectedVal.toLowerCase()).multiselect({
noneSelectedText: 'Please select',
selectedList: 3,
selectedText: '# of # selected',
position: {
my: 'left center',
at: 'right center',
offset: '20 100'
}
}).multiselectfilter();
});
}
});
instead of triggering the event, can't you just call the handler ?
var handler = function(event, selectValues)
{
if ($('#context_filter').prop("selectedIndex") > 0)
{
populateDateValues();
var contextFilterComboObject = $('#context_filter');
var selectedVal = $(contextFilterComboObject).val();
var validate = $('#collapsiblePanel :input').attr('disabled') == null;
if (!validate)
{
$('table[id*=OtherOptions] :input').attr('disabled', false);
$('#collapsiblePanel :input').attr('disabled', false);
}
var formInput = decodeURIComponent($('#rptInputParams').serialize());
formInput += "&validate=" + validate;
$('#ajaxBusy').show();
$.getJSON('GetContextFilterData', formInput, function(data)
{
var selectBox = '<tr><td class="celltoppad"><b>' + selectedVal +
' : </b></td> <td class="celltoppad"><select multiple="multiple" name="' +
selectedVal.toLowerCase() + '" id="' + selectedVal.toLowerCase() + '" >';
var errorMsg = '';
var errorCount = 1;
errorMsg += '<html>';
$.each(data.errorMessageList, function(index, value)
{
errorMsg += errorCount + ') ' + value + '</br></br>';
errorCount++;
});
errorMsg += '</html>';
if (errorCount > 1)
{
$('#ajaxBusy').hide();
showErrorDialog(errorMsg, errorCount * 20);
$(contextFilterComboObject).prop("selectedIndex", '0');
return;
}
$.each(data.contextFilterDataList, function(index, value)
{
selectBox += '<option value="' + value + '">' + value + "</option>";
});
selectBox +=
'</select></td><td class="celltoppad"><a href="#"><img id="removeCF" ' +
'src="../images/remove.png"/></a></td></tr>';
$('#ajaxBusy').hide();
// If the context filter has not been already added.
if ($('#' + selectedVal.toLowerCase()).length == 0)
{
$('a[id*=_showDialog]').hide();
toggleDatePickerLink();
$('img#removeDate').hide();
$('table[id*=OtherOptions] :input').attr('disabled', true);
$('#collapsiblePanel :input').attr('disabled', true);
$('table#context_filter').append(selectBox);
$(contextFilterComboObject).prop("selectedIndex", '0');
}
if (selectValues != null)
{
$('#' + selectedVal.toLowerCase()).val(selectValues.split(","));
}
$('#' + selectedVal.toLowerCase()).multiselect({
noneSelectedText: 'Please select',
selectedList: 3,
selectedText: '# of # selected',
position: {
my: 'left center',
at: 'right center',
offset: '20 100'
}
}).multiselectfilter();
});
}
});
for (i = 0; i < contextFilters.length; i++)
{
var contextFilter = contextFilters[i];
if (contextFilter != "")
{
var cfData = contextFilter.split(":");
var cfName = cfData[0];
var cfVal = cfData[1];
if (cfName != null)
{
//alert("cfName : " + cfName);
//alert("cfVal : " + cfVal);
$('#context_filter').val(cfName);
handler(null, cfVal);
}
}
}
I never tested above code, but I declared your handler as a function and then in the loop at the bottom, you can see how I call it instead of triggering it (handler(cfVal))
I was able to figure out the solution to my problem, when the back button is clicked and the change event is fired then I made the ajax call using async as false and that resolved the issue. This is because if the async is true json calls happen simultaneously and some events are lost during that period.
Thanks

problem ajax load with autocomplete.?

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

Categories

Resources