How to add auto complete address to dynamically added input fields - javascript

I want that user to see an alert whenever he doesn't enter proper Google address (or select from suggestion box) on dynamically added text areas. How can I perform that?
I have tried the following code.
I want that when I add new divs at runtime the auto-complete method should apply on that input field and when the user clicks submit button without selecting any suggested address it should display an alert.
Please help me where am I wrong in my code?
function updateNames() {
var rows = $(".clonedInput");
var index = 0;
rows.each(function () {
var inputFields = $(this).find("input");
inputFields.each(function () {
var currentName = $(this).attr("name");
$(this).removeClass("hasDatepicker");
$(this).removeClass("hasTimepicker");
$(this).attr("name", currentName.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var textareaFields = $(this).find("textarea");
textareaFields.each(function () {
var currName = $(this).attr("name");
$(this).attr("name", currName.replace(/\[(.*?)\]/, '[' + index + ']'));
var places = new google.maps.places.Autocomplete(currName);
var a = places.getPlace();
if (a == null) {
alert('Please Select a valid location');
}
else { }
var currId = $(this).attr("id");
$(this).attr("id", currId.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var numberSpan = $(this).find("span.taskNumber");
numberSpan.html(index + 1);
index++;
});
}

Related

Not pulling any data from JQuery object

$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>

Saving dynamic fields to the database - javascript

I want to save the text and select inputs I have added with Append to the database. How do I get the value of the dynamically added select and input fields?
http://jsfiddle.net/qBURS/1848/
function register() {
var count = document.getElementById("buildyourform").childElementCount;
for (var i = 0; i < count; i++) {
}
alert(count);
}
using $( 'form').serializeArray() you can get array of input and select values
Demo : http://jsfiddle.net/qBURS/1849/
$('#register').click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
});
});

If-Else not working as expected if found matching element in array

I have a form where user can fill details and on clicking of add attendee button can add up to 9 people details. I am getting value of user name, selected checkbox item id and item quantity and storing inside array and passing these values in URL to add selected items and created user. On first click I'm checking if item is already there in array.
On first click I'm adding id's and quantity in array what I want to achieve is to increase quantity of that id which is already present in array, each time i click on this button it checks array and update quantity if its already present but its not working.
Here is my code
jQuery("#btnadd2").click(function() {
var qty;
var allVals = [];
var nameatt = jQuery("#txtAttendeeNames").val();
var nameatt= jQuery("#txtAttendeeNames").val();
var emattendee= jQuery("#txtAttendeeEmails").val();
var eventname = jQuery("#hdEventName").val();
var eventlocation = jQuery("#hdLocation").val();
jQuery(".big:checked").each(function() {
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val());
if (jQuery.inArray(jQuery(this).val(), allVals) == -1) {
allVals.push(jQuery(this).val()); //not present in array
} else {
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val() + 1);
}
});
for (var i = 0; i < allVals.length; i++) {
var rslt = allVals.join(',' + qty + ',' + 'custcol_name_of_attendees|' + nameatt + '||custcol_email_o f_attendees|' + emattendee + '||custcol_event_name|' + eventname + '||custcol_event_location|' + eventlocation + ';');
rslt1 = jQuery('#txtCntNameReg').val(rslt);
console.log(rslt1);
}
});
Try this line:
qty = qty + 1;
instead of this,
qty = parseInt(jQuery(this).parents().nextAll().children().find('input[name="quantity"]').val() + 1);
in else condition.

trigger keyup event on a tinymce window

I have a webpage/form with multiple tinymce instances and setup to respond with count of words/characters. everything works fine but could not get the display of word/character count on page load with initial content. here is my setup portion in tinymce setup.
setup: function(ed) {
var text = '';
var wordcount = false;
ed.onKeyUp.add(function(ed, e) {
var contents = new Object();
for(i=0; i < tinyMCE.editors.length; i++){
if (tinyMCE.editors[i].getContent())
contents[i] = tinyMCE.editors[i].getContent();
text = contents[i].replace(/(<([^>]+)>)/g,'').replace(/\s+/g,' ');
text = $.trim(text);
$('#' + tinyMCE.editors[i].id + '_path_row').text(text.split(' ').length + ' words, ' + text.length + ' characters.');
}
}
}
Now the part i am struggling is how to trigger key up when the page is displayed with initial content so that it displays word/character count.
I tried $('#' + tinyMCE.editor(0).id + '_ifr').keyup(); and $('#textarea1').keyup(); but no use.
Can some one help me to get it right?
Add this to your setup:
ed.onInit.add(function(ed) {ed.onKeyUp.dispatch();});
Doc: http://tinymce.moxiecode.com/wiki.php/API3:class.tinymce.util.Dispatcher
After:
tinymce.init
you place the code:
init_instance_callback: function(editor) {
editor.on('keyUp', function(e) {
observa_boton_ir_paso1();
});
}
There was a character missing. Try this (works at elast in my browser FF 3.6.17)
setup: function(ed) {
var text = '';
var wordcount = false;
ed.onKeyUp.add(function(ed, e) {
var contents = new Object();
for(i=0; i < tinyMCE.editors.length; i++){
if (tinyMCE.editors[i].getContent())
contents[i] = tinyMCE.editors[i].getContent();
text = contents[i].replace(/(<([^>]+)>)/g,'').replace(/\s+/g,' ');
text = $.trim(text);
$('#' + tinyMCE.editors[i].id + '_path_row').text(text.split(' ').length + ' words, ' + text.length + ' characters.');
}
});
}

setTimeout() doesn't seem to be working in Firefox?

I have inherited a website! which was designed to work in IE and only IE it seems.. I've now been asked to make the site run in Firefox. I've fixed most of the bugs without any problems but this one has me stumped.
setTimeout(fDelayedFunc, 1000);
This line of Javascript, works fine in IE but in Firefox the function fDelayedFunc never fires. I've removed the setTimeout and the function wrapper and tried running the code as part of the main function. This works without any problems at all.
There is alot of code involved but here's the main but I'm having trouble with. If you'd like to see anymore of the code please let me know.
setTimeout(fDelayedFunc, 0);
//Save the current text box value
var vCurrentTBValue = vJQElement.val();
function fDelayedFunc() {
if (vJQElement.val() == vCurrentTBValue) {
alert("test");
//Get position list box should appear in
var vTop = vJQElement.position().top + 25;
var vLeft = vJQElement.position().left;
//Had to put a special case in for account due to the position co-ords being wrong. This is due to a css error
if (vHiddenFieldToWriteTo == "#ctl00_ContentPlaceHolder1_hfAccountCode") {
vTop = vJQElement.position().top + 58;
vLeft = vJQElement.position().left + 200;
}
else {
vTop = vJQElement.position().top + 25;
vLeft = vJQElement.position().left;
}
//Create div element
var vDivElement = $("<div id='divSearchBox' style='position:absolute; top:" + vTop + ";left:" + vLeft + "; z-index: 40000;'></div>");
//Create list box
var vListBox = $("<select id='lbResults' tabIndex='" + vJQElement.attr("tabIndex") + "' size='4' style='height:400px;'></select>");
//Bind a function to the list box which will select the item via either tab or enter
vListBox.bind("keydown", function() {
//Check if tab or enter has been pressed
if (event.keyCode == 9 || event.keyCode == 13) {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Check if the up arrow has been pressed at the top of the listbox
else if (event.keyCode == 38 && $(vListBox.find(":selected")).val() == $(vListBox.find(":first")).val()) {
//Focus back on the search box
vElement.focus();
}
}).bind("dblclick", function() {
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val());
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
});
//Get search field
var vSearchText = vJQElement.val();
var vDepotID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfDepotID").val();
var vCustomerID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCustomerID").val();
var vCountryID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCountryID").val();
var vConsignee = vJQElement.attr("boolConsignee");
//Set a loading image in place until call completed
vJQElement.css("backgroundImage", "url(images/small-loader.gif)");
vJQElement.css("backgroundRepeat", "no-repeat");
vJQElement.css("backgroundPosition", "right");
//Make AJAX call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewConsignment.asmx/fGetAddressesAndIDs",
data: "{'strSearchText' : '" + vSearchText + "', 'intDepotID' : '" + vDepotID + "', 'intCustomerID' : '" + vCustomerID + "', 'intCountryID' : '" + vCountryID + "', 'boolConsignee' : '" + vConsignee + "'}",
dataType: "json",
success: function fGetAddressesAndIDsResult(GetAddressesAndIDsResult) {
//Make sure there are results
if (GetAddressesAndIDsResult != null && GetAddressesAndIDsResult != "") {
var vNumberOfResults = 0;
var vNumberOfLearntAddresses = 0;
var vLearntAddressUniqueID = "";
//Try to get results (first call will work on Linux and catch will work on Windows)
try {
//Check array exists (if this fails will go to catch)
if (GetAddressesAndIDsResult.d.length > 0) {
//Loop through the results
$.each(GetAddressesAndIDsResult.d, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
}
catch (err) {
//Loop through the results
$.each(GetAddressesAndIDsResult, function() {
//Check for results
if (this.length > 0) {
//Evaluate JSON
var vAddress = eval("(" + this + ")");
//Create list item
var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>");
//Find out number of learnt addresses
if (vAddress.uniqueID.indexOf("ConLA") != -1) {
vNumberOfLearntAddresses++;
vLearntAddressUniqueID = vAddress.uniqueID;
}
//Add list item to list box
vListBox.append(vOption);
//Mark result added
vNumberOfResults++;
}
});
}
//Check if only 1 learnt address was found
if (vNumberOfLearntAddresses == 1) {
//Auto select this address
//Set hidden value to the selected items code
$(vHiddenFieldToWriteTo).val(vLearntAddressUniqueID);
//Create postback
$('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click();
}
//Add list box to div
vDivElement.append(vListBox);
//Check if any results exist in div
if (vNumberOfResults != 0) {
//Append div to page
$("body").append(vDivElement);
//Auto select first item
vListBox.find(".AddressOption:first").attr("selected", "true");
}
}
//Hide loading image
vJQElement.css("backgroundImage", "none");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//Inform user of error
alert("An error occured, please try again");
//Hide loading image
vJQElement.css("backgroundImage", "none");
}
});
}
}
Try this:
setTimeout(function() { fDelayedFunc(); }, 0);
I took setTimeout(function () {function1();}, 1500) out from the addEventListener("load", () => {code})
it worked for me inside Firefox
try this : setTimeout('fDelayedFunc()', 0);

Categories

Resources