Create bootstrap-modal from string in javascript - javascript

I have the following code (which is the HTML from the example):
var modal=
'<div class="modal fade" id="infoModal"'+id+'tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'
+'<div class="modal-dialog">'
+'<div class="modal-content">'
+'<div class="modal-header">'
+'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'
+'<h4 class="modal-title">Modal title</h4>'
+'</div>'
+'<div class="modal-body">'
+'<p>One fine body…</p>'
+'</div>'
+'<div class="modal-footer">'
+'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
+'<button type="button" class="btn btn-primary">Save changes</button>'
+'</div>'
+'</div>'
+'</div>'
+'</div>';
document.body.appendChild(modal);
And I get the error:
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The
new child element is null.
If I put the same HTML inside my index.html it works just fine. What's the problem here?

modal is not an element. It is just a string. appendChild expects an actual element reference, not just a string.
While I don't suggest it, you could do
document.body.innerHTML = document.body.innerHTML+modal;
This is lame and will remove your event listeners from anything in the body.
You could also do something like:
var div = document.createElement('div');
div.innerHTML = modal;
document.body.appendChild(div);
Live demo (click).
If I had that amount of markup in string form, I would just put it in an html file and either include it from the server or load it with javascript via ajax.
You could also create the whole structure using document.createElement for each piece.

Related

How to pass a json string as parameter in javascript?

I have received a json string like this:
The Api response as following list:
[
{
"id": "1018491557",
"results": "{\"combo\":\"3,4,13,14\"}",
"time": "2020-07-13T16:11:03.082Z",
"modifiedTime": "0001-01-01T00:00:00",
"status": "SUCCESS"
},...
]
Then I mockup html like this and I need to open the modal to show single details:
var res =
'<a href="#" onclick="openDetails(\''+value.id+'\', \''+value.results+'\', \''+value.time+'\', \''+value.modifiedTime+'\')">';
$(".list").append(res);
But I just cant get the right format of RESULTS to display.
function openDetails($id, $res, $time, $modTime){
$("#DetailsModal").remove();
var modal =
'<div id="DetailsModal" class="modal fade" tabindex="-1" role="dialog">'+
'<div class="modal-dialog" role="document">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<h5 class="modal-title">Details</h5>'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">'+
'<span aria-hidden="true">×</span>'+
'</button>'+
'</div>'+
'<div class="modal-body">'+
'<p>ID: '+$id+'</p>'+
'<p>Sesults: '+$res+'</p>'+
'<p>Time: '+$time+'</p>'+
'</div>'+
'<div class="modal-footer">'+
'<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
$("body").append(modal);
$("#DetailsModal").modal({
backdrop:"static",
keyboard:false,
show:true
});
}
Anyone can point me out here? Thanks
solved!
Okay~ it turns out no need to quote the string again. problem solved by replacing the double quotes to single.
<a href="#" onclick="openDetails(\''+value.id+'\', '+value.results.replace(/"/g, "'")+', \''+value.time+'\', \''+value.modifiedTime+'\')">
I don't know exactly what your code is, but if you get a json string you have to use JSON.parse() to transform it into a JavaScript object.
var result = JSON.parse('{"combo":"3,4,13,14"}');
...
<a href="#" onclick="openDetails(result)">

Append Html Using Javascript or Jquery

I'm trying to make a multi-page modal like this one (last button): https://www.ngzhian.com/multi-step-modal/
but I'm getting only this html when I run the script. What am I missing here?? I dont get any error.
var testCaseNames = ['test', 'test2'];
//Modal
var testCaseNames = ['test', 'test2'];
//Modal
var modal = '<form class="modal multi-step" id="creationModal"><div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
//Progress
modal += '<div class="m-progress"><div class="m-progress-bar-wrapper"><div class="m-progress-bar"></div><div class="m-progress-stats"><span class="m-progress-current"></span>/<span class="m-progress-total"></span></div><div class="m-progress-complete">Completed</div></div>';
$.each(testCaseNames, function(key, value) {
//Headers
$('.modal-header').html('<h4 class="modal-title step-' + key + ' data-step="' + key + '"</h4>');
//Body
modal += '<div class="modal-body step-' + key + '" data-step="' + key + '">' + value + '</div>';
// //Footer Buttons
modal += '<div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div>';
modal += '</div></div></form>';
});
$('#modalDiv').empty().html(modal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modalDiv">
<form class="modal multi-step in" id="creationModal" style="display: block; padding-right: 17px;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title step-0" data-step="0"> </h4></div>
</div>
</div>
</form>
</div>
Errors occur when changing the innerHTML of elements many times at the same function. Try calling .html() once, like you did at this line $('#modalDiv').empty().html(modal);
Instead of this line $('.modal-header').html('...');, keep adding html text in the modal variable.

$.post in jquery is not working?

My $.post is not working as I am trying to extract JSON data from my PHP file, I don't know the reason why it's not showing the output?
Here's my code.
HTML:
<pre id="love" type="submit" data-toggle="modal" data-target="#myModal" onclick="mymodal(\''+this["id"]+'\')">'+this["love"]+' students <i class="glyphicon glyphicon-heart fa-lg" style="color:red"></i></pre >
where this["id"] has been passed to mymodal() function.
javascript code:
var list='';
function mymodal(id){
$.post('postname_.php',{post_id:id},function(data1){
$.each(data1.result,function(){
list+='<div class="modal fade" id="myModal" role="dialog">'+'<div class="modal-dialog">'+'<div class="modal-content">'+
'<div class="modal-header">'+'<button type="button" class="close" data-dismiss="modal">×</button>'+
'<h4 class="modal-title">Students who loved your post</h4>'+' </div>'+'<div class="modal-body">';
list+='<h4 class="text-danger">'+this["finame"]+' '+this['sename']+'</h4>';
list+='</div>'+'<div class="modal-footer">'+
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'+'</div>'+
'</div>'+'</div>'+'</div>';
$('#insert').append(list);}),'json'
});
}
my php code:
<?php
require("../vendor/library50-php-5/CS50/CS50.php");
CS50::init(__DIR__ . "/../config.json");
$result=array();
$frows3=CS50::query("SELECT * FROM userhit WHERE plove=? AND bypost=?",1,$_POST['post_id']);
foreach($frows3 as $frow3){
$frow4=CS50::query("SELECT * FROM userinfopersonal WHERE user_id=? ",$frow3['user_id']);
$frow5=CS50::query("SELECT * FROM userprof WHERE user_id=? ",$frow3['user_id']);
array_push($result,array('finame'=>$frow4[0]['firstname'],'sename'=>$frow4[0]['secondname'],'url1'=>$frow5[0]['url']));
}echo json_encode(array('result'=> $result)); ?>
where CS50::query provides me all my rows of table which satisfy the given query, no worry about that, I checked that's giving perfect json file. The main problem is the alert in function mymodal() is working that means on clicking pre tag it's coming inside function, but the alert inside $.post is not executed.
It looks like your 'json' argument for $.post() function is not within the correct function scope. See the updated code below (I took the liberty of removing the excess string concatenation – I may be wrong, but it didn't appear to have utility). Proper spacing can help to catch these syntax errors.
var list='';
function mymodal (id) {
$.post('postname_.php', {post_id: id}, function (data) {
$.each(data.results, function (i, result) {
list+='<div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">×</button><h4 class="modal-title">Students who loved your post</h4></div><div class="modal-body">';
list+='<h4 class="text-danger">' + result["finame"] + ' ' + result['sename'] + '</h4>';
list+='</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>';
$('#insert').append(list);
});
}, 'json');
}
To see the difference, here is the original code tabbed in a more conventional manner.
var list='';
function mymodal(id){
$.post('postname_.php',{post_id:id},function(data1){
$.each(data1.result,function(){
list+='<div class="modal fade" id="myModal" role="dialog">'+'<div class="modal-dialog">'+'<div class="modal-content">'+
'<div class="modal-header">'+'<button type="button" class="close" data-dismiss="modal">×</button>'+
'<h4 class="modal-title">Students who loved your post</h4>'+' </div>'+'<div class="modal-body">';
list+='<h4 class="text-danger">'+this["finame"]+' '+this['sename']+'</h4>';
list+='</div>'+'<div class="modal-footer">'+
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'+'</div>'+
'</div>'+'</div>'+'</div>';
$('#insert').append(list);
}),'json'
});
}
Your JavaScript code is correct (Please format the code before asking for help in online forums).
https://jsfiddle.net/s295zzmt/
Your HTML code looks in correct, probably because it was copy pasted from within JavaScript code. But since you said that alert inside mymodal function is working correctly, lets ignore it.
There are two possibilities.
The HTTP request is failing
It is returning invalid JSON
Check network tab in Firefox Developer Tools / Chrome Developer Console. Make sure that the XHR request is returning 200 OK. If so, check the HTTP response and ensure that it is valid JSON.

Populating string with dynamic data

I have the following line of code inside me JS:
'<a class="txt333 clps" data-toggle="collapse" aria-expanded="false" '+
'href="#collapse_reqConf'+sent+'" '+
'aria-controls="collapse'+sent+'" '+
'data-parent="#accordion_reqConf'+sent+'">'
Which populates var sent and produces the following results (from source view):
<a class="txt333 clps" data-parent="#accordion_reqConf137" aria-controls="collapse137" href="#collapse_reqConf'+sent+'" aria-expanded="false" data-toggle="collapse">
I cannot figure out why the one within href attribute is not being inserted properly...
UPDATE: WORKING ANSWER IN MY LAST COMMENT.
Since you're using jQuery anyways, you try something like the following to create DOM elements using jQuery. Personally, I feel that creating elements using strings of HTML is error-prone, makes the code hard to read and debug. I create the <a></a> element that you are having an issue with using jQuery and append its containing elements using elements created from string.
var inner = '<div class="row">'+
'<div class="col-xs-9 col-sm-8">'+
'<table class="w100p text-success b">'+
'<tr>'+
'<td width="50%" class="nowrap pad10rt">'+ '<i class="fa fa-clock-o fa-lg valignMid xtraSm"></i> 4:00 pm'+'</td>'+
'<td width="50%"><i class="fa fa-user fa-lg valignMid xtraSm"></i> x '+part+'</td>'+
'</tr>'+
'</table>'+
'</div>'+
'<div class="col-xs-3 col-sm-4 text-right">'+
'<i class="indicator fa fa-fw fa-chevron-right"></i>'+
'</div>'+
'</div>';
var attribs = {
"class": "txt333 clps",
"data-toggle": "collapse",
"aria-expanded": false,
"href": "#collapse_reqConf" + sent,
"aria-controls": "collapse" + sent,
"data-parent": "#accordion_reqConf" + sent
};
var elStr = $('<a>').attr(attribs).append($(inner)).prop('outerHTML');
console.log(elStr);

How to get ID of Button(onClick) which is created dynamically in javascript

How to get ID of button which is created by using following JS. I want to set Button's ID on
as label's text.
function addnewsubj(){
var a = $("#subjname").val();
if(a!=="" ){
$('.techsubj').append(
'<div class="row sub'+ a +'" id="sub'+ a +'">'+
'<div class="col-xs-6 col-md-4">'+
'<a href="#fourth" id="'+ a +'" class="btn btn-info" >'+ a +'</a>'+
'</div>'+
'<div class="col-xs-12 col-sm-6 col-md-8">'+
'<div class="progress">'+
'<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">'+
'<span class="sr-only">60% Complete (warning)</span>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'
);
}
else{
alert("Text Box is empty");
}}
HTML
<label id="subjTitle"> </label>
You don't have a button anywhere. If you mean the anchor element that is styled as a button,
$('subjTitle').text($('.techsubj .btn').attr('id'))
Or, you could always explicitly create it with an ID, or best of all you could create the content as a DOM hierarchy instead of as a HTML source and just keep the reference to the "button" object around.
use jquery 'on' method for dynamic event. use this code:
$(document).on('click','.btn-info', function(){
$('#subjTitle').text($(this).attr('id'));
});
if you are using jquery below version 1.7 than you may use "live" or "delegate" for dynamic element.
Here is a little Example:
HTML :
<div id='th'></div>
Jquery:
$('#th').append('<div id="rock">this is Dynamo</div>');
alert($($('#th').children('div')[0]).attr('id'));
may it helps you!

Categories

Resources