Getting values of inputs generated using jQuerys html() function - javascript

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

Related

getJSON does not work on button click but does with hitting enter key

My getJSON request and the rest of my function works fine if the user hits enter after filling out the field however my function does not get past the getJSON request if they click the search button.
I've found some similar post on SO but haven't been able to fix my issue yet. I've tried adding .live before my .click event and also tried adding e.preventDefault in a couple different spots but that hasn't resolved it either.
My HTML looks like this
<input id="zipCode" maxlength="5" type="text"> <button id="zipSearch" onclick="findByZip()">Search</button></p>
My JS looks like this
$(document).ready(function () {
$('#zipSearch').click(findByZip);
$('#zipCode').bind('keydown', function (e) {
if (e.keyCode === 13) { // 13 is enter key
e.preventDefault();
findByZip();
return false;
}
});
}
);
function findByZip() {
console.log('running findByZip');
var zip = $('#zipCode').val();
var stateName = $('#stateName');
stateName.text("Reps for " + zip);
$("#results").empty();
var url='//something.com/api/Reps?Zipcode=' + zip;
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
if (data.length == 0) {
var header = "<h3>No matches found.</h3>"
$('#result').append(header);
}
else {
$.each(data, function (i, item) {
var header = "<h3>Manufacturer's Representative</h3>";
var businessName = $("<h4 id=businessName" + i + "></h4>").text(item.BusinessName);
var contactName = $("<h4 id=contactName" + i + "></h4>").text(item.Contact);
var address = $("<div id=address" + i + "></div>").text(item.Address);
var address2 = $("<div id=address2" + i + "></div>").text(item.City + ", " + item.State + " " + item.Zipcode);
var phone1 = $("<div id=phone1" + i + "></div>").text("PH: " + item.Phone1);
var phone2 = $("<div id=phone2" + i + "></div>").text("PH2: " + item.Phone2);
var fax = $("<div id=fax" + i + "></div>").text("FAX: " + item.Fax);
var email = '<div id=email' + i + '>' + item.Email + '</div>';
var website = '<div id=website' + i + '>' + item.Website + '</div>';
if (item.RegionalRepId == item.Id) {
header = "<h3>Regional Manager</h3>";
}
$("#results").append(header, businessName, contactName, address, address2, phone1, phone2, fax, email, website);
if (businessName[0].textContent == "null") {
$("#businessName" + i).remove();
}
if (contactName[0].textContent == "null") {
$("#contactName" + i).remove();
}
if (address[0].textContent == "null") {
$("#address" + i).remove();
$("#address" + i).remove();
}
if (phone1[0].textContent == "PH:null") {
$("#phone1" + i).remove();
}
if (phone2[0].textContent == "PH2:null") {
$("#phone2" + i).remove();
}
if (fax[0].textContent == "FAX:null") {
$("#fax" + i).remove();
}
if (email.includes("null")) {
$("#email" + i).remove();
}
if (website.includes("null")) {
$("#website" + i).remove();
}
});
}
});
}
expected result is to just pull and display data by different click events and searches to a map. Clicking on a state works, typing in a zipcode and hitting enter works, but typing in a zipcode and clicking search does not work.
If you guys have any suggestions it would be greatly appreciated. Young in my career, mostly have worked in .NET, C#, and Xamarin. Unfortunatly JS and JQuery are a little new to me. Thanks!
My form wasn't preventing a default on form via the submit button. It was only preventing the default on enter. Once I added type="button" inside my <button> tag everything worked fine.

Click function by Enrr

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 .

Validate Dynamic input filed with "formvalidation.io"

I am using Plugin Form Validation to validate the form. And this plugin is working awesome.
But i am facing issue in validating dynamically generated inputs.
Below code is used to generate input fields dynamically
$("#countaccmp").change(function() {
var selVal = $(this).val();
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
$("#textboxDiv").append('<input type="text" name="accmp'+i+'"
id="accmp'+i+'" class="form-control " />');
}
}
})
I tried validating with plugin as below:
$('#form').formValidation({
//--------- Plugin Validator Method -----------//
})
.on('change', '[name="countaccmp"]', function(e) {
//---- Wrote validation here, It works(only on change) but form is getting submitted
even after error ----//
$('.dynDiv').each(function(){
var input = $(this).children('input');
var dynField =
($(this).find("input[name^='accmp']").attr('name'));
if(input.val() == '' || input.val() == undefined){
alert("Error");
return false;
}
})
.on('success.form.fv', function(e) {
//---- Wrote validation here, It works but form is getting
submitted even after error ----//
Same Validation As above
})
Please let me know solution.
You should add your inputs to the plugin in order to be validated.
To do so, use the addField method, see bellow:
$("#countaccmp").change(function () {
var selVal = $(this).val();
$("#textboxDiv").html('');
if (selVal > 0) {
for (var i = 1; i <= selVal; i++) {
var input = ''
+ '<div class="form-group">'
+ ' <label class="col-sm-3 control-label" for="accmp' + i + '">Accmp ' + i + '</label>'
+ ' <div class="col-sm-5">'
+ ' <input type="text" name="accmp' + i + '" id = "accmp' + i + '" class = "form-control " / >'
+ ' </div>'
+ '</div>';
$("#textboxDiv").append(input);
$('#defaultForm').formValidation('addField', 'accmp' + i, {
validators: {
// Here, add your field validators.
}
});
}
}
});
Demo:
http://jsfiddle.net/Arkni/fpps1dqn/
References:
addField documentation: http://formvalidation.io/api/#add-field
Example using addField: http://formvalidation.io/examples/adding-dynamic-field/

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

javascript/jquery remove or delete option from select

I need to delete an option from a select in certain circumstances.
Basically:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
Anyone know the code for me to achieve this?
Many thanks.
Remove by Value:
$("#select1 option[value=1]").remove();
Remove by Text:
$("#select1 option:contains(Text)").remove();
Edit
Since id is unique in the document no need to relate it to the parent select element. You can do simply
$("#option1").remove();
jQuery:
$("#option1").remove();
or
$("#select").remove("#option1");
And the classic javascript method:
var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);
I have seen many people with this problem. I have created this script that could be useful. Hope you like it:
var robable = {
init: function() {
robable.get_selected_option_from_select();
},
get_selected_option_from_select: function() {
$(".robable").off().on("change", function() {
if ($(this).val() !== "") {
robable.add_to_list($(this));
}
});
},
remove_option_from_select: function(select_id, value) {
$("#" + select_id + " option[value='" + value + "']").remove();
},
add_option_to_select: function(select_id, value, text) {
$('#' + select_id).append('<option value="' + value + '">' + text + '</option>');
},
add_to_list: function(select) {
option_text = $(".robable option[value='" + select.val() + "']").text();
//Add to list
$('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>");
robable.remove_from_list();
//Remove from select
robable.remove_option_from_select(select.attr("id"), select.val());
},
remove_from_list: function() {
$(".filter-remove").off().on("click", function() {
var select_id = $(this).data('parent-id');
var option_value = $(this).closest("li").data('value');
var option_text = $(this).closest("li").data('text');
//Add to select
robable.add_option_to_select(select_id, option_value, option_text);
//Remove from list
$(this).closest("li").remove();
});
}
};
robable.init();
<!DOCTYPE html>
<html>
<head>
<title>Select Robables</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<ul id="list"></ul>
</body>
</html>

Categories

Resources