Django Forbidden (CSRF token missing.) - html

I am facing a problem to submit a text in Django. When I click Insert, the message Forbidden (CSRF token missing.): appears. Can somebody help me?
Normally the csrf token is supposed to work.
I put the CSRF token in the html file, but still no working. I do not know if the csrf is in the wrong part of the code or not.
> <form method="POST" enctype="multipart/form-data">
> {% csrf_token %}
> <div class="modal-dialog modal-md">
> </form>
> <div class="modal-content" hx-target="this" hx-swap="outerHTML" id="this">
> {% load crispy_forms_tags %}
>
> <!-- Modal Header -->
> <div class="modal-header">
> <h4 class="modal-title">Show gabarit</h4>
> <button type="button" class="close" data dismiss="modal">×</button>
> </div>
>
> <!-- Modal body -->
> <div class="modal-body">
> <pre style="font-size: 12px"><textarea id='input-text' name='input-text' style='height:100px; width: 800px;'>{{commande}}</textarea></pre>
>
> if formset %}
> <button class="mb-2 btn btn-outline-secondary mr-2"
> id="variables-button" type="button" onclick="openModal()">Variables</button>
> endif %}
>
>
> <div id="modal" style="display:none;">
> <div id="variables-container"></div>
> <button class="mb-2 btn btn-outline-secondary mr-2"
> id="insert-button" type="button" onclick="closeModal()">Insérer</button>
> </div>
> </form>
>
> <div id='result'></div>
>
> </div>
>
>
> </div>
>
> </div>
>
>
> <script>
> function openModal() {
> var inputText = document.getElementById("input-text").value;
> var variableNames = inputText.match(/{(.*?)}/g);
> var variablesContainer = document.getElementById("variables-container");
> variablesContainer.innerHTML = "";
> for (var i = 0; i < variableNames.length; i++) {
> var variableName = variableNames[i].slice(1, -1);
> variablesContainer.innerHTML += "<div><label for='variable-" + variableName + "'>" + variableName + ":</label><input type='text' id='variable-" + variableName + "' name='variable-" + variableName + "'></div>";
> }
> document.getElementById("modal").style.display = "block";
> }
>
> function closeModal() {
> var inputText = document.getElementById("input-text").value;
> var variableNames = inputText.match(/{(.*?)}/g);
> for (var i = 0; i < variableNames.length; i++) {
> var variableName = variableNames[i].slice(1, -1);
> var variableValue = document.getElementById("variable-"+ variableName).value;
> inputText = inputText.replace(variableNames[i], variableValue);
> }
> document.getElementById("input-text").value = inputText;
> document.getElementById("modal").style.display = "none";
> document.getElementById("variables-button").style.display = "none";
>
> var xhr = new XMLHttpRequest();
> xhr.open("POST", "{% url 'gabarits:save-variables-text' %}", true);
> xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
> xhr.onreadystatechange = function() {
> if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
> console.log("Input text saved successfully.");
> }
>
> };
> xhr.send("text=" + inputText);
> }
> </script>
On the view side:
def save_variables_text(request):
if request.method == 'POST':
text = request.POST.get('text')
InputText.objects.create(text=text)
return render(request, 'previsualise.html')

Related

div style display:inline-block doesn't work when printing. When I removed, it prints the first page blank

.gunlukProgramCerceve {
width: 100%;
height: auto;
/*display: inline-block;*/
border-bottom: 1px dashed #0274bd;
padding: 0.2%;
margin-top: 2px;
margin-bottom: 3px;
}
<tr class="gosterme islem #(item.isSaatBelirsiz? "saatbelirsizelem" : " saatbellielem nosort")">
<td colspan="2">
<input type="hidden" name="ID" value="#item.ID" />
<input type="hidden" name="SiralamaTarih" value="#(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />
<table class="ictablo" width="100%" style="text-align:left;border-bottom: 0px; vertical-align:top;">
<tr class="#renkClass prgOzet" data-link="#Url.Action("ProgramOzetTooltip", "Program", new { ID = item.ID, area = "yonetim", TurID = item.TurID,Tarih=item.Tarih.Value.ToString("dd.MM.yyyy HH:mm") })">
<td colspan="2">
<div style=" ">
<div class="gunlukProgramCerceve">
<div class="gunlukProgramBaslik">
<span class="saatYazi" style="font-weight:bold;">
#if (item.isSaatBelirsiz)
{
#("../..")
}
else
{
#item.Tarih.Value.ToString("HH:mm")
}
</span>
It doesn't print when display:inline-block is in div style. It gives an error loading preview. When I remove it, the first page is blank. Actually, the first page is blank when there is a lot of data(picture 1). It works fine when there is little data(picture 2).
All code:
<tbody class="SaatBelli sortelem" style="display:#(Model.Liste.Any(d =>d.DurumID!=prgSablonID&& ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz||(d.isSaatBelirsiz&&(d.SiralamaTarih!=null&&d.SiralamaTarih <= SBSiralamaTarih))))))?"":"none")">
#foreach (var item in Model.Liste.Where(d => d.DurumID != prgSablonID && ((d.Sure != Sabitler.PrgTumGun && (!d.isSaatBelirsiz || (d.isSaatBelirsiz && (d.SiralamaTarih != null && d.SiralamaTarih <= SBSiralamaTarih)))))).OrderBy(d => d.SiralamaTarih))
{
string renkClass = "";
if (item.TurID == (int)Sabitler.ZiyaretTur.Program)
{
renkClass = item.DurumID == prgGerceklestiID ? "kayitGray" : (item.DurumID == prgIptalID || item.DurumID == prgGerceklesmediID) ? "kayitRed" : "";
}
else if (item.TurID == (int)Sabitler.ZiyaretTur.Arz)
{
renkClass = item.DurumID == ArzEdildiID ? "kayitGray" : (item.DurumID == ArzEdilemediID || item.DurumID == ArzIptalID) ? "kayitRed" : "";
}
else if (item.TurID == (int)Sabitler.ZiyaretTur.Bilgi)
{
renkClass = item.DurumID == BilgiGerceklestiDurumID ? "kayitGray" : (item.DurumID == BilgiGerceklesmediDurumID) ? "kayitRed" : "";
}
string KayitTurYazi = Fonksiyonlar.ProgramKayitTurYaziVer(item.TurID, item.DurumID);
<tr class="gosterme islem #(item.isSaatBelirsiz? "saatbelirsizelem" : " saatbellielem nosort")">
<td colspan="2">
<input type="hidden" name="ID" value="#item.ID" />
<input type="hidden" name="SiralamaTarih" value="#(item.SiralamaTarih==null?item.Tarih:item.SiralamaTarih)" />
<table class="ictablo" width="100%" style="text-align:left;border-bottom: 0px; vertical-align:top;">
<tr class="#renkClass prgOzet" data-link="#Url.Action("ProgramOzetTooltip", "Program", new { ID = item.ID, area = "yonetim", TurID = item.TurID,Tarih=item.Tarih.Value.ToString("dd.MM.yyyy HH:mm") })">
<td colspan="2">
<div style=" ">
<div class="gunlukProgramCerceve">
<div class="gunlukProgramBaslik">
<span class="saatYazi" style="font-weight:bold;">
#if (item.isSaatBelirsiz)
{
#("../..")
}
else
{
#item.Tarih.Value.ToString("HH:mm")
}
</span>
#if (item.Sure != 0)
{
<br /><span class="programsurec saatYazi">#(item.Sure == Sabitler.ProgramSuresiBelirsiz ? " Süre belirsiz " : Fonksiyonlar.ToplantiSureCevir(item.Sure))</span>
}
#if (item.TurID != (int)Sabitler.ZiyaretTur.Program)
{
<br /><span class="programdurum saatYazi #(item.TurID == (int)Sabitler.ZiyaretTur.Arz ? "programArzBg" : "programZiyaretciBg")">
#(KayitTurYazi)
#if (DvtKesinDegilDurumID == item.DurumID)
{
<span class="davetKatilimKesinDegil tooltips" data-original-title="Katılım Kesin Değil"> ? </span>
}
</span>
}
else if (item.TurID == (int)Sabitler.ZiyaretTur.Program && isTaslakprgVar && item.KategoriID == TaslakPrgKategori.ID)
{ <br />
<span class="programdurum saatYazi programArzBg">
Taslak
</span>
}
</div>
<div class="gunlukProgramDetay">
<span class="icerikBolum" style="display:block;">
#if ((item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret || item.isRandevuAciklama))
{
#Html.Raw(item.Aciklama)
}
#if (Model.Filtre.EkstraNot && !string.IsNullOrEmpty(item.EkstraNot))
{
<span style="color:red">#item.EkstraNot</span>
}
</span>
#if (!string.IsNullOrEmpty(item.PrgNotu) && item.TurID != (int)Sabitler.ZiyaretTur.Ziyaret && Model.Filtre.PrgNot)
{
<span class="katilimcilarNot icerikBolum"> #(Html.Raw(item.PrgNotu))</span>
}
#if (string.IsNullOrEmpty(item.Aciklama) && item.TurID != (int)Sabitler.ZiyaretTur.Program && item.katilimcilar.Any() && !Model.Filtre.Katilimci)
{
YeniKisiModel katilimci = item.katilimcilar.FirstOrDefault();
if (katilimci != null)
{
<b>#(KayitTurYazi + " :" + katilimci.AdSoyad )</b>
<span class="icerikBolum" style="font-size:#(Model.Filtre.yazi)px;"> #(katilimci.Aciklama)</span>
}
}
#if (item.katilimcilar.Any() && ((Model.Filtre.Katilimci && (item.TurID != (int)Sabitler.ZiyaretTur.Davetiye))))
{
bool isFirst = false;
<br />
foreach (var jitem in item.katilimcilar)
{
#(Html.Raw(isFirst ? "<br />" : ""))
<div class="katilimcilar icerikBolum">
#(jitem.AdSoyad)
</div>
if (!string.IsNullOrEmpty(jitem.Aciklama))
{
<span class="icerikBolum" style="font-size:#(Model.Filtre.yazi)px;"> #(jitem.Aciklama)</span>
}
if (!isFirst)
{
isFirst = true;
}
}
}
</div>
</div>
</div>
</td>
</tr>
</table>
#if (Fonksiyonlar.YetkiKontrol("Program Ekle##") && isPrgGosterim && !Model.Filtre.isDisardan &&
(!isKisitli ||
(isKisitli &&
((GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGecmis && Trh.Date >= BugunBas) ||
(GunSinir == (int)Sabitler.ProgramGunSinir.SadeceGelecek && Trh.Date <= BugunSon) ||
(GunSinir >= 0 && (Trh.Date >= SinirBasTarih && Trh.Date < SinirBitTarih))))))
{
<div class="yeniekle hidden-print" onclick="YeniProgramModal(0,'#string.Format("{0:00}", item.Tarih.Value.Hour):00','#(Trh.ToString("dd-MM-yyyy"))');"><span><i class="fa fa-plus"></i> yeni ekle</span></div>
}
<div class="hidden-print bg-gosterme">
<label class="font-xs" for="gosterme"> Yazıcıda Gösterme <input type="checkbox" id="gosterme" class="yazicidagosterme" /></label>
</div>
</td>
</tr>
}
</tbody>

Create a table in jQuery with crud operations and data save in local storage

I tried to create a table in jQuery with Create, Update, Edit and Delate row functions. I need to save the data in local storage. The table must have a column wise filter and sorting.
When I run the application the table header and first row should be displayed. The first row includes some sample data. What are the changes I need to make?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="container">
<div class="form-row">
<div class="col-md-3">
<label>Name <span class="errdiv"> *</span></label>
<input id="txtName" type="text" class="form-control txt txtName" placeholder="Enter Name" required>
<input id="txtId" type="hidden" class="form-control txt">
</div>
<div class="col-md-3 col-sm-6 col-6">
<label>Contact No <span class="errdiv"> *</span></label>
<input id="txtContact" data-type="number" type="text" minlength="10" maxlength="10" class="form-control txt txtContact" placeholder="Contact No" required>
</div>
<div class="col-md-3 col-sm-6 col-6">
<label>Alt Contact No</label>
<input id="txtAltNo" type="text" class="form-control txt txtAltNo" minlength="10" maxlength="10" placeholder="Alt Contact No">
</div>
</div>
<div class="form-row">
<div class="col-md-6 col-sm-7">
<label>Address <span class="errdiv"> *</span></label>
<textarea id="txtAddress" class="form-control txt txtAddress" rows="3" minlength="15" placeholder="Enter Address" required></textarea>
</div>
</div>
<div class="row pt-2">
<div class="col-md-2">
<button type="button" class="btn btn-success" id="btnSave">Save</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-secondary" id="btnClear">Clear</button>
</div>
</div>
<div class="row pt-3">
<div class="col-md-12 col-sm-12 col-12 p-2 ">
<table id="tblData" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th> Name</th>
<th>Phone</th>
<th>Alt Phone</th>
<th>Address</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
var emptyRow = "<tr><td colspan='6' class='text-center'> No Records Available</td></tr>";
$(document).ready(function() {
loadDataFromLocal();
$('#tblData').on('click', '.btn-edit', function() {
debugger;
const name = $(this).parent().parent().find(".txtName").html();
const contact = $(this).parent().parent().find(".txtContact").html();
const altContact = $(this).parent().parent().find(".txtAltNo").html();
const address = $(this).parent().parent().find(".txtAddress").html();
const id = $(this).parent().parent().find(".txtName").attr("data-id");
$("#txtName").val(name);
$("#txtContact").val(contact);
$("#txtAltNo").val(altContact);
$("#txtAddress").val(address);
$("#txtId").val(id);
$("#btnSave").text("Update");
});
$('#tblData').on('click', '.btn-delete', function() {
debugger;
const id = $(this).parent().parent().find(".txtName").attr("data-id");
deleteDataFromLocal(id);
});
$("#btnSave").click(function() {
debugger;
if ($("#txtId").val() == '') {
addDataToLocal();
} else {
updateDataFromLocal();
}
});
$("#btnClear").click(function() {
debugger;
clearForm();
});
});
function clearForm() {
debugger;
$("#txtName").val("");
$("#txtContact").val("");
$("#txtAltNo").val("");
$("#txtAddress").val("");
$("#btnSave").text("Add");
}
function addEmptyRow() {
debugger;
if ($("#tblData tbody").children().children().length == 0) {
$("#tblData tbody").append(emptyRow);
}
}
function loadDataFromLocal() {
debugger;
let localData = localStorage.getItem('localData');
if (localData) {
$("#tblData tbody").html("");
let localArray = JSON.parse(localData);
let index = 1;
localArray.forEach(element => {
let dynamicTR = "<tr>";
dynamicTR = dynamicTR + "<td> " + index + "</td>";
dynamicTR = dynamicTR + "<td class='txtName' data-id=" + element.id + ">" + element.name + "</td>";
dynamicTR = dynamicTR + "<td class='txtContact'>" + element.contact + "</td>";
dynamicTR = dynamicTR + "<td class='txtAltNo'>" + element.altContact + "</td>";
dynamicTR = dynamicTR + "<td class='txtAddress'>" + element.address + "</td>";
dynamicTR = dynamicTR + " <td class='tdAction text-center'>";
dynamicTR = dynamicTR + " <button class='btn btn-sm btn-success btn-edit'> Edit</button>";
dynamicTR = dynamicTR + " <button class='btn btn-sm btn-danger btn-delete'> Delete</button>";
dynamicTR = dynamicTR + " </td>";
dynamicTR = dynamicTR + " </tr>";
$("#tblData tbody").append(dynamicTR);
index++;
});
}
addEmptyRow();
}
function addDataToLocal() {
debugger;
let localData = localStorage.getItem('localData');
if (localData) {
let localArray = JSON.parse(localData);
const obj = {
id: localArray.length + 1,
name: $("#txtName").val(),
contact: $("#txtContact").val(),
altContact: $("#txtAltNo").val(),
address: $("#txtAddress").val()
};
localArray.push(obj);
localStorage.setItem('localData', JSON.stringify(localArray));
loadDataFromLocal();
} else {
const arryObj = [];
const obj = {
id: 1,
name: $("#txtName").val(),
contact: $("#txtContact").val(),
altContact: $("#txtAltNo").val(),
address: $("#txtAddress").val()
};
arryObj.push(obj);
localStorage.setItem('localData', JSON.stringify(arryObj));
loadDataFromLocal();
}
clearForm();
}
function updateDataFromLocal() {
debugger;
let localData = localStorage.getItem('localData');
let localArray = JSON.parse(localData);
const oldRecord = localArray.find(m => m.id == $("#txtId").val());
oldRecord.name = $("#txtName").val();
oldRecord.contact = $("#txtContact").val();
oldRecord.altContact = $("#txtAltNo").val();
oldRecord.address = $("#txtAddress").val();
localStorage.setItem('localData', JSON.stringify(localArray));
loadDataFromLocal();
clearForm();
}
function deleteDataFromLocal(id) {
debugger;
let localData = localStorage.getItem('localData');
let localArray = JSON.parse(localData);
let i = 0;
while (i < localArray.length) {
if (localArray[i].id === Number(id)) {
localArray.splice(i, 1);
} else {
++i;
}
}
localStorage.setItem('localData', JSON.stringify(localArray));
loadDataFromLocal();
}

How can validate image dimension and size for 3 target platforms each with different image dimensions but same size in vuejs

I am working on a feature for an image uploader for different platforms with different recommended image dimensions.
For example
platform 1 - dimension 920 x 300
platform 2 -210 x 200
platform 3 - 790 x 270
when the select file button is clicked an image is preview if the image dimensions are not the same as the recommended for a specific platform it should be flagged also the size shouldn't be more that 1mb on all platforms. I am having issue modifying the recommended dimension validation.
this is my code
data() {
return {
isLoading: false,
rules: [
images => !image || !images.some(image => image.size > 2048) || 'Image size should be less than 1 MB!',
],
async selectedFile() {
const MAX_SIZE = 100000;
const MAX_WIDTH = 500;
const MAX_HEIGHT = 300;
this.imageError = '';
let file = this.$refs.myFile.files[0];
if(!file || file.type.indexOf('image/') !== 0) return;
this.image.size = file.size;
if(this.image.size > MAX_SIZE) {
this.imageError = `The image size (${this.image.size}) is too much (max is ${MAX_SIZE}).`;
return;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = evt => {
let img = new Image();
img.onload = () => {
this.image.width = img.width;
this.image.height = img.height;
console.log(this.image);
if(this.image.width > MAX_WIDTH) {
this.imageError = `The image width (${this.image.width}) is too much (max is ${MAX_WIDTH}).`;
return;
}
if(this.image.height > MAX_HEIGHT) {
this.imageError = `The image height (${this.image.height}) is too much (max is ${MAX_HEIGHT}).`;
return;
}
}
img.src = evt.target.result;
}
reader.onerror = evt => {
console.error(evt);
}
},
async onFileChange(e) {
let self = this
this.loadingImage = true
let files = e.target.files || e.dataTransfer.files
if (files && files[0]) {
self.formData.TypeofDocument = files[0].name
.split('.')
.pop()
.toLowerCase()
const file = files[0]
await CMS.uploadImageToCloud(file, fileUrl => {
this.formData.LinkToDocument = fileUrl
this.loadingImage = false
})
}
},
<form #submit.prevent="submit" style="padding: 10px;">
<div class="form-group">
<label for>{{ $t('Platforms') }}</label>
<select class="form-control" v-
model="formData.PlatformTypeID">
<option
v-for="(platform, index) in platformTypes"
:key="index"
:value="platform.ID"
>{{ platform.Name }}</option
>
</select>
</div>
</div>
<div class="form-group">
<label for>{{ $t('Select Image') }}</label>
<div class="row">
<div class="col-md-4 mb-5">
<img
:rules="rules"
accept="image/jpg, image/jpeg,image/png"
v-if="formData.LinkToDocument"
:src="formData.LinkToDocument"
class="img-responsive"
height="100"
/>
<img
src="~/static/img/loading.gif"
height="100"
v-if="!formData.LinkToDocument && loadingImage"
/>
</div>
</div>
<input
type="file"
v-on:change="onFileChange"
id="fileInput"
style="display: none"
/>
<button
type="reset"
class="btn btn-primary"
align="center"
:disabled="loadingImage"
#click="selectFile"
>
{{ $t('Choose File') }}
</button>
</div>
<div class="row marginTop">
<div class="col-6 col-md-6">
<button
v-if="!isLoading"
type="submit"
id="saveBtn"
class="btn btn-success text_white btn-block text-white btn-md btn-responsive"
tabindex="7"
>
{{ $t('Save') }}
</button>
<button
v-if="isLoading"
class="btn disabled btn-success text_white btn-block text-white btn-md btn-responsive"
tabindex="7"
>
<i class="fa fa-spin fa-spinner fa-1x"></i>
</button>
</div>
<div class="col-6 col-md-6">
<router-link
to=""
class= `btn btn-default btn-block btn-md btn-responsive`
>{{ $t('Cancel') }}</router-link
>
</div>
</div>
</form>
enter image description here
I use this code and works :)
<v-img
alt="image"
:src="image_url"
contain
></v-img>

Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick in JQuery and HTML

I am applying JQuery:
HTML
<div id="myNotice" class="container-fluid">
<div style="margin-bottom: 10px;" class="row">
<div class="col-lg-12" >
<button type="button" onclick="myFunction()" class="btn btn-block btn-info">
<i class="fas fa-arrow-right"></i>
<span >Proceed</span>
</button>
</div>
</div>
</div>
<div id="myMSF" class="container-fluid" style="display:none">
<table id="msfTable" class=" table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th scope="col" width="4%">ID</th>
<th scope="col" width="25%">Core Value<span style="color:red;">*</span></th>
<th scope="col" width="25%">Rating<span style="color:red;">*</span></th>
<th scope="col" width="46%">Comment</th>
</tr>
</thead>
<tbody class="resultbody">
</tbody>
</table>
</div>
JQuery
<script type="text/javascript">
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#msfTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#msfTable');
$('[name=count_skills_no]').text();
function myFunction() {
var x = document.getElementById("myMSF");
var y = document.getElementById("myNotice");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "block";
}
var nx = ($('.resultbody tr').length - 0) + 1;
var num_rows = $("#msfTable tbody tr").length + 1;
var rows = $('[name=count_skills_no]').val() - 1;
var sn;
for (var i = 0; i < rows; i++) {
sn = num_rows + i;
//Add row
table.append('<tr>\n' +
'<td class="no">' + sn + '</td>\n' +
' <td><select class="form-control select2bs4" data-placeholder="Choose Employee Type" tabindex="1" name="appraisal_skill_id[]" required>\n' +
' <option value="0" selected="true" disabled="true">Select Core Value</option>\n' +
' #if($skills->count() > 0 )\n' +
' #foreach($skills as $skill)\n' +
' <option value="{{$skill->id}}">{{$skill->skill_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td><select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="appraisal_respondent_rating_id[]" required>\n' +
' <option value="0" selected="true" disabled="true">Select Rating</option>\n' +
' #if($ratings->count() > 0 )\n' +
' #foreach($ratings as $rating)\n' +
' <option value="{{$rating->id}}">{{$rating->rating_value}} - {{$rating->rating_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td><input type="text" name="comment[]" placeholder="Enter comment here" class="form-control comment" required></td>\n' +
'</tr>');
}
}
});
</script>
By default
<div id="myMSF" class="container-fluid" style="display:none">
is hidden while
<div id="myNotice" class="container-fluid">
is visible.
<button type="button" onclick="myFunction()" class="btn btn-block btn-info">
<i class="fas fa-arrow-right"></i>
<span >Proceed</span>
</button>
is to display myMSF and hide. Also it creates tbody of the table
When the button proceed is onclick, I got this error:
Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick
and this code is highlighted
<button type="button" onclick="myFunction()" class="btn btn-block btn-info">
How do I resolve it?
Thanks
You defined function myFunction() { inside the context of $(document).ready(function() {. Hence, it is not visible outside. Move such a function outside the dom ready.
Moreover, avoid inline event handler, use instead .on():
$('#myNotice button.btn-info').on('click', function(e) {
.....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<div id="myNotice" class="container-fluid">
<div style="margin-bottom: 10px;" class="row">
<div class="col-lg-12" >
<button type="button" onclick="myFunction()" class="btn btn-block btn-info">
<i class="fas fa-arrow-right"></i>
<span >Proceed</span>
</button>
</div>
</div>
</div>
<div id="myMSF" class="container-fluid" style="display:none">
<table id="msfTable" class=" table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th scope="col" width="4%">ID</th>
<th scope="col" width="25%">Core Value<span style="color:red;">*</span></th>
<th scope="col" width="25%">Rating<span style="color:red;">*</span></th>
<th scope="col" width="46%">Comment</th>
</tr>
</thead>
<tbody class="resultbody">
</tbody>
</table>
</div>
<script>
function myFunction() {
var x = document.getElementById("myMSF");
var y = document.getElementById("myNotice");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "block";
}
var nx = ($('.resultbody tr').length - 0) + 1;
var num_rows = $("#msfTable tbody tr").length + 1;
var rows = $('[name=count_skills_no]').val() - 1;
var sn;
for (var i = 0; i < rows; i++) {
sn = num_rows + i;
//Add row
table.append('<tr>\n' +
'<td class="no">' + sn + '</td>\n' +
' <td><select class="form-control select2bs4" data-placeholder="Choose Employee Type" tabindex="1" name="appraisal_skill_id[]" required>\n' +
' <option value="0" selected="true" disabled="true">Select Core Value</option>\n' +
' #if($skills->count() > 0 )\n' +
' #foreach($skills as $skill)\n' +
' <option value="{{$skill->id}}">{{$skill->skill_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td><select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="appraisal_respondent_rating_id[]" required>\n' +
' <option value="0" selected="true" disabled="true">Select Rating</option>\n' +
' #if($ratings->count() > 0 )\n' +
' #foreach($ratings as $rating)\n' +
' <option value="{{$rating->id}}">{{$rating->rating_value}} - {{$rating->rating_name}}</option>\n' +
' #endforeach\n' +
' #endif\n' +
' </select></td>\n' +
' <td><input type="text" name="comment[]" placeholder="Enter comment here" class="form-control comment" required></td>\n' +
'</tr>');
}
}
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#msfTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#msfTable');
$('[name=count_skills_no]').text();
});
</script>

Bootstrap modal login

I have this website that is almost a 100% complete but it is based on a customized bootstrap 2.X to meet my needs (bad practice, the fault is entirely on my end.) and what I would like to do is to come up with a modal login that looks like this:
DEMO
The live preview above is based on bootstrap 3.X
You can check with the below link.
Fiddle
<a data-target="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<div class="modal fade hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-remote="/mmfansler/aQ3Ge/show/">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div style="margin-left:35%;>
<modal title="Login form" visible="showModal">
<form role="form">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</modal>
</div>
</div>
</div>
Please Try This one:
$(function() {
var $formLogin = $('#login-form');
var $formLost = $('#lost-form');
var $formRegister = $('#register-form');
var $divForms = $('#div-forms');
var $modalAnimateTime = 300;
var $msgAnimateTime = 150;
var $msgShowTime = 2000;
$("form").submit(function () {
switch(this.id) {
case "login-form":
var $lg_username=$('#login_username').val();
var $lg_password=$('#login_password').val();
if ($lg_username == "ERROR") {
msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "error", "glyphicon-remove", "Login error");
} else {
msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "success", "glyphicon-ok", "Login OK");
}
return false;
break;
case "lost-form":
var $ls_email=$('#lost_email').val();
if ($ls_email == "ERROR") {
msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "error", "glyphicon-remove", "Send error");
} else {
msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "success", "glyphicon-ok", "Send OK");
}
return false;
break;
case "register-form":
var $rg_username=$('#register_username').val();
var $rg_email=$('#register_email').val();
var $rg_password=$('#register_password').val();
if ($rg_username == "ERROR") {
msgChange($('#div-register-msg'), $('#icon-register-msg'), $('#text-register-msg'), "error", "glyphicon-remove", "Register error");
} else {
msgChange($('#div-register-msg'), $('#icon-register-msg'), $('#text-register-msg'), "success", "glyphicon-ok", "Register OK");
}
return false;
break;
default:
return false;
}
return false;
});
$('#login_register_btn').click( function () { modalAnimate($formLogin, $formRegister) });
$('#register_login_btn').click( function () { modalAnimate($formRegister, $formLogin); });
$('#login_lost_btn').click( function () { modalAnimate($formLogin, $formLost); });
$('#lost_login_btn').click( function () { modalAnimate($formLost, $formLogin); });
$('#lost_register_btn').click( function () { modalAnimate($formLost, $formRegister); });
$('#register_lost_btn').click( function () { modalAnimate($formRegister, $formLost); });
function modalAnimate ($oldForm, $newForm) {
var $oldH = $oldForm.height();
var $newH = $newForm.height();
$divForms.css("height",$oldH);
$oldForm.fadeToggle($modalAnimateTime, function(){
$divForms.animate({height: $newH}, $modalAnimateTime, function(){
$newForm.fadeToggle($modalAnimateTime);
});
});
}
function msgFade ($msgId, $msgText) {
$msgId.fadeOut($msgAnimateTime, function() {
$(this).text($msgText).fadeIn($msgAnimateTime);
});
}
function msgChange($divTag, $iconTag, $textTag, $divClass, $iconClass, $msgText) {
var $msgOld = $divTag.text();
msgFade($textTag, $msgText);
$divTag.addClass($divClass);
$iconTag.removeClass("glyphicon-chevron-right");
$iconTag.addClass($iconClass + " " + $divClass);
setTimeout(function() {
msgFade($textTag, $msgOld);
$divTag.removeClass($divClass);
$iconTag.addClass("glyphicon-chevron-right");
$iconTag.removeClass($iconClass + " " + $divClass);
}, $msgShowTime);
}
});
DEMO
More Demos