I am building a string and creating a table with it:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog();" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
When I click the link, the function fires.
I need to pass some Javascript variables in the function VarTest() so I've written the code:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+ VarTest + ');" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
But nothing happens, I've tried all sorts of options but nothing works.
This works (with +) but then nothing gets passed.
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+')" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
var VarTest = "my text";
function portal_openModalDialog(Title) {
alert(Title);
}
Any ideas?
UPDATE: (this now works for single argument)
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle+'")" >'+ oListItem.get_item('Title') +'</a>' + '</td>';
but not if I pass 2 arguments:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle,oDescription+'")" >'+ oListItem.get_item('Title') +'</a>' + '</td>';
The html gets rendered on the screen:
<a href="#" onclick="portal_openModalDialog1("Bank of England</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1("Investor centre - Reed Elsevier</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1("This is some news</tr></table> </body>
Here is source code of html page (cant see why it would not render correctly):
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle+'")" >'+ 'click here' +'</a>' + '</td>';
table += ''+ ''+ 'click here' +'' + '';
The content of onclick attribute is parsed as JavaScript. You can just pass the variable, no magic involved:
<script>
var myVar = 'foo';
function myFunction(aVar) {
alert('The variable: ' + aVar);
}
</script>
<button onclick="myFunction(myVar)">Click me</button>
You can pass multiple variables, just make sure that the comma (,) is part of the resulting HTML and not a comma in the original JavaScript code:
<script>
var myFirstVar = 'foo';
var mySecondVar = 'bar';
function myFunction(aVar, anotherVar) {
alert('The first variable: ' + aVar + ', and the second: ' + anotherVar);
}
</script>
<button onclick="myFunction(myFirstVar, mySecondVar)">Click me</button>
If you want to generate the button in the page, and you are sure your variables are meant to be strings, you can keep quoting the parameters:
document.write('<button onclick="myFunction("' + myFirstVar + '", "' + mySecondVar + '")">Generated button 1</button>');
But, it is easier and less error prone to just pass the variables directly:
document.write('<button onclick="myFunction(myFirstVar, mySecondVar)">Generated button 2</button>');
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I am currently working on a web application that needs to preview some report using a button inside a data table. each row on the data table has its own button created on the javascript and I want to trigger that button using the same javascript file.
Is there anyway to do this? Please see code below:
$('#AccountList').append('<tr data-empid="' + row.ci_ID + '">'
+ '<td text-align:center;">' + row.ciCODe + '</td>'
+ '<td text-align:center;">' + row.FullName + '</td>'
+ '<td text-align:center;">' + row.LoanType + '</td>'
+ '<td text-align:center;">' + row.Bank + '</td>'
+ '<td text-align:center;">' + row.Amount + '</td>'
+ '<td text-align:center;"><label class="'+ xLabel +'"><h6>' + xText + '</h6></label></td>'
+ '<td text-align:center;"><button class="btn btn-primary btn-outline-primary" id="btnPreview" name="btnPreview"><i class="icofont icofont-prescription"></i></button>'
+ '<button class="btn btn-danger btn-outline-danger" id="btnReinvestigate" name="btnReinvestigate"><i class="icofont icofont-redo"></i></button>'
+'</td>'
+ '</tr>');
$("#btnReinvestigate").click(function(){
alert("Hello Worlds!");
});
$("#btnPreview").click(function(){
alert("Hello World!");
});
Thanks and Regards
Appending rows where elements share the same id is semantically invalid.
In fact, you can do away with the id attribute on the buttons and instead utilise the name attribute.
You'll then want to delegate your click handlers to #AccountList
$('#AccountList')
.on('click', 'button[name="btnReinvestigate"]', function () {
alert('Reinvestigate')
})
.on('click', 'button[name="btnPreview"]', function () {
alert('Preview')
});
So I got into this tricky situation. I have a variable which present table data:
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall()">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
Latter on I will append that into my table. Now, when I click Call button, I want to get the button's Id. I have tried this way:
function handleClick() {
console.log(this);
}
but it refer to window object. Can anybody show me the way to achieve my goal? Thanks
Simply pass the elements ID as a parameter to keep it simple,
Change,
onclick="handleCall()"
to,
onclick="handleCall(this.id)"
this referring to the button in question the user is pressing.
then,
function handleClick(id) {
console.log(id);
}
Finally don't use inline event handlers as they are a pain to work with in the long run, make use of the addEventListener method.
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall(this)">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
function handleClick(element) {
console.log(element);
//here you will have all element properties
}
There are two ways you can do this, you can do it via jQuery by using attr or if you are wanting to stay vanilla Javascript then you can use .id.
For jQuery please see code below:
console.log(jQuery('element').attr('id'));
For Javascript please see code below:
console.log(element.id);
i am creating a search suggestion and i want to create a div and put suggestion elements like full name, image and ... in it.
so i have a empty div in my HTML code that my suggestions will be added to it.
<input type="text" name="query" autocomplete="off" id="base_main_search_box">
<button type="button" value="" id="base_main_search_box_button"></button>
<div id="main_searchSuggestion">
</div>
i want to appear search suggestions when user key up in input type.
so i create jQuery function.
my jQuery function is:
$('#base_main_search_box').keyup(function () {
$.ajax({url:'http://localhost:8000/search_suggestion/',success:function(result){
$(addSuggestion).append('<div class="base_searchSuggestionItem">' +
'<img src="' + result.movie_images[i] + '" class="base_searchSuggestionItem_image">' +
'<div class="base_searchSuggestionItem_info">' +
'<p class="base_searchSuggestionItem_info_name">' +
'<a href="">' +
result.movie_names[0] +
'</a>' +
'(' +
result.movie_yearProduction[0] +
')' +
'</p>' +
'<p class="base_searchSuggestionItem_info_description">' +
result.movie_descriptions[0] +
'</p>' +
'</div>' +
'</div>');
console.log('final: '+addSuggestion.innerHTML);
}
}});
});
the output is:
"final: undefined"
it is not correct.
As per the docs
.html() is not available on XML documents so you need to add it to DOM before setting or checking its HTML.
change the sequence as following
$(addSuggestion).append(search_item);
$(search_item).html(
div_innerHTML
);
console.log('div_innerHTML: '+div_innerHTML);
console.log('search_item: '+$(search_item).innerHTML);
I have a javascript function like this
function doIt(link) {
alert(link);
}
And i call this function in below given JS code, where i am creating an a tag and appending it to my html page on runtime:
jQuery.each(data, function (i, val) {
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); "> \
<div class=" card"> \
<img src='+ val.Img + ' /> \
<p>'+ val.Title + '</p> \
</div> \
</a>';
document.getElementById('News').innerHTML += card;
});
Say for example our val.Img = 'abcd'
When i click the a tag it calls doIt(abcd), but i want to call doIt('abcd') passing it as string.
Is there any workaround for this.
You need to escape quotes like
var card ='<a href="Views/NewsDetail.html" onclick="doIt(\'' + val.Img + '\'); "> \
//^ ^
As per your current implementation the argument abcd is treated as variable thus you must be getting undefined
You can do this one:
var card='';
The below HTML string already used both quotes till the characters doIt(. So any string type values inside the quotes, must be escaped using any of the quote-character.
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); ">'
to [added quote escape character \"]
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(\"' + val.Img + '\"); ">'
Yet another option:
var doItAndRedirect=function(val){
//do stuff with val here
window.location = "Views/NewsDetail.html";
}
jQuery.each(data, function (i, val) {
var card = '<a href="javascript:doItAndRedirect(\''+ val +'\')">'+
'<div class=" card">' +
'<img src='+ val.Img + ' />' +
'<p>'+ val.Title + '</p>' +
'</div>'+
'</a>';
document.getElementById('News').innerHTML += card;
});
It is already a string it just doesn't display '' on alert but at the background it is string only.
doIt("' + val.Img + '");
should do it, but if you have, e.g, " inside val.Img you need to quote those: How do I add slashes to a string in Javascript?
I saw in the firebug the ID is like this whereas I want the value of existingProductArray[i] to be the ID. What am I doing wrong?
var html ='<li id="existingProductArray[i]">'
+ '<input type="image" id="existingProductArray[i]" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ existingProductArray[i]
+ '</li>';
Try this
var id = existingProductArray[i];
var html ='<li id="' + id + '">'
+ '<input type="image" id="' + id + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ id
+ '</li>';
But
ID hence the name should be unique you are giving 2 elements the same ID ( that's a bad idea )
Try changing:
+ '<input type="image" id="existingProductArray[i]" src="...>'
to
+ '<input type="image" id="'+existingProductArray[i]+'" src="...>'
So in your line of code it was just using it as text string. You need to break out of the string and do it.
You just need to close the quotes and concatenate it in with +:
var html ='<li id="existingProductArray[i]">'
+ '<input type="image" id="' + existingProductArray[i] + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ existingProductArray[i]
+ '</li>';
your reference is inside the quotations
var html ='<li id="'+existingProductArray[i]+'">'
+ '<input type="image" id="'+existingProductArray[i]+'" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ existingProductArray[i]
+ '</li>';
I stumbled upon the same problem, I know my problem is not 100% the same as yours but I bet I can help other people out who search for this kind of problem.
I was trying to add a variable as a ID name for a div. I tried several methods mentioned above but none of those seemed to work.
I did the following:
div.id = array[i];
which in your case would have simply been:
id=existingProductArray[i];
No " " or + needed, don't forget to declare the i variable. This might be very obvious for some people with more experience.