Is there a simpler way to set modal-body text by classname - javascript

I am using Bootstrap 5.1.3 with Pure Vanilla JavaScript and I am able to set the .modal-body content using below:
function showBSModal(modalid, inputid) {
var myModal = new bootstrap.Modal(document.getElementById(modalid), {});
var theValue = document.getElementById(inputid).value;
const parent = document.getElementById(modalid);
parent.querySelector(".modal-body").innerHTML = "Successfully Delete Uesr with ID: " + theValue;
myModal.show();
};
Here I am passing modalid and my input box's id (inputid) dynamically and getting the desired output.
I tried myModal.querySelector instead of parent.querySelector but that did not work as myModal.querySelector is not accepted by the browser.
Question: Any there a better say to achieve above?

myModal is a modal object and not an HTML element. Let's load the HTML element, store it in a variable and use that instead.
function showBSModal(modalid, inputid) {
let context = document.getElementById(modalid);
var myModal = new bootstrap.Modal(context, {});
var theValue = document.getElementById(inputid).value;
context.querySelector(".modal-body").innerHTML = "Successfully Delete Uesr with ID: " + theValue;
myModal.show();
};

Related

Why isn't my function related to an onclick workin?

I'm studding HTML, CSS and JS and while I was creating an exercise, I was forced to stop due to an error. I created an button dynamically, setted an onclick to it and then created a function with that onclick. The problem is that the function isn't working, at leats it doesn't made anything till now.
let formularys = document.querySelector('section#formulary')
let slct = document.createElement('select')
let opts = document.createElement('option')
let optp = document.createElement('option')
let fbtn = document.querySelector('input#formularybtn')
let nbtn = document.createElement('input')
let br = document.createElement('br')
slct.id = 'pors'
slct.size = '2'
opts.value = 'rsite'
opts.innerHTML = 'Rate site'
optp.value = 'rp'
optp.innerHTML = 'Rate products'
nbtn.setAttribute('type', 'button')
nbtn.setAttribute('value', 'Next')
nbtn.setAttribute('onclick', 'nbutton')
function nbutton(){
console.log('Next working')
/*if(slct.selectedIndex == 1){
console.log('Valid rate choose')
}*/`enter code here`
}
instead of using setAttribute you can just do
nbtn.onclick = nbutton
in javascript, onclick isn't a string but a function.
The problem is, you are not appending your html code generated from JavaScript to DOM. You can either append to main DOM like below
document.body.appendChild(nbtn);
document.body.appendChild(optp);
or you can append them to some parent div by first getting div id
document.getElementById("divId").appendChild(nbtn);
where divId is id of your div where you want to add this html.
Also you should assign event listener in correct way as suggested by Tony and Rashed Rahat.
Try:
element.onclick = function() { alert('onclick requested'); };

Anchor dynamic element with click event

I am trying to dynamically add an anchor element through Javascript. The problem I have is the onclick event is not firing. I believe the problem is how I am generating the HTML. I am creating an array and then push my HTML code to the array. After I have created my output I am joining the array and then adding it to the div tag I have.
var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
//do something specific with rowItem variable
alert(rowItem);
}
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
<div id="mainViewer"></div>
When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.
Any ideas?
I will have multiple anchor links and I don't want to hardcode the function name. I want the onclick event to fire whatever function the itemLink Object has set.
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.
So, what is the solution? to push a DOM element instead of string, something like this:
//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}
var itemLink = {
LinkName: "Edit User",
LinkListClass: "",
LinkListRole: "",
LinkFunction: function() {
//do something specific with rowItem variable
alert(rowItem);
}
};
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)
<div id="mainViewer"></div>
Thanks to #David Thomas for his comment :)

create id dynamically

I am creating a element dynamically how would i give this an id?
_addQuestionElement : function() {
var el = new Element('div');
el.addClass('dg-question-label');
el.set('html', this._getCurrentQuestion().label);
$(this.html.el).adopt(el);
},
im using moo tools and jquery.
Many Thanks
Your code looks like Mootools, here's how I'd do it (cleaned up your code a bit)
_addQuestionElement: function() {
var el = new Element('div', {
'class': 'dg-question-label',
html: this._getCurrentQuestion().label,
id: 'yourId'
});
$(this.html.el).adopt(el);
}
If you're generating the same element multiple times, your id will need to somehow be unique each time.
You could also do without that el variable (unless of course it's used somewhere further in the function that you didn't include)
_addQuestionElement: function() {
$(this.html.el).adopt(new Element('div', {
'class': 'dg-question-label',
html: this._getCurrentQuestion().label,
id: 'yourId'
}));
}​
Just assign the id via (if you created the element with new Element()):
var yourCustomId = "myId";
el.id = yourCustomId;
Or use Mootools attr-setting capabilities:
var yourCustomId = "myId";
el.setProperty("id", yourCustomId);
You can give it like this,
var uniqueNumber = 1; //define uniqueNumber globally and increament at each element creation
With javascript
el.id = 'idprefix' + uniqueNumber++)
With jQuery
$(el).attr('id','idprefix' + uniqueNumber++);
In jQuery, to create a div with an ID, you would do something like this:
function createDiv(id) {
$("body").append("<div id=" + id + "></div>");
}
createDiv("myNewDivId");
_addQuestionElement, I think you need to generate a unique id for each question element.
var IDs = 0;
var pfx = "id_";
_addQuestionElement : function() {
...
el.attr("id", pfx + ++IDs);
var el = $('<div />') .attr('id', myVal);
all elements created or accessed by MooTools automatically get a unique uid (for the DOM) anyway, saves you from having to keep state yourself (if you want to be doing this automatically).
console.log( Slick.uidOf( new Element('div') ) )
so...
_addQuestionElement: function() {
var el = new Element('div.dg-question-label', {
html: this._getCurrentQuestion().label
});
// prefix number with uid-
el.set('id', 'uid' + Slick.uidOf(el)).inject(this.html.el);
},
to give it an id via the combined element constructor, it goes:
var el = new Element('div#someid.dg-question-label') or add it in the properties passed to the constructor:
new Element('div', { id: 'foo' })
You can use the jQuery plugin idfy.
Full Disclosure: I wrote that plugin :)

Getting HTML value from Tinymce

Is there a way to get HTML contents from TinyMCE editor using jQuery so I can copy this over to another div?
I tried several methods like val() on content but it doesn't seem to be working...
if you are initilizing with jquery adaptor
$(selector).tinyMCE().getContent();
Using jQuery:
<textarea id="content" name="content">
$('#content').html()
Using TinyMce API:
$('#content').tinymce().activeEditor.getContent() // overall html
$('#content').tinymce().activeEditor.getContent({format : 'text'}) // overall text
$('#content').tinymce().selection.getContent() // selected html
$('#content').tinymce().selection.getContent({format : 'text'})) // selected text
if you are using tinymce, i would use it's internal methods to get the content you need. when i need to get content within the active editor, i do this:
var rawString = tinyMCE.activeEditor.getContent();
i invoke that method within an event handler function.
here is the documentation:
tinymce api
use TinyMCE's API to get it:
alert(tinyMCE.activeEditor.getContent());
Use text(); instead of val();.
I was trying charlietfl method: $(selector).tinyMCE().getContent();
There was an error:
[$(selector).tinyMCE().getContent();][1]
This way with activeEditor worked for me:
activeEditor
tinymce.activeEditor.getContent()
Source
Here is my code:
$(document).ready(function() {
$(document).on("click", ".btnClassClose", function () {
var tinyMCEcontent = tinymce.activeEditor.getContent();
var getAttrIDArray = [];
$("#" + getelementId).html("");
$("#" + getelementId).html(tinyMCEcontent);
$("#" + getelementId).append(buttonEDI);
var PageName = new Object();
PageName["mdlPageId"] = getelementId;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageContentHtml"] = tinyMCEcontent;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageName"] = "Default";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlAligen"] = "Central";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlOrderNumberHorizontal"] = "1";
getAttrIDArray.push(PageName);
alert(JSON.stringify(getAttrIDArray));
var contentGetAttrIDArray = SecondMainSendAjax("CMS?handler=Content", getAttrIDArray);
});
});

obj is null, javascript

function init()
{
alert("init()");
/**
* Adds an event listener to onclick event on the start button.
*/
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
});
ok so what I have here is a event listerner function, the case is when viewInvitation is clicked , the program will fetch my xml file and run page master function where I created my decline button with id="declinebutton", however this does not work, the error message that i get is obj=null or the program could not find id = declinebutton, why is it so? I have created it when I called page master using dom. any help will be appreciated.
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
var subjectList;
var i;
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table=document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
var input=document.createElement("p");
var inputText=document.createTextNode("You are invited to join " + groupName + "(groupId : " + groupId +")");
input.className="style11";
var blank=document.createElement("nbps");
input.appendChild(inputText);
var acceptButton=document.createElement("input");
acceptButton.type="button";
acceptButton.id="acceptbutton";
acceptButton.value="accept";
var declineButton=document.createElement("input");
declineButton.type="button";
declineButton.id="declinebutton";
declineButton.value="decline";
table.appendChild(input);
table.appendChild(acceptButton);
table.appendChild(declineButton);
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
/**function getValueOf()
{
return i;
}**/
function declineInvitation()
{
alert("decline");
}
function acceptInvitation()
{
alert("hello");
/**var pos=getValueOf();
alert(subjectList[pos].attributes[0].nodeValue);**/
}
That's my page master function, and I definitely have created the button. but it does not work.
Try calling your function like this:
window.onload=init;
The javascript runs as the page loads. At that point, the element does not yet exist in the DOM tree. You'll need to delay the script until the page has loaded.
The example you gave doesn't create the "Decline" button, as your question suggests it should. If it should, you might want to look at that.
Of course, if the button already exists, please disregard this answer.
You have a listener inside a listener. Is that right?
What about this?:
function init(){
alert("init()");
/** * Adds an event listener to onclick event on the start button. */
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
}
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
As far as I understand, you create button with id="declinebutton" for each entry from xml, is that right?
If yes, I'd suggest you to generate different id's for each button (for example, append line index to 'declinebutton', so you have buttons 'declinebutton0', 'declinebutton1' an so on), and assign event listener to buttons separately in the loop.

Categories