Passing parameter to the javascript function fails - javascript

function test() {
var id = 123;
var id12 = 'abcd';
var childDiv = "";
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked('+id12+')">Click</div>';
$("#mydiv").append(childDiv);
}
function newsClicked(param) {
alert(param);
}
Above is the test function, test() is the function which I call inside onClick event of a test div. If I pass id which is a number(integer) it works, If I pass
string it says reference error. Its related to closure I guess. How to solve it.
Whats happening actually here ?

Change:
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked('+id12+')">Click</div>';
to
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked(\''+id12+'\')">Click</div>';
When you append childDiv 1st one to div with integer as parameter the result will be:
<div style="width:20px;height:20px" onclick="newsClicked(3)">Click</div>
which is correct, in case of string the result will be:
<div style="width:20px;height:20px" onclick="newsClicked(string_as_arg)">Click</div>
this is not ok, because string_as_arg is not a variable at last not in the scope. That's why you should enclose it in apostrophes. Then the proper results will be:
<div style="width:20px;height:20px" onclick="newsClicked('3')">Click</div>
<div style="width:20px;height:20px" onclick="newsClicked('string_as_arg')">Click</div>
so there is no really big difference in case of integer constant but string now is properly recognised as string not as variable.

Its working when you are passing a number because the number need not be in quotes but the string has to be in quotes. so to pass string you should use escape char "\"
something like :
newsClicked(\''+id12+'\')

on you issues,
How to solve it.
*note: you can see like \''+id12+'\' on below code
function test() {
var id = 123;
var id12 = 'abcd';
var childDiv = "";
childDiv += '<div style="width:20px;height:20px" onclick="newsClicked(\''+id12+'\')">Click</div>';
$("#mydiv").append(childDiv);
}
function newsClicked(param) {
alert(param);
}
Whats happening actually here ?
newsClicked function will fired after DIV clicked which is recently added to dom,
It will added to dom like
<div onclick="newsClicked(abcd)" style="width: 20px; height: 20px;">Click</div>
here, abcd is use like variable, but does not exist on real.
And you will get error like
abcd is not defined
but if you put id variable which is integer, it will add on dom like
<div onclick="newsClicked(123)" style="width: 20px; height:20px;">Click</div>
which is totally correct on syntax wise.
I guess, you clear on this now.
Cheers,

Related

javascript find div id inside string and delete it's content

I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);
var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]

How to replace a html tag in js?

I have a string in which there are continous occurances of a font tag
<font color="blue">DATA ENTRY</font>
and in some cases like this
<font class="beat">DATA ENTRY</font>
I want to replace the 2 tags with
So that it looks like this
<p>DATA ENTRY</p>
I tried this ,can anyone please suggest me help.Thanks.
text = text.replace('<font [^"]*>',<p>).replace('</font>','');
block.outerHTML = "<p>" + block.innerHTML + "</p>"
where block is any HTML block
it just left to select it correctly with:
var block = document.querySelector(".selector");
If you want to stick with your simple string manipulation, you need to use regular expressions and correct the replacements in your replace calls:
text = text.replace(/<font[^>]*>/g,'<p>').replace(/<\/font>/g,'</p>');
Since you just need to replace the string you can do this with just one replace statement.
text = text.replace(/<(\/*)font[^>]*>/g, '<$1p>');
If you using jQuery with replaceWith
$('font').replaceWith('<p>DATA ENTRY</p>');
First of all the font tag is deprecated and should not be used.
Get an array of the tags you want to replace.
var elems = document.getElementsByTagName('font');
Go through loop and replace old HTML with new HTML
for (var i = 0; i < elems.length; i++)
{
var target = elems[i].innerHTML;
elems[i].innerHTML = target.replace(/(<p)/igm, '<font').replace(/<\/p>/igm, '</font>');
}
Note: This is not tested but should work.
Try like this :
$('font').contents().unwrap().wrap('<p/>');
In javascript, you can do something like this :
var str="<font>hello world</font>";
str = str.replace(/<font>/, "<p>");
str = str.replace(/<\/font>/,"</p>");

How to convert html to variable in javascript?

I have problem while convert html to javascript variable.
My HTML Code
<div onclick="openfullanswer('2','Discription part','This is the code part');">
I want to create this html code dynamically, but I have the problem in quote(" and ')
I tried like below
for(i=0;i<result.length;i++)
{
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
}
https://jsfiddle.net/8782n60z/1/
Way 1:
You should have to change the sequence of single and double quotes and have to escape the single quotes with '\' in on-click function arguments
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +='<div onclick="openfullanswer(\''+result[i].ReplyID+'\',\''+result[i].Description+'\',\''+result[i].Code+'\');">Test code</div>';
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
Way 2:
Don't change the sequence of quotes.
Only change the onclick event declaration quotes from signle to double and escape double quotes with '\' and you need not have to change anything.
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +="<div onclick=\"openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
strVar +="<div onclick=\"openfullanswer('"+result[i].ReplyID+"','"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
try this.
The code you wrote produces the following:
<div onclick='openfullanswer(1,'This is my description','This is my Code Part');'>Test code</div>
The above is not valid since there are single quotes inside the value of onclick.
You will need to escape these characters.
strVar +="<div onclick=\"window.openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
See here an article in SO explaining this matter in detail.
See a working demo here: https://jsfiddle.net/8782n60z/3/
P.S. I changed a bit the way to declare and call the function because it gave an error.
You can use template literal
var result = [];
var obj = new Object();
obj.ReplyID = 1;
obj.Description = "This is my description";
obj.Code = "This is my Code Part";
result.push(obj);
strVar = "";
for (i = 0; i < result.length; i++) {
strVar += `<div
onclick="openfullanswer('${result[i].ReplyID}'
, '${result[i].Description}'
, '${result[i].Code}');">
Test code
</div>`;
}
function openfullanswer(replyid, desc, code) {
alert("success");
console.log(replyid, desc, code);
}
document.getElementById("test").innerHTML = strVar;
<div id="test">
</div>
jsfiddle https://jsfiddle.net/8782n60z/5/
Instead of building the string you could also use document.createElement to generate your div. And then append it to the parent #test
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
var div;
for(i=0;i<result.length;i++)
{
div = document.createElement('div');
div.innerHTML = 'Test code'
div.onclick = openfullanswer;
}
document.getElementById("test").appendChild(div);
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<div id="test">
</div>
Since what you need has already been answered above, I'll just add that the way you are trying to access and manipulate DOM element is not safe or recommended way of handling dom elements. Instead of directly writing to DOM, its better to make use of addEventListner() function and bind your element to it.
For instance, instead of writing ,
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
you should be instead doing
strVar.outerHTML += '<input id="btncall" ...>'
document.getElementById ("btncall").addEventListener ("click", openfullanswer(parameters), false);

How to find if an ID is present in a variable which has HTML content

Am trying to find if the ID is present in a variable which has HTML content.
ID name is getting attached to DIV element by dynamic variables.
strHTML = "<div id='"+var1+var2+"'>"
Now, i like to check if a particular ID is present in strHTML.
How do i do that.?
Thanks in advance.
EDITED
Added actual code for more clarity...
for(data in ArrayOFObjects)
var splitDate = ArrayOFObjects[data]["NewsDate"].split("-");
**if(!$(strHTML).find('#'+splitDate[1]+splitDate[0]))** // if condition is not correct, just my try
{
strHTML += "<div id='"+splitDate[1]+splitDate[0]+"></div>"
}
}
So when the next for in loop happens, i like to check if the ID already exist in strHTML, if it exists then i do not want the DIV creation to happen
Thanks
If you want to know if your HTML contains an element whose id contains some value, you may do
var $elements = $('[id~="'+someValue+'"]', '<div>'+strHTML+'</div>');
var doContain = $elements.length>0;
If your string strHTML is really something like "<div id='"+var1+var2+"'>", then simply use a regex :
var id = strHTML.match(/["']([^\"']*)["']/)[1];
and look in id for your id.
You can use javaScript's search function:
var n=strHTML.search(var1+var2);
if (n > -1)
{
// found it!
}

Pass variable in document.getElementByid in javascript

I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product

Categories