Use jquery in the javascript object - javascript

Bellow I show some example. How I can add some jquery expression into onCalculate() function.
var obj = {
id: '',
onCalculate: function () {
var _date = $("#date").val(); //jquery expression doesn't work here
// how I can do it?
}
};

You can call function like this. See working snippet.
var obj = {
id: '',
onCalculate: function() {
var _date = $("#date").val(); //jquery expression doesn't work here
// how I can do it?
console.log(_date);
}
};
$("#date").keyup(function() {
obj.onCalculate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='date' />

Related

How to handle Jquery custom funtions undefined scenario?

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

Multiple jQuery regex test

I'm trying to perform multiple regex test on input filed.
Below the script:
$("#search-registration").keyup(function () {
var input_data = $('#search-registration').val();
var regexTest = function() {
this.withPrefix = /^[iI]-[a-zA-Z]{4}$/;
this.noPrefix = /^[a-zA-Z]{4}$/;
}
if(regexTest.withPrefix.test(input_data) || regexTest.noPrefix.test(input_data)) {
console.log(input_data);
$( "div.result" ).html(input_data);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-registration" name="regcode" class="form-control" placeholder="Search">
<div id="result">
</div>
I'm not able to perform the double regex and I get the following error:
Uncaught TypeError: Cannot read property 'test' of undefined
What am I doing wrong? Honestly I'm not able to figure out the issue.
Thanks
You need the 'new' keyword before function, like this:
var regexTest = new function() {
this.withPrefix = /^[iI]-[a-zA-Z]{4}$/;
this.noPrefix = /^[a-zA-Z]{4}$/;
}
Try using
var regexTest = Object({
withPrefix : "/^[iI]-[a-zA-Z]{4}$/",
noPrefix : "/^[a-zA-Z]{4}$/",
test : function (input_data) {
//test code here
}
});
Instead of
var regexTest = function() {
this.withPrefix = /^[iI]-[a-zA-Z]{4}$/;
this.noPrefix = /^[a-zA-Z]{4}$/;
}

Alternative to HTML in String

I'm using this code right now, but I'm not really liking the way it looks.
function createPageSettingsPopup(page) {
return '<div class="form-group">' +
'<label for="page-title">Title</label>' +
'<input type="text" class="form-control" id="page-title" value="' + page.title + '">' +
'</div>'
}
Is there any alternative to write the HTML in strings to make it look better?
You could use template engines. This is at the expense of elements in the page, but the code will look much cleaner and the template easier to understand as HTML. Put the template in a script tag with type set to text/template
<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>
And modify your function as below. Remember to cache the template.
var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}
var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}
console.log(
createPageSettingsPopup({title:'Hello World'})
);
<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>
The above is a minimal example of a template engine, but there are great ones like mustache, handlebars.js, and pug.js
Assuming ES6 you can use backticks:
return `<div>
...
</div>`;
Or have a look at react, to manipulate your DOM, they use jsx which is really nice:
const element = <h1>Hello, world!</h1>;
In case you are using jQuery, sometimes you can do things like these:
var div = $('div').addClass('form-group');
div.append($('label').attr('for', 'page-title').text('Title');
...
Depending on your problem at hand it might also make sense to have the full html structure written up-front and then just manipulate some content and styling using js. In your example:
$('div#title').show();
$('div#title').find('label.page-title').text('Title');
You can try creating a HTML utility that creates elements, add necessary properties and the returns element.
I have created a small implementation of this utility in sample. Benefit of this is you can modify this utility to work with JSON based structure to create dynamic HTML.
Sample
function createPageSettingsPopup(page) {
var divParams = {
class: 'form-group'
}
var labelParams = {
for: 'page-title'
}
var inputParams = {
type: 'text',
class: "form-control",
id: 'page-title',
value: page.title
}
var div = utils.createMyElement('div', '', divParams);
var label = utils.createMyElement('label', 'Title', labelParams)
var input = utils.createMyElement('input', '', inputParams)
div.appendChild(label);
div.appendChild(input);
document.body.appendChild(div)
}
window.addEventListener('load', function() {
createPageSettingsPopup({
title: "foo"
})
})
// This code can be exported to another file
var utils = (function() {
function createMyElement(type, htmlString, params) {
var el = document.createElement(type);
if (htmlString)
el.innerHTML = htmlString;
addProps(el, params)
return el;
}
function addProps(el, props, key) {
if (Object.keys(props).length) {
for (var k in props) {
if (typeof(props[k]) === "object") {
addProps(el, props[k], k);
} else {
if (key) {
el[key][k] = props[k]
} else {
el[k] = props[k]
}
}
}
}
}
return {
createMyElement: createMyElement
}
})()
You can also try JSON based form.
Sample
JSFiddle
window.addEventListener('load', function() {
createPageSettingsPopup({
title: "foo"
})
})
function createPageSettingsPopup(page) {
var form = utils.createForm(getFormData(page))
document.body.appendChild(form)
}
// This can be stored in JSON file or in db and then can be fetched
function getFormData(page) {
var json = {
type: "div",
params: {
class: 'form-group',
innerHTML: "",
},
children: [{
type: 'label',
params: {
for: 'page-title',
innerHTML: "Title"
},
}, {
type: 'input',
params: {
type: 'text',
class: "form-control",
id: 'page-title',
value: page.title
}
}]
}
return json
}
// This is a generic utility and can be exported to a utility file
var utils = (function() {
function JSONBasedForm(form_json) {
var el = "";
if (form_json) {
el = createMyElement(form_json.type, form_json.params);
if (form_json.children && form_json.children.length > 0) {
form_json.children.forEach(function(child) {
var c_el = JSONBasedForm(child)
c_el && el.appendChild(c_el)
})
}
}
return el;
}
function createMyElement(type, params) {
var el = document.createElement(type);
addProps(el, params)
return el;
}
function addProps(el, props, key) {
if (Object.keys(props).length) {
for (var k in props) {
if (typeof(props[k]) === "object") {
addProps(el, props[k], k);
} else {
if (key) {
el[key][k] = props[k]
} else {
el[k] = props[k]
}
}
}
}
}
return {
createForm: JSONBasedForm
}
})()
This does not look better but is another way to create elements in JavaScript
Using the document.createElement you have more programmatic control over which attributes to set
function createPageSettingsPopup(page) {
var div = document.createElement("div");
div.className="form-group";
var label = document.createElement("label");
label.htmlFor="page-title";
label.textContent="Title";
var input = document.createElement("input");
input.type="text";
input.className="form-control";
input.id="page-title";
input.value=page.title;
label.appendChild(input);
div.appendChild(label);
return div;
}
Same in jQuery:
function createPageSettingsPopup(page) {
var $div = $("<div />",{"class":"form-group"});
$div.append(
$("<label />", {"htmlFor":"page-title").text("Title").append(
$("<input/>", { "type":"text","class":"form-control","id":"page-title"}).val(page.title)
)
);
return $div;
}

On Change not firing when input value is entered

I cannot figure out why my input is not showing the results of my calc. based on the input change. I have checked to see if there is an output in the console.log and there is, I am use an IDE environment to develop an have noticed errors when coding that don't involve the code it is the IDE I'm wondering if this is the case? Or is there something not right with the code on my part.
Any help would be appreciated
HTML
<td>InPut</td>
<td>
<input class="" id="bhp_1" type="number" value="440">
</td>
<td>OutPut</td>
<td>
<input class="" id="bpm_l60" type="number" value="567.11">
</td>
JavaScript
var manualEntry = function(){
var bhp = parseFloat($('#bhp_1').val());
var bhp2 = parseFloat($('#bhp_2').val());
var bhp3 = parseFloat($('#bhp_3').val());
var bhp4 = parseFloat($('#bhp_4').val());
var bhp5 = parseFloat($('#bhp_5').val());
var bhp6 = parseFloat($('#bhp_6').val());
var bhp7 = parseFloat($('#bhp_7').val());
var bhp8 = parseFloat($('#bhp_8').val());
var bhp9 = parseFloat($('#bhp_9').val());
var bhp10 = parseFloat($('#bhp_10').val());
var bhp11 = parseFloat($('#bhp_last').val());
return {
val: bhp,
val2: bhp2,
val3: bhp3,
val4: bhp4,
val5: bhp5,
val6: bhp6,
val7: bhp7,
val8: bhp8,
val9: bhp9,
val10: bhp10,
val11: bhp11
}
}
manualEntry();
// console.log(manualEntry());
//Filter for return object
var bhpKeys = Object.keys(manualEntry())
var bhpmatchingKeys = bhpKeys.filter(function(key) {
return key.indexOf('val', 'val2', 'val3', 'val4', 'val5', 'val6','val7','val8','val9','val10','val11') !== -1
});
var bhpmatchingValues = bhpmatchingKeys.map(function(key) {
return manualEntry()[key]
});
var bpm_l60 = function() {
var mySpline = new MonotonicCubicSpline(
[4000, 8000, 15000, 20000, 25000, 30000, 35000, 40000, 60000, 80000, 100000], bhpmatchingValues);
var total = mySpline.interpolate(43592.990983668795);
$('#bpm_l60').val(+total.toFixed(2));
$('#bpm').val(+total.toFixed(2));
return total;
};
bpm_l60();
Onchange listener
document.getElementById("bhp_1").onchange = (function() {
manualEntry();
bpm_l60();
});
Here is a Code pen example of the problem I'm having.
http://codepen.io/coryk/pen/zqgPyz?editors=1011
Put your js code inside
window.onload = function() { }
Where are you calling the onchange listener? If it's before the <input> elements are created, it won't work. You're already using jQuery, try
$(document).on("change", "#bhp_1", function () {
manualEntry();
bpm_l60();
});
Try changing your onchange event to the following:
document.getElementById("bhp_1").onchange = function() {
manualEntry();
bpm_l60();
}
What you are currently doing is wrapping your function in an additional method call () which is not the correct syntax to use for binding an onchange event to an element.

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");
});

Categories

Resources