Bootstrap 4 not updating onclick attribute of popover - javascript

I am trying to create a popover in bootstrap 4 with a nested button inside it, but on updating the data-content attribute of that popover with the button element it updates this element, but the onclick attribute is missing.
I have tried using button instead of anchor tag, also tried using plain JavaScript to update the element, but the problem still persists.
I already have set popover property html: true.
This is the js code for update:
function popoverUpdate(cart){
console.log("pop update");
var popoverdata = "<ol>"
for (i in cart){
popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
}
popoverdata += "</ol><a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a>";
$('#cartVal').attr('data-content', popoverdata);
$('#cartVal').popover('show');
}
HTML element whose data-content I am updating:
<button class="btn btn-primary m-lg-2" title="In Cart" id="cartVal" data-content="this is default content" data-toggle="popover" data-placement="bottom"
data-trigger="focus">Cart(0)</button>
Updated element as expected:
<a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a></pre>
Instead updates to:
Hello
As you can see, the onclick attribute is missing.

Here's a hack. First, enable the data-html attribute, then you setup an event listener for clicks on your button, and finally prevent the default behavior
function popoverUpdate(cart){
console.log("pop update");
var popoverdata = "<ol>"
for (i in cart){
popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
}
popoverdata += "</ol><a href='#' class='btn btn-secondary popoverButton'>Hello</a>";
$('#cartVal').attr('data-html', true);
$('#cartVal').attr('data-content', popoverdata);
$('#cartVal').popover('show');
document.querySelectorAll('.popover-body a.popoverButton').forEach((button, index) => button.addEventListener('click', (event)=>{
event.preventDefault();
console.log(5);
//put the rest of your code here
}));
}

Related

Why button not created properly in JS function?

I create button dynamically in my JS function and the put created button to the DOM.
Here is the code:
var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' class="button_air-medium">'+
+'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
$( "#tdStrView" ).append(button);
When I display the creted dynamically button in consle I see this:
"<button id="btnStrView" type="button" onclick=undefined class="button_air-medium">NaN</button>"
it seems that but not created properly the onclick is undefined and img tag is missing.
any idea what I do wrong? Why image button not created properly?
UPDATE:
I tryed to add double quotes to the onclick event:
onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
and the created button is:
"<button id="btnStrView" type="button" onclick="undefined" class="button_air-medium">NaN</button>"
the onclick is still undefined.
You need to add double quotes.onclick will look like this onclick ="yourFunction()"
onclick="' + parent.ExecuteCommand(item.cmdIndex) + '"
// add double quotes in onClick and if you are getting NaN in place of image,
// it means that it is trying to add numbers. I'm not sure yet why this is happening, but
// to fix that, add extra string in second line. like this. and then console button.
var button = '<button id="btnStrView" type="button" onClick="alert(7)" class="button_air-medium">'+
+'' +'<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png">'
+'</button>'
While this code is a lot more verbose, it is more readable and less error prone.
const button = document.createElement('button');
button.id = 'btnStrView';
button.type = 'button';
button.className = 'button_air-medium';
button.addEventListener('click', event => {
parent.ExecuteCommand(item.cmdIndex);
});
const img = document.createElement('img');
img.id = 'streetView';
img.className = 'miniToolbarContant';
img.src = '../stdicons/streetview-icon.png';
button.appenChild(img);
$( "#tdStrView" ).append(button);

JQuery .hide() won't hide button suddenly

I have this a button which a user can click on which adds a comment box at the bottom of the page. My button html looks like this:
<input type="button" name="inspection_2895_14045_comment" tabindex="-1" value="+" class="commentBtn" onclick="generateComment('Test', 14045,1, this )">
So as you can see it calls a method called generateComment which looks like this:
function generateComment(name, id, isInspection, button){
//get the current button and hide it
var btn = $("a[name='" + button.name + "'");
btn.hide();//doesn't work
var generatedName = '';
if(isInspection){
generatedName = "comment_" + id;
}
else{
generatedName = "section_" + id;
}
var comment = $('#comments');
var genHtml = '<div class="bigDataDiv">' +
' <label class="commentBoxLabels">' + name + '</label>' +
' x' +
' <textarea rows="4" class="commentBox" name=' + generatedName + ' maxlength="200"></textarea>'
'</div>';
comment.append(genHtml);
$('html,body').animate({
scrollTop: $(".bigDataDiv").offset().top},
'slow');
}
All this method does it hide the button, generate the comment div then scroll to the newly created div. This code worked no problem and used to hide the button but now for some reason it doesn't work and the button still shows up
As neokio pointed out, you forgot the closing ], but you are also selecting an anchor tag, when what you want is an input tag.
var btn = $("input[name='" + button.name + "']");
Since button in your generateComment function is a reference to the button you could just use this to set your btn variable:
var btn = $(button);
Then you don't have to worry about putting strings together to make your selector, or what kind of element the button is. Your hide should work no matter what that way.
You forgot the closing ] ...
var btn = $("a[name='" + button.name + "']");
You're also missing a + before the final '</div>';

Jquery - click to edit script

I have a table of data where users can edit the information by a click. The click will replace the number data with an input text field that will allow the users to submit their edits. I've included a "cancel" link where once clicked, the input field will disappear and the data text reappears. However, if I clicked to edit multiple rows and cancel it, the data text will reappear as the first row that I clicked.
For example, my table of data looks like this
Ref No. | Container No.
0006 | OLKI2940
0005 | KL2223KL
0004 | PPO80596
0003 | JLJ93459
If I clicked to edit Container # "OLKI2940", I cancel it and "OLKI2940" will reappear fine. However, if I clicked to edit the second row Container # "KL2223KL" and cancel, the Container # "OLKI2940" will appear. So it's copying the first row that I clicked. How do I get it for the right container number to appear?
My html as follow:
// this is in a loop
<tr>
<td>{{ refnum }}</td>
<td id="{{ ctrnum }}">{{ ctrnum }}</td>
</tr>
My JS:
// editing container no
$('#containers').delegate("a.ctrnoedit","click", function() {
var index = $(this).closest("td").attr("id");
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='"+index+"'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function() {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>"+index+"</a>");
})
})
JS fiddle example:
http://jsfiddle.net/9Lsgw2ve/1/
although your way of coding violates the rules of html by generating duplicated ids, this is a Working Demo
var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
index = $(this).closest("td").attr("id");
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function () {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
})
})
you just need to define index out of the click function
also if you wanna get the exact same values as it was in the links then try this:
DEMO
var index='';
// editing container no
$('#containers').delegate("a.ctrnoedit", "click", function () {
index = $(this).closest("td").children('a').html();
var html = "<form id='editctrno' method='post'><input name='ctrnum' type='text' value='" + index + "'>" +
"<br><button type='submit'>Update</button> <a href='#' id='canceledit'>Cancel</a></form>";
$(this).closest("td").html(html);
$('#containers').delegate("a#canceledit", "click", function () {
$(this).closest("#editctrno").html("<a href='#' class='ctrnoedit'>" + index + "</a>");
})
})

Bind gridview using jquery : Have table data clickable

I have this part of code which is suppose to pass values from my dataset to a gridview.
var row = $("[id*=gvPlastic] tr:last-child").clone(true);
var codes = $(this).find("Code").text();
if ($(this).find("Stock").text() == 'Y') {
$("td", row).eq(7).html('<a href="#" onclick="getStock()" value=' + codes + ' />' + codes + '</a>');
}
else {
$("td", row).eq(7).html($(this).find("Stock").text());
}
How ever the variable code is outside the link i.e shown below:
<a value="80043" onclick="getStock()" href="#"></a>
80043
I am binding a gridview using jquery. My intention was the boundfield Stock be clickable if value is Y.
You are closing the anchor element in your code twice...
<a href="#" onclick="getStock()" value=' + codes + ' />' + codes + '</a>
Should be:
<a href="#" onclick="getStock()" value=' + codes + '>' + codes + '</a>
(note the removed "/" right before the anchor's greater-than character)

Calling function from button not working for html created using javascript

I am using javascript to create html page , but not able to call some function on button click .
var alernative = "plot1";
var buttonvalue= "mybutton";
function callme()
{alert("hello");}
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' + callme() + '";></div>');
In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .
Hoping for Suggestion or some help .
You need to pass the function name as a part of the string:
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
It is a bad practice to write HTML with strings, DOM exists for one reason!
var input = $('<input/>', {
type: "button",
style: "float: right",
value: buttonValue
}),
element = $('<div/>').append(input);
input.click(function () {
callme();
});
$('#test').html(element);

Categories

Resources