Why button not created properly in JS function? - javascript

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

Related

Bootstrap 4 not updating onclick attribute of popover

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

Pass jquery object to javascript onclick

I'm trying to do this:
var linha = $(this).parent().parent()
$("#modal-footerMsg").append(
"<button type='button' id='btnOK'
class='btn btn-md' onclick='RemoveLinha(" + linha + ");'> OK");
which will execute this function:
function RemoveLinha(element) {
element.parent().parent().remove();
}
how can i do this? Pass the jquery object to the function?
Hi attach event listener after appending your HTML like this
$(document).ready(function(){
var linha = $("#removeElm")
$("#modal-footerMsg").append("<button type='button' id='btnOK' class='btn btn-md'> OK</button>");
$("#btnOK").on("click",function(){
RemoveLinha(linha);
})
function RemoveLinha(element) {
element.remove();
}
})
Currently you are trying to put a jQuery object - literally an object, not a string representation of it - into a string. This won't work.
You are already using jQuery, which is great for constructing elements and creating event handlers on those elements, without reverting to setting inline strings of onclick="". Create the button element separately, setup the click event handler, then append it to the modal:
// get parent element
var linha = $(this).parent().parent();
// create a button
var button = $('<button type="button" id="btnOK" class="btn btn-md" />');
// add click event handler to button
button.click(function() { RemoveLinha(linha); });
// append button and text to modal
$("#modal-footerMsg").append(button, "OK");
Or if you want to be concise but messy:
var linha = $(this).parent().parent();
$("#modal-footerMsg").append(
$('<button type="button" id="btnOK" class="btn btn-md" />')
.click(function() { RemoveLinha(linha); }),
"OK"
);

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>';

Dynamically building a button with an onClick

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.
I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".
Here is a code snippet of the construction as it stands.
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
Value="Go To Field"
onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
/>
</div>';
return structure;
};
This is outputting:
<button class="inputButton"
value="Go To Field"
onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>
As you can see, the quotations will not be out put correctly and so break on click.
Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.
Kind Regards.
As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).
1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
value="Go To Field" data-field="' + this._field.name + '"/>
</div>';
return structure;
};
2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:
$(document).on('click', '.inputButton', function() {
var $button = $(this);
var field = $button.data('field');
goToFieldFromAlert('input[name="' + field + '"]');
});
You should create element using jQuery. This is much cleaner and error free approach
An example with your code
InvalidField.prototype.getMessageStructure = function(){
var structure =
$('<div></div>').append(
$('<span></span>').text(this._message)
);
structure.append(
$('<button></button>')
.addClass('inputButton')
.text("Go To Field")
.click(function(){
goToFieldFromAlert($(this._field.selector));
})
);
return structure;
};
The following example will dynamically add buttons:
hello.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = value; // some value
card.style.backgroundColor="#5ABC7B";
document.body.appendChild(card);
});

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