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"
);
Related
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);
I am using dynamically added textbox (class name is myclass) and need to validate all textboxs. My code is here. This coding is working for only first textbox. If i add new text box, the code is not working. I don't know how to write the event binding in each(function())
$('.myclass').each(function() {
$(this).rules('add', {
required: true,
messages: {
required: "Required input"
}
});
});
HTML CODE
<div id="TextBoxesGroup">
<div id="Div1">
<input type='text' value ='' class='myclass' />
</div>
</div>
<input type="button" name="add" id="addButton" value="Add">
$(document).ready(function(){
var counter=2;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'Div' + counter);
var texthtml = "";
texthtml += "<input type='text name='fieldname[]' class='myclass' value='' />";
newTextBoxDiv.after().html(texthtml);
newTextBoxDiv.appendTo("TextBoxesGroup");
});
The each function can only be applied to elements already existing in you DOM. Elements which are added later will not be affected. You need to apply rules() to them after they are created. Like this:
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'Div' + counter);
...
$( newTextBoxDiv ).rules( ... );
});
Ps: to get more readable code, try to encapsulate your functionality into functions. Like
function addRulesToElement( element ) {
$( element ).rules( ... );
}
You can then call this function from your each() loop and the #addButton click-handler without repeating yourself.
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);
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Click event for elements added to DOM dynamically
(2 answers)
Closed 9 years ago.
I have the following jquery code to create a button for each row in a table:
$("#add_to_rule").click(function(){
var contact_type=$("#contact_types option:selected").val();
var email_address = $('#email_address').val();
var call_order = $('#call_order').val();
var htmlstring = '<tr>'
htmlstring = htmlstring + '<td><input type="button" value="Remove" class="removeruleset"/></td>'
htmlstring = htmlstring + '<td>' + contact_type + '</td>'
htmlstring = htmlstring + '<td>' + email_address + '</td>'
htmlstring = htmlstring + '<td>' + call_order + '</td>'
htmlstring = htmlstring + '</tr>'
$('#rule_summary tr:last').after(htmlstring);
});
Then, I've got some more jquery to handle the .click event for the remove button:
$(".removeruleset").click(function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
The code to add a row to my table, along with the remove button works. But when I click on one of the remove buttons, it doesn't trigger the click event.
As a test, I created a button like so, outside of jquery:
<input type="button" class="removeruleset" value="push me">
and it triggers the click event no problem.
Can you tell me where I'm going wrong?
Thank you.
EDIT 1
I've tried changing the code to look like this:
$(document).on("click", ".removeruleset", function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
But that gives me the following error :
SCRIPT438: Object doesn't support property or method 'on'
I'm using version 1.5.2.
So, I referred to the article that's mentioned in some of the comments (Event binding on dynamically created elements?) and tried this instead:
$("body").delegate("click", ".removeruleset", function(e){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
That got rid of the error message but the event handler is still not triggered
Also tried:
$("body").on("click", ".removeruleset", function(e){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
Thanks.
Try this:-
$(document).on("click", ".removeruleset", function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
When you added the event to the element it was not existing. To make this work you need to use event delegation.
hi another way is to do this htmlstring = htmlstring + '<td><input type="button" value="Remove" class="removeruleset"click=\"myhandler\"/></td>'
where myhandler is a function
function myhandler(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
}
you can try this for dynamic control.
$('#id').live('click', function() {
----your code--
})
else you can try this:
>>>$(document).on('click','#id', function() {
-----your code ---
})
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);