How to handle Jquery custom funtions undefined scenario? - javascript

I defined a custom funtion in jquery like below
jQuery.predictiveTextInit = function (obj, options) {
//do something
}
and i am calling the funtion like below
<script>
$(document).ready(function () {
assignselectedvalues();
})
function getpredictions_c(e, selector, loc) {
localStorage['SearchCache'] = "";
$(".myInputContainer2").hide();
var hdnPredictiveval = $('#hdnPredictiveURL').val();
var formatselector = "." + selector;
var formatloc = "." + loc; //".searchCommunityLocation";//"." + loc;
var ptObj = { url: hdnPredictiveval, suggestContainer: formatselector };
$.predictiveTextInit($(formatloc), ptObj);
$(".searchCommunityLocation").val(e.target.value);
}
</script>
html
<input type="text" class="#searchCommunityLocation" onkeyup="getpredictions_c(event,'#dynamicContainer','#searchCommunityLocation')" name="searchCommunityLocation" id="searchCommunityLocation"/>
but some times i am getting error saying like $.predictiveTextInit is not a function but sometimes works fine what could be reason?
thanks in advance

Related

Click event for button created dynamically [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
In my AJAX success function, I've written:
rt = JSON.parse(responseText);
for (i = 0; i < rt.length; i++) {
$("#inv").append("<tr><td>" + rt[i][0] +
"</td><td><input type='submit' value='Sync' " +
"class='syncnow' id='sync"+rt[i][6]+"' /></td></tr>");
}
I've tried jQuery code:
$(".syncnow").on("click", function() {
alert("Hi");
});
Tried .click(), $(".tdclass").on("click", ".syncnow", function() {}) etc., but to no avail. Can anyone help me with this?
You can't add an event to a not yet created element. You need to add it to a higher place and catch it when it is bubbling up.
Try this:
$("body").on("click", ".syncnow", function() {
console.log('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
You can attach event to element when created using jQuery()
$.each(rt, function(i, value) {
$("<tr>", {
appendTo: "#inv",
html: $("<td>", {
html: value[0],
append: $("<input>", {
type: "submit",
value: "Sync",
"class": "syncnow",
id: value[6],
on: {
click: function(event) {
console.log("clicked");
}
}
})
})
})
})
Try this one
$(document).on("click", ".syncnow", function() {
alert('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
I've written a jquery function, to append syncbuttons to an invElement
$.fn.appendSyncElements = function(responseText, onComplete) {
var invElement = $(this);
var rt = JSON.parse(responseText);
var base_sync_attrs = [];
base_sync_attrs.push("type=\"submit\"");
base_sync_attrs.push("value=\"Sync\"");
base_sync_attrs.push("class=\"syncnow\"");
var base_sync_attrs_str = base_sync_attrs.join(' ');
for(var i = 0; i < rt.length; i++) {
var crt = rt[i];
var crt_sync_label = crt[0];
var crt_sync_attrs = crt[6];
var sync_attrs = [];
sync_attrs.push(base_sync_attrs_str);
sync_attrs.push("id=\"sync_" + String(i) + "\"");
sync_attrs.push("data-sync_index=\"" + String(i) + "\"");
sync_attrs.push(crt_sync_attrs);
var sync_attrs_str = sync_attrs.join(' ');
var syncElement = $('<input ' + sync_attrs_str + ' />');
syncElement.click(function(e) {
var syncBtn = $(this);
console.log("the syncBtn was clicked at index " + String(syncBtn.data('sync_index'));
var syncEvent = {
'event' : e,
'button' : syncBtn,
'fullresponse': crt,
};
if(typeof(onComplete) === 'function') {
onComplete(syncEvent)
};
});
var tableRowElement = $('<tr><td class="synclabel" ></td><td class="syncinput" ></td></tr>');
tableRowElement.find("td.synclabel").html(crt_sync_label);
tableRowElement.find("td.syncinput").append(syncElement);
invElement.append(tableRowElement);
};
};
Usage
$("#inv").appendSyncElements(responseText);
Or
$("#inv").appendSyncElements(responseText, function(syncResult) {
console.log("This is a custom Complete Method");
});
You can use document on click event:
$(document).on("click",".syncnow",function() {
alert("Working");
});
Also you can check my answer here:
Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?
Thanks
$("body").on("click",".syncnow", function() {} )

Format number with commas in .each function

So I have some js which is converting a div class's number through a daily exchange rate engine. It outputs correctly as it should and I am now trying to separate this number it outputs using jQuery and a function I found whilst doing some research. I am trying to feed the number to the function using a .innerHTML method. I have got the function to alert a converted number but I have multiple elements which this function should run for, so have used an .each function - this is where something isn't working. I get no alert so I think there is something wrong with the .each code.
Can anyone see anything that might be causing it?
The complete code is here:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
//alert("Product Costs" + rate.toFixed(4))
}
$.getJSON("http://api.fixer.io/latest", demo);
});
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
</script>
I think the reason is
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
happends before you created the converted elements. Because you put the creation inside a get call.
I suggest you put this inside the callback of your get call.
Something like this
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
//alert("Product Costs" + rate.toFixed(4))
});
$(".converted").each(function() {
var convertedPrice = $(this).html();
console.log(ReplaceNumberWithCommas(convertedPrice));
});
}
$.getJSON("https://api.fixer.io/latest", demo);

javascript not working, onclick function

I have an HTML page with a heading and 2 Divs, I then have a javascript where I want the heading to change if the user selects one off the Divs.
https://jsfiddle.net/L27xqgfs/1/
var happyMood = getElementById("happy");
var sadMood = getElementById("sad");
happyMood.onclick = function () {
var mainHeading = getElementById("heading");
mainHeading.innerHTML = "You have selected ";
};
sadMood.onclick = function () {
var mainHeading = getElementById("heading");
mainHeading.innerHTML = "You have selected " + sadMood;
};
Please can someone advise where I've gone wrong?
Thanks in advance.
if you call getElementById without any object,then you call window. getElementById, but you really should call document.getElementById. And you should import js file into html(in you local test).
I have created another jsfiddle which is correct.
var happyMood = document.getElementById("happy");
var sadMood = document.getElementById("sad");
happyMood.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected ";
};
sadMood.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected " + sadMood;
};

How can I create a link based on this format: google->someword?

I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});

Object required error Java Script

i have problem with below code which i use for Jira. When i run the code, i get
Object required error at line 4
Could you please Help! the values for approver and assigne are right so there is no problem with them
<script type="text/javascript" charset="utf-8" id="priorityCustomFieldScript">
//utils(common)
var by_id=function(n){
var i=document.getElementById(n);
return { //error line
value:i.value,
set_value:function(v){i.value=v;}
};
};
function setSummaryAndSubmit(e){
e.preventDefault();
e.stopPropagation();
//utils
var id_set=function(n){
var v={};
v.a=function(x,y){v[x]=y;return v;};
v.g=function(){return v[by_id(n).value] || '';};
return v;
};
//approver
var by_id_11690=id_set('customfield_11690').
a('22468','205 SSNL SAP');
//assignee
var by_id_11690_1=id_set('customfield_11690:1').
a('22469','jpechea').
a('22470','amikusi');
var setter=(function(){
var d=new Date();
by_id('customfield_10146').set_value(d.getFullYear());
by_id('summary').set_value('ADI - '
+by_id('customfield_10146').value+' - '
+document.getElementById("customfield_10171").options[document.getElementById("customfield_10171").selectedIndex].text+' - '
+by_id_11690.g()+' - '
+by_id('customfield_10163').value);
//by_id('assignee').set_value(by_id_11690_1.g());
by_id('assignee-container').set_value(by_id_11690_1.g());
var selectedGlobalId;
selectedGlobalId=document.getElementById('assignee-container').value;
jQuery("#assignee").find('option').remove();
jQuery("#assignee").append("<option value='" + selectedGlobalId +"'>JIRA User</option>");
jQuery("#assignee").val(selectedGlobalId).attr("selected", "selected");
}());
//ok
//var form=this;
//form.submit();
jQuery("#customfield_10146").parents('form').submit();
}
jQuery(document).ready(function($) {
function hideSummaryAndAddSeverityHook(){
var row = document.getElementById("assignee-container");
if (row) {
row.style.display = 'none';
}
$('#customfield_10146').closest('div.field-group').hide();
$('#summary').closest('div.field-group').hide();
jQuery("input#issue-create-submit").click( function(event) {
setSummaryAndSubmit(event);});
jQuery("input#issue-edit-submit").click( function(event) {
setSummaryAndSubmit(event);});
}
var currentLocation = window.location.href;
if (currentLocation.indexOf('CreateIssue') > -1 || currentLocation.indexOf('EditIssue') > -1)
{
hideSummaryAndAddSeverityHook();
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (e,context) {
hideSummaryAndAddSeverityHook();
});
}
});
</script>
document.getElementById() returns null if no element is found - you need to check for that in your code. The error you're getting means that i isn't an object - so document.getElementById() returned null in one of your calls.

Categories

Resources