Unable to tigger elements inside the webui-popover - javascript

I am working on a app dashboard, where I am trying to add a jquery calculator inside webui-popover. the calculator is working fine outside the popover but when it is inside the popover div it is not working. The plugin author said "This problem is caused by that the plugin stop the event bubbling",
I do not have much knowledge about Jquery or Javascript, If anyone can help me with this it will be nice. So, is there any way to make the calculator work inside popover element?.
Calculator Script taken from HERE
Here is the codes
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>

Use dismissible:false
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true,
dismissible:false
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>

Related

How to have clear button on my calculator using javascript

I am kind of having trouble on making my clear function works on my calculator
This is my HTML:
<input type="button" id="result" value="C" onClick="clr()">
<input type="button" name="greater" value="<" onClick="calcNumbers(greater.value)">
<input type="button" name="divb" value="/" onClick="calcNumbers(divb.value)">
<input type="button" name="mulb" value="*" onClick="calcNumbers(mulb.value)">
and this is my JavaScript
function calcNumbers(result) {
form.displayResult.value = form.displayResult.value + result;
}
Wrap all the input fields inside form tag or div tag and give id to that tag, ... and in script tag add function and rest it as document.getElementById("myForm").reset();
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function Add() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else{
var txtResult = +x + +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Sub() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x - +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Mul() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x * +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Div() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else if (y != 0) {
var txtResult = +x / +y;
}
else {
alert("Second Number Should not be Zero");
}
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
function Clear() {
document.getElementById('txtFirst').value = "";
document.getElementById('txtSecond').value = "";
document.getElementById('txtResult').value = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label> FirstNumber :</label><br />
<input id="txtFirst" type="text" /><br />
<label> Second Number :</label><br />
<input id="txtSecond" type="text" /><br />
<label id="txtResult"></label><br />
<input id="btnAdd" type="button" value="ADD" onclick="Add()"/>
<input id="btnSub" type="button" value="SUB" onclick="Sub()"/><br />
<input id="btnMul" type="button" value="MUL" onclick="Mul()"/>
<input id="btnDiv" type="button" value="DIV" onclick="Div()"/>
<input id="btnClear" type="button" value="Clear" onclick="Clear()"/>
</div>
</form>
</body>
</html>
Calculator image
You can clear the text by setting the value to an empty string.
const form = document.querySelector('.calculator > form');
const handleMemoryClear = (v) => {
const disp = form.querySelector('.display');
disp.value = '';
};
const handleMemoryRecall = (v) => console.log('Implement MEMORY_RECALL');
const handleMemoryAdd = (v) => console.log('Implement MEMORY_ADD');
const handleMemoryRemove = (v) => console.log('Implement MEMORY_REMOVE');
const handleOpAdd = (v) => console.log('Implement OP_ADD');
const handleOpSub = (v) => console.log('Implement OP_SUB');
const handleOpMul = (v) => console.log('Implement OP_MUL');
const handleOpDiv = (v) => console.log('Implement OP_DIV');
const handleOpEval = (v) => console.log('Implement OP_EVAL');
const handleTypeIn = (v) => {
const disp = form.querySelector('.display');
disp.value += v;
};
const handleTypeOp = (v) => {
switch (v) {
case '+': return handleOpAdd();
case '-': return handleOpSub();
case '×': return handleOpMul();
case '÷': return handleOpDiv();
case '=': return handleOpEval();
}
}
const handleTypeFn = (v) => {
switch (v) {
case 'MC': return handleMemoryClear();
case 'MR': return handleMemoryRecall();
case 'M+': return handleMemoryAdd();
case 'M-': return handleMemoryRemove();
}
}
const handleButtonPress = (button, type) => {
switch (type) {
case 'in': return handleTypeIn(button.textContent);
case 'op': return handleTypeOp(button.textContent);
case 'fn': return handleTypeFn(button.textContent);
}
};
const ignoreSubmission = e => e.preventDefault();
const handleFormInput = e => {
if (e.target instanceof HTMLButtonElement && e.target.dataset.type) {
handleButtonPress(e.target, e.target.dataset.type);
}
};
form.addEventListener('submit', ignoreSubmission);
form.addEventListener('click', handleFormInput);
:root {
--root-bg: #222;
--root-fg: #EEE;
--calc-bg: #444;
--calc-border: #888;
--calc-disp-bg: #333;
--calc-disp-fg: #EEE;
--calc-btn-bg: #444;
--calc-btn-fg: #EEE;
--calc-btn-hover-bg: #888;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
background: var(--root-bg);
color: var(--root-fg);
}
.calculator {
display: flex;
padding: 0.25em;
background: var(--calc-bg);
border: thin solid var(--calc-border);
align-items: center;
}
.calc-input {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 0.25em;
}
.calc-input > .display {
grid-column-start: 1;
grid-column-end: 5;
grid-row-start: 1;
grid-row-end: 1;
font-size: 1.5em;
background: var(--calc-disp-bg);
border: thin solid var(--calc-border);
color: var(--calc-disp-fg);
font-family: monospace;
text-align: right;
padding: 0.25em;
}
.calc-key {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.125em;
font-weight: bold;
border: thin solid var(--calc-border);
background: var(--calc-btn-bg);
color: var(--calc-btn-fg);
padding: 0.25em 0;
cursor: pointer;
}
.calc-key:hover {
cursor: pointer;
background: var(--calc-btn-hover-bg);
}
.calc-key[data-type="fn"] {
background: #06D;
}
.calc-key[data-type="fn"]:hover {
background: #08F;
}
.calc-key[data-type="op"] {
background: #D60;
}
.calc-key[data-type="op"]:hover {
background: #F80;
}
<div class="calculator">
<form class="calc-input">
<input type="text" class="display" placeholder="0" />
<button class="calc-key" data-type="fn">MC</button>
<button class="calc-key" data-type="fn">M+</button>
<button class="calc-key" data-type="fn">M-</button>
<button class="calc-key" data-type="fn">MR</button>
<button class="calc-key" data-type="in">7</button>
<button class="calc-key" data-type="in">8</button>
<button class="calc-key" data-type="in">9</button>
<button class="calc-key" data-type="op">÷</button>
<button class="calc-key" data-type="in">4</button>
<button class="calc-key" data-type="in">5</button>
<button class="calc-key" data-type="in">6</button>
<button class="calc-key" data-type="op">×</button>
<button class="calc-key" data-type="in">1</button>
<button class="calc-key" data-type="in">2</button>
<button class="calc-key" data-type="in">3</button>
<button class="calc-key" data-type="op">-</button>
<button class="calc-key" data-type="in">0</button>
<button class="calc-key" data-type="in">.</button>
<button class="calc-key" data-type="op">=</button>
<button class="calc-key" data-type="op">+</button>
</form>
</div>

Submit button that shows the score

Below it's my code with a quiz of 4 questions and with a "Submit" button in the last question and I tried to add some code that on Submit it will show an alert with the results of the quiz about how many questions I got correct.
But there are some errors with my code that when I press Submit it doesn't show results of the quiz and it still shows me "Select an option", even that I've selected an option from the question and I've added an if statement to Submit button so it will check if any option is selected or not, but even If I select any option it still shows me that alert ?
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
if (validateForm(i + 1)) {
switchToNextQuestion(this);
}
}
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function validateForm(elementNumber) { // elementnumber gets radio name from multiple questions
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
}
let questions = [{
question: "I am a ?",
userAnswers: ["Male", "Female", "Other"],
correctAnswers: 0,
},
{
question: "Football has letters ?",
userAnswers: [8, 5, 6],
correctAnswers: 0,
},
{
question: "VW stands for ?",
userAnswers: ["BMW", "Volkswagen", "Audi"],
correctAnswers: 1,
},
{
question: "What year is it ?",
userAnswers: [2017, 2015, 2019],
correctAnswers: 2,
}
];
function submitAnswer(elementNumber) {
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
for (i = 0; i < questions.length; i++) {
let correctAnswerIndex = questions[i].correctAnswers;
if (correctAnswerIndex === userAnswers[i]) {
score++;
}
}
if (score != total) {
alert("You got " + score + " out " + total)
}
if (score === total) {
alert("Congratulation your score " + score + " out of " + total);
}
let results = document.getElementById('results')
alert("you")
}
document.getElementById("bot-submit").addEventListener("click",
function(e) {
e.preventDefault();
})
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 60px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
<form id="quiz-form">
<div di="results"></div>
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other" id="correct3"> Other<br/>
<input class="bot" type="button" value="Next" "/>
</div>
<div id="pytja2 " class="questions2 ">
<span class="quest2 ">Football has letters ?</span><br/>
<input type="radio " name="q2 " value="8 " class="correct "> 8<br/>
<input type="radio " name="q2 " value="5 "> 5<br/>
<input type="radio " name="q2 " value="6 "> 6<br/>
<input class="bot " type="button " value="Next ""/>
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" "/>
</div>
<div id="pytja4 " class="questions4 ">
<span class="quest4 ">What year we are ?</span><br/>
<input type="radio " name="q4 " value="2017 " /> 2017<br/>
<input type="radio " name="q4 " value="2015 " /> 2015<br/>
<input type="radio " name="q4 " value="2019 " class="correct " /> 2019<br/>
<input id="bot-submit " type="submit " value="Submit " onclick="submitAnswer(); "/>
</div>
</div>
</form>
As mentioned above, your code has some errors but I have written snippets that will achieve your aim with shorter syntax.
//Javascript code
let questionss = [{
question: "I am a ?",
options: ["Male", "Female", "Other"],
correctAnswers: 'Male',
},
{
question: "Football has letters ?",
options: [8, 5, 6],
correctAnswers: 8,
},
{
question: "VW stands for ?",
options: ["BMW", "Volkswagen", "Audi"],
correctAnswers: 'Volkswagen',
},
{
question: "What year is it ?",
options: [2017, 2015, 2019],
correctAnswers: 2019,
}
];
let questionText = document.getElementById('cd-questions');
let optiontext = document.querySelectorAll('.optiontext');
let options = document.querySelectorAll('.options');
let nextBtn = document.getElementById('next-btn');
let currentQuestion = 0;
var score = 0;
var checkedStatus = false;
setQuestion(currentQuestion); // set default question
nextBtn.addEventListener('click', e => {
e.preventDefault();
if (valForm()) setQuestion(currentQuestion); //validates and next question
});
function setQuestion(currentQuestion) {
questionText.innerText = questionss[currentQuestion].question; //set current question to the DOM
for (let i = 0; i < 3; i++) {
options[i].value = questionss[currentQuestion].options[i]; //set options value for current question
optiontext[i].innerText = questionss[currentQuestion].options[i]; //set options for current question
}
}
function valForm() {
for (let i = 0; i < 3; i++) {
if (options[i].checked) {
let userans = options[i].value;
if (questionss[currentQuestion].correctAnswers == userans) {
score++;
}
options[i].checked = false;
if (currentQuestion < questionss.length - 1) {
currentQuestion++;
if (currentQuestion == questionss.length - 1) {
nextBtn.innerText = 'Submit';
}
} else {
alert('Your total score is ' + score);
currentQuestion = 0;
nextBtn.innerText = 'Start';
}
return true;
}
}
if (checkedStatus == false) {
alert('please choose an answer');
setQuestion(currentQuestion);
}
return false;
}
<form>
<div id="cd-questions"></div>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<div>
<button id="next-btn">Next</button>
</div>
</form>
I'm happy it worked. I want to believe your other question is from the second loop.
for (let i = 0; i < 3; i++) {
if (options[i].checked) { //iterates through the radio buttons for the checked option
let userans = options[i].value; // get the value of the checked
if (questionss[currentQuestion].correctAnswers == userans) {
score++; //increment score by 1 if the chosen answer is the correct answer
}
options[i].checked = false; //reset button to avoid next question being checked by
default.
if (currentQuestion < questionss.length - 1) {
currentQuestion++; // increment current question index
if (currentQuestion == questionss.length - 1) {
nextBtn.innerText = 'Submit'; // Changed submit button text if it's the last question.
}
} else {
alert('Your total score is ' + score);
currentQuestion = 0;
nextBtn.innerText = 'Start';
}
return true; // return true which was tested when the function was involked before nexting the question.
}
}
I hope that helps.

Product configurator doesn't work -.-

I built a WooCommerce configurator on my landingpage, but unfortuantely it doesn't work. Console shows problem with JS code because of .hasclass() which I just don't get - can anyone help me?
Thanks a lot!
HTML:
<div id="amounts">
<button type="button" class="amount-button dreiriegel" value="6,50€" name="7,47€">
<h2>3 Natural Energy-Riegel</h2>
</button>
<button type="button" class="amount-button zwoelfriegel" id="selected" value="23,88€" name="29,88">
<h2>12 Natural Energy-Riegel</h2>
<span>Du sparst xyz</span>
</button>
<button type="button" class="amount-button vierundzwanzigriegel" value="44,90€" name="59,76€">
<h2>24 Natural Energy-Riegel</h2>
<span>Du sparst yz</span>
</button>
</div>
<div id="offer-price"></div>
<div id="normal-price"></div>
<div id="input_div">
<input type="button" value="-" id="moins" onclick="minus()">
<div value="1" id="count">1</div>
<input type="button" value="+" id="plus" onclick="plus()">
</div>
<form id=“bestell-button" action="/cart/?add-to-cart=294&variation_id=299&quantity=1&attribute_pa_variante=12-riegel" method="POST">
<input type="submit" value="Jetzt bestellen">
</form>
CSS:
#selected {
background-color: green;
}
.amount-button {
width: 100%;
}
.amount-button:hover {
cursor: pointer;
}
.amount-button:hover {
background: #DDD;
}
JavaScript:
jQuery(document).ready(function () {
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
jQuery(function($) {
$('.amount-button').click(function() {
$('.amount-button').not(this).removeAttr('id', 'selected');
$(this).attr('id', 'selected');
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
});
var count = 1;
var countEl = document.getElementById("count");
function plus(){
count++;
countEl.value = count;
countEl.innerHTML = count;
}
function minus(){
if (count > 1) {
count--;
countEl.value = count;
countEl.innerHTML = count;
}
}
function getVariation(){
var dieses=jQuery(this);
if (dieses.hasClass("dreiriegel")) {
return 297;
}
else if (dieses.hasClass("zwoelfriegel")) {
return 299;
}
else if (dieses.hasClass("vierundzwanzigriegel")) {
return 300;
}
}
function getAttribute(){
var jenes=jQuery(this);
if (jenes.hasClass("dreiriegel")) {
return 3-riegel;
}
else if (jenes.hasClass("zwoelfriegel")) {
return 12-riegel;
}
else if (jenes.hasClass("vierundzwanzigriegel")) {
return 24-riegel;
}
}
function getLink(){
var href=window.location;
var amount=document.getElementById("#count").value;
var attribute=jQuery("#selected").getVariation();
var variante=jQuery("#selected").getAttribute();
href=href+"cart/?add-to-cart=294&variation_id="+variante+"&quantity="+amount+"&attribute_pa_variante="+attribute;
return href;
}

Create simple text editor (javascript)

I would like to create a simple text editor in Javascript. The challenge for me is: the buttons above my text-editor should be adjusted on the content of the DOM. For example: if the cursor is within a 'ul'-tag in my text-editor, only button 'li' should be displayed.
I already created a 'content-editable div', but I don't know where to look next. Can someone help me with some ideas? If I can do this with help of an existing JS-text-editor, please say.
<html>
<head>
<style>
#textEditor {
border: 1px solid black; display:block; width: 300px; height: 200px;
}
</style>
<script>
var options = ['ul','div'];
var subOptions = {
'ul':['li'],
'div':['div','span', 'p']
};
</script>
</head>
<body>
<div id="textEditor" contenteditable="true"></div>
</body>
</html>
I Create a simple & rich text editor using the only javascript. Especially I create this for my powerBI custom visual. You can use it in any project.
function chooseColor(){
var mycolor = document.getElementById("myColor").value;
document.execCommand('foreColor', false, mycolor);
}
function changeFont(){
var myFont = document.getElementById("input-font").value;
document.execCommand('fontName', false, myFont);
}
function changeSize(){
var mysize = document.getElementById("fontSize").value;
document.execCommand('fontSize', false, mysize);
}
function checkDiv(){
var editorText = document.getElementById("editor1").innerHTML;
if(editorText === ''){
document.getElementById("editor1").style.border = '5px solid red';
}
}
function removeBorder(){
document.getElementById("editor1").style.border = '1px solid transparent';
}
body {
font: 400 16px/1.4 'serif';
}
#container #containerHeader{
text-align: center;
cursor:move;
}
#container #editor1 {
border: 1px solid grey;
height: 100px;
width: 602px;
margin: 0px auto 0;
padding:10px;
}
#container fieldset {
margin: 2px auto 0px;
width: 600px;
height:26px;
background-color: #f2f2f2;
border:none;
}
#container button {
width: 5ex;
text-align: center;
padding: 1px 3px;
height:30px;
width:30px;
background-repeat: no-repeat;
background-size: cover;
border:none;
}
#container img{
width:100%;
}
#container .bold{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAJmSURBVHic7drPi05RHMfx18igGaaJzbAQShby22ZYKBb+CKyMJTsryo/IQigWUjbKnoWVpJSy8TOpIckCC0Xj1zTKGItLWcyZnmbuuY/z+L7rbO73PN/P93y65z73nHsIgiAIgiAIgiAIgiAIgiD43+lqSGc+1qB3Gr/9gfd4h5E6i/oX2YdRTNTQnuA4Fjc6gobYqLoz6jDq7/YVxzC7uaHk57D6jfq73cLCpgYzK3P+RZnz78ANzM2sg/xmNcEgLjQh1Almw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S+8H2cfT3i1B8nksxiLS2U/ShaxRkvlXjjaPOJMsf4DQ22vjD/V/uUAAAAASUVORK5CYII=');
width:40px;
}
#container .align-right{
background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAAA1CAAAAAAsDUmHAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAAAqo0jMgAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+MIHAYOC3tn6N4AAAIsSURBVEjHzZexaxRBFMa/NzMXkzaltimjcQmI7QlqzFmpSQr1GsFWLCRgLSSpRP8B44GViRYhx9mJjRgi54lWabW1VtyZZ5GAM7uZZeYlRbbchY8337zf+94axrE9Bidciy3JFFhTRYvlFTJToMX069lQVBgXDyYPxMyB1O9rO8pJtNRW/8PEvti+ljUbO6dkhlFr93XXGt+vn3ClzC7Cj8B7wgVYofkOF+H7pbm9vMYiBIgfXWLt3yPx6tJ3kV9uuqj0BMgVhbC/nKr2vXJOJqVUncf/746VbbY5EjUeQ8Cy2sOB4lr059Xn5Dvl2dvjAY/BR+Kb/XQ2ldvYVj6PQcn6TX/MpV+EGWwuOB2pC3tZbBrsgSNnJJwFtZJ5IuAcYn5p7nR7OX7duQ4du0fCi6UvyX6583NNvcqYn8/pL27qL7IZ44d0I0PQR+TRCreBel3MsloAOKrOQn43lEkVlytzguneujAfXfdlwLbV/XVDomFIqrfYsR6PjK/AX9kZDUYdn0fCFJQwHxWmAh4VbswNhH6VV25B+XWxetsbivxyxV0VzlXisfvi/qplLUqpVj2H6Oib6+EKORl+WG77UlkZXt8nvIfV6Fu61PRMwyxkerxC6dnBy6vRrLX6/UrOGd3a1baN5uMn6Aw2W+5jm6N+nYYy6WdUOBP1XmPh+W5GPpazi9F8JB4fPB2l5+PMw4mo9yCefJLT7tyYj1xmrNTcuBdK2Typ/7X/ACjdr4z8YnCHAAAAAElFTkSuQmCC');
width:40px;
}
#container .align-center{
width: 38px;
background-size: contain;
background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAABGdBTUEAALGPC/xhBQAAADRJREFUOBFjYGBg2ArE/6mEtzIBDaImADlsCAJSwhSkFgVQGoYjIMwIpdfRdAhJUYMrHQIAWPdBdW2q70gAAAAASUVORK5CYII=');
}
#container .redo-apply{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAKJSURBVHic7du7axRRGIbxn260MELQIoIIFjYBa01lI0btFVEQRBtbSeEFUmhnbeEfoOK1EkQQKxsLUbH00gQLxesuRBANMRZrIJHd2T3jzsyOfA98zdnZc9555sxyZnaGIAiCIAjqw2HcwTXsrjjLUHMBi8vqF85UmmhIWY95K2Ut1dkKcw0lEzqLCmEdWINPQljfHMCCENY3x/UWNlNZuiEkhCUSwhIJYYmEsERCWCIhLJFShK361w56MIot2IS1BY91DEd7bHMOFwvOkcQmnMZjvY92FTVd3K73zyjOY071QrLqJ7YXo6A/tuKF6kX0W6fy7ORIni/9xQQeYXwAfZVFq4pBN+C16mdKSr37k7t0bucIW2W1MFmIiR5Mat8LzzqC09iGRsFZRrT/zOglamfBObpyLyPYA4yVlKMfUU0VihrDjy7BnmNdSTmGXhQc6hBqqXaVlKFfUTtKytOVGZ3DvSlp/NqIgss6B7xVwtgNXO8yfqE/5nkXpd3WKc28QfpkBDdwMGObJvbi6aAHXz3g/hYH3N9yGrgiW1QL+xUgisHLKooGruJIxjYt7MOTokIM4tqwDC7JFtXEFJ4VGaIOM2scJzM+L0UU9ZhZ47pfLjWxR3shXDh1mFmv8KFD+1cliqIesuZxAt+Xtc0qWRT1OA3hvvbdiynt29YP8a3sEHWRBe+111mVUYfTcGgIWQmErARCVgIhK4GQlUDISiBkJRCyEghZCYSsBEJWAiErgZCVQMhKIGQlELISCFkJhKwEQlYCISuBkJVAXlkLXdqLfOSocvLKetmlfTZnf/81m/HRykcT32JjlaGKJu/D/HO4qf2+4hfc1X5B8vOAcgVBEARBMJT8BsNk0YqzYcGdAAAAAElFTkSuQmCC');
}
#container .undo-apply{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAALFSURBVHic7ZzPi05RGMc/M0aSJDZMUXaSlB3T+DGkWCgW2Cn+AYVsSBo/xm78LpoihcmUlIXyIxbWYolSQ7IgeY0fM2Te1+JsmO499zz3fZ97jvF86mxuvef53k/nvfe8z729YBiGYRhGHLYCQ8A1YEPkLMnSBpwDGhPGrpihUiRPVAN4FzFXcrQBZ8gW1QDqwPRo6RLjFPmiGsDTeNHSoh+/qFGgK1q6hOjDL+oHsClauoQ4jokK4hgmKoijmKggjmCigujFRAVxGBMVxH7+E1EdTX7+AG6L4OMsMAasb7JWFp+AYeCjwtwtZS/+FVXleA1cBjYC7ZonXYYlwE/iS8oaL4EduB/vSbCH+FKKxmNgYStPuuyS/dzKEEqsxHUz1sYOMhvXsIu9ekLGGO5aFpXlQI34MkLGV2CZjoZwVuC+kr6gQzS/RcliKrAA2A7cAH4V5HgBzFDIIaKLYmGDwBTlHIuBRwU5+pQzBNENjOAPehV9YR3ARU+G78Bc5QxBdANf8Au7gv6msR245cnQq1w/mFUUC7uEvrBZwIec+q+Ua4tYjbv7+IQNoL/D3uepv0i5tog1FAu7gK6wecB4Tu3knoD3AN/wCzuPrrAnOXVPKNYsTcg17DR6wm7m1BxQqtc06yheYQeVaudtIwbLTFZF7+chsBn35DmPQ7g7WKupt3KyqhplD/ALmwbMryhLaarsKt4HtuC6ABMZIbH9TxZVt2Dv4YTV/jhWB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P8KKLQdVVbn6FBnBSKtCcdKa0bAEcl7Y6+v0oVY0zCs6UdnJaeRib8FA6U1pmUDrH1aR/d9rSRuezfg8khBBCCCGEEEIIIYQQ6u03kq1rwGv96WIAAAAASUVORK5CYII=');
}
#container .orderedlist{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAJDSURBVHic7dq9TxRBGMfx7x2KQfSQzhCICRgSk9OKBgobwY6KhARLC/4CaioKqAQLGwtfao0k0BITNbGSoFEIEBrsjAQTCETepJi7gMfOvrl7Oye/TzLNZGb3mefYJfPsgIiIiIiIiIiIiMh5lws57gJQBLaAtZBzmoHbQH2MuLLyE/gG7Me9QBFYBf6U2nvgus/4HPAYODo1p5baD6A3Rp7IAV89LvjaZ84DBxacRMKuRE3WTcvFdjGPppfnDiw2iXa3cmH5gGTtlCZWOsA8ZrY5/4NY65jmbNYf+YzvpnbfV+X2GaiLniooAE+BX5hneRz7I1g2ACwDhw4sPErbBWaAtqhJEhERERGpirD1rKiuAQ+BdmAeeInZT/q5B9wvzc3KNvABeFOtGzYDK/y9jZjDf681QjbbG1ub/McchDZqCWDQMr6Bk+qGK+0QuFEZaFCJJo6ipf+Opb8NkzCX5IFOr86kLVr6lyz93zG7fZccYaomqWvCJOb0n/U7/D9c1MQ7K63/hgVgGFOW/gS8APYC5vQB/cCllGIK4wB4C7zKMAYREREREfcVgGfAJrAOjBF8rmsAWMDsDJLa5mxijis4/UV6hrOBT/iM7yHd8xRfCD6ikIkWvAPewL53fWKZk2TrqrxpGiWaqBot/Vex/7qXU4ql2veIzHa6cNZnzpDH+CRbrJN/1XILU2wrB/uR4HOrU6Tz3rKeKU2rnhVHHlOS/s3JB48grUAHcDGhGLYxB9lcq9yKiIiIiIiIiIiIOOIYaxc11Cpvh4UAAAAASUVORK5CYII=');
}
#container .strikethrough{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAQAAACROWYpAAAAAmJLR0QA/4ePzL8AAABFSURBVEjHY2AY2eAww38i4GHsmv8TCXFqxmYYPjVIzj5MUPNhXM7G5Q2ywKhm2mo+TG7ipFjzYAGjiYTs8uwwHTUPZwAAW5aYHd3noZcAAAAASUVORK5CYII=');
}
#container .color-apply{
width: 20px;
}
#container #input-font{
width: 100px;
height: 25px;
}
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-text);
color:#888;
}
#container .loader {
border: 6px solid #f3f3f3;
border-top: 6px solid #3498db;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 2s linear infinite;
margin: 0 auto;
line-height: 20px;
}
/* #keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
} */
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript" src="custom-text-editor.js"></script>
<link type="text/css" rel="stylesheet" href="custom-text-editor.css"/>
</head>
<body>
<div id="container" >
<fieldset>
<button class="fontStyle italic" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"></button>
<button class="fontStyle bold" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"></button>
<button class="fontStyle underline" onclick="document.execCommand( 'underline',false,null);"></button>
<select id="input-font" class="input" onchange="changeFont (this);">
<option value="Arial">Arial</option>
<option value="Helvetica">Helvetica</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Sans serif">Sans serif</option>
<option value="Courier New">Courier New</option>
<option value="Verdana">Verdana</option>
<option value="Georgia">Georgia</option>
<option value="Palatino">Palatino</option>
<option value="Garamond">Garamond</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Arial Black">Arial Black</option>
<option value="Tahoma">Tahoma</option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<button class="fontStyle strikethrough" onclick="document.execCommand( 'strikethrough',false,null);"><strikethrough></strikethrough></button>
<button class="fontStyle align-left" onclick="document.execCommand( 'justifyLeft',false,null);"><justifyLeft></justifyLeft></button>
<button class="fontStyle align-center" onclick="document.execCommand( 'justifyCenter',false,null);"><justifyCenter></justifyCenter></button>
<button class="fontStyle align-right" onclick="document.execCommand( 'justifyRight',false,null);"><justifyRight></justifyRight></button>
<button class="fontStyle redo-apply" onclick="document.execCommand( 'redo',false,null);"><redo></redo></button>
<button class="fontStyle undo-apply" onclick="document.execCommand( 'undo',false,null);"><undo></undo></button>
<button class="fontStyle orderedlist" onclick="document.execCommand('insertOrderedList', false, null);"><insertOrderedList></insertOrderedList></button>
<button class="fontStyle unorderedlist" onclick="document.execCommand('insertUnorderedList',false, null)"><insertUnorderedList></insertUnorderedList></button>
<input class="color-apply" type="color" onchange="chooseColor()" id="myColor">
<!-- font size start -->
<select id="fontSize" onclick="changeSize()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<!-- font size end -->
</fieldset>
<div id="editor1" contenteditable="true" data-text="Enter comment...."></div>
</div>
</body>
</html>
You can make a contenteditable html element so the user can edit it.
<div id="myDiv" contenteditable = "true" style = "border: 1px solid black">
<!DOCTYPE html><br>
<html><br>
<head><br>
<br>
<br>
</head><br>
<body><br>
<br>
<br>
</body><br>
</html>
</div>
<script>
w3CodeColor(document.getElementById("myDiv"));
function w3CodeColor(elmnt, mode) {
var lang = (mode || "html");
var elmntObj = (document.getElementById(elmnt) || elmnt);
var elmntTxt = elmntObj.innerHTML;
var tagcolor = "mediumblue";
var tagnamecolor = "brown";
var attributecolor = "red";
var attributevaluecolor = "mediumblue";
var commentcolor = "green";
var cssselectorcolor = "brown";
var csspropertycolor = "red";
var csspropertyvaluecolor = "mediumblue";
var cssdelimitercolor = "black";
var cssimportantcolor = "red";
var jscolor = "black";
var jskeywordcolor = "mediumblue";
var jsstringcolor = "brown";
var jsnumbercolor = "red";
var jspropertycolor = "black";
elmntObj.style.fontFamily = "Consolas,'Courier New', monospace";
if (!lang) {lang = "html"; }
if (lang == "html") {elmntTxt = htmlMode(elmntTxt);}
if (lang == "css") {elmntTxt = cssMode(elmntTxt);}
if (lang == "js") {elmntTxt = jsMode(elmntTxt);}
elmntObj.innerHTML = elmntTxt;
function extract(str, start, end, func, repl) {
var s, e, d = "", a = [];
while (str.search(start) > -1) {
s = str.search(start);
e = str.indexOf(end, s);
if (e == -1) {e = str.length;}
if (repl) {
a.push(func(str.substring(s, e + (end.length))));
str = str.substring(0, s) + repl + str.substr(e + (end.length));
} else {
d += str.substring(0, s);
d += func(str.substring(s, e + (end.length)));
str = str.substr(e + (end.length));
}
}
this.rest = d + str;
this.arr = a;
}
function htmlMode(txt) {
var rest = txt, done = "", php, comment, angular, startpos, endpos, note, i;
comment = new extract(rest, "<!--", "-->", commentMode, "W3HTMLCOMMENTPOS");
rest = comment.rest;
while (rest.indexOf("<") > -1) {
note = "";
startpos = rest.indexOf("<");
if (rest.substr(startpos, 9).toUpperCase() == "&LT;STYLE") {note = "css";}
if (rest.substr(startpos, 10).toUpperCase() == "&LT;SCRIPT") {note = "javascript";}
endpos = rest.indexOf(">", startpos);
if (endpos == -1) {endpos = rest.length;}
done += rest.substring(0, startpos);
done += tagMode(rest.substring(startpos, endpos + 4));
rest = rest.substr(endpos + 4);
if (note == "css") {
endpos = rest.indexOf("</style>");
if (endpos > -1) {
done += cssMode(rest.substring(0, endpos));
rest = rest.substr(endpos);
}
}
if (note == "javascript") {
endpos = rest.indexOf("</script>");
if (endpos > -1) {
done += jsMode(rest.substring(0, endpos));
rest = rest.substr(endpos);
}
}
}
rest = done + rest;
for (i = 0; i < comment.arr.length; i++) {
rest = rest.replace("W3HTMLCOMMENTPOS", comment.arr[i]);
}
return rest;
}
function tagMode(txt) {
var rest = txt, done = "", startpos, endpos, result;
while (rest.search(/(\s|<br>)/) > -1) {
startpos = rest.search(/(\s|<br>)/);
endpos = rest.indexOf(">");
if (endpos == -1) {endpos = rest.length;}
done += rest.substring(0, startpos);
done += attributeMode(rest.substring(startpos, endpos));
rest = rest.substr(endpos);
}
result = done + rest;
result = "<span style=color:" + tagcolor + "><</span>" + result.substring(4);
if (result.substr(result.length - 4, 4) == ">") {
result = result.substring(0, result.length - 4) + "<span style=color:" + tagcolor + ">></span>";
}
return "<span style=color:" + tagnamecolor + ">" + result + "</span>";
}
function attributeMode(txt) {
var rest = txt, done = "", startpos, endpos, singlefnuttpos, doublefnuttpos, spacepos;
while (rest.indexOf("=") > -1) {
endpos = -1;
startpos = rest.indexOf("=");
singlefnuttpos = rest.indexOf("'", startpos);
doublefnuttpos = rest.indexOf('"', startpos);
spacepos = rest.indexOf(" ", startpos + 2);
if (spacepos > -1 && (spacepos < singlefnuttpos || singlefnuttpos == -1) && (spacepos < doublefnuttpos || doublefnuttpos == -1)) {
endpos = rest.indexOf(" ", startpos);
} else if (doublefnuttpos > -1 && (doublefnuttpos < singlefnuttpos || singlefnuttpos == -1) && (doublefnuttpos < spacepos || spacepos == -1)) {
endpos = rest.indexOf('"', rest.indexOf('"', startpos) + 1);
} else if (singlefnuttpos > -1 && (singlefnuttpos < doublefnuttpos || doublefnuttpos == -1) && (singlefnuttpos < spacepos || spacepos == -1)) {
endpos = rest.indexOf("'", rest.indexOf("'", startpos) + 1);
}
if (!endpos || endpos == -1 || endpos < startpos) {endpos = rest.length;}
done += rest.substring(0, startpos);
done += attributeValueMode(rest.substring(startpos, endpos + 1));
rest = rest.substr(endpos + 1);
}
return "<span style=color:" + attributecolor + ">" + done + rest + "</span>";
}
function attributeValueMode(txt) {
return "<span style=color:" + attributevaluecolor + ">" + txt + "</span>";
}
function commentMode(txt) {
return "<span style=color:" + commentcolor + ">" + txt + "</span>";
}
function cssMode(txt) {
var rest = txt, done = "", s, e, comment, i, midz, c, cc;
comment = new extract(rest, /\/\*/, "*/", commentMode, "W3CSSCOMMENTPOS");
rest = comment.rest;
while (rest.search("{") > -1) {
s = rest.search("{");
midz = rest.substr(s + 1);
cc = 1;
c = 0;
for (i = 0; i < midz.length; i++) {
if (midz.substr(i, 1) == "{") {cc++; c++}
if (midz.substr(i, 1) == "}") {cc--;}
if (cc == 0) {break;}
}
if (cc != 0) {c = 0;}
e = s;
for (i = 0; i <= c; i++) {
e = rest.indexOf("}", e + 1);
}
if (e == -1) {e = rest.length;}
done += rest.substring(0, s + 1);
done += cssPropertyMode(rest.substring(s + 1, e));
rest = rest.substr(e);
}
rest = done + rest;
rest = rest.replace(/{/g, "<span style=color:" + cssdelimitercolor + ">{</span>");
rest = rest.replace(/}/g, "<span style=color:" + cssdelimitercolor + ">}</span>");
for (i = 0; i < comment.arr.length; i++) {
rest = rest.replace("W3CSSCOMMENTPOS", comment.arr[i]);
}
return "<span style=color:" + cssselectorcolor + ">" + rest + "</span>";
}
function cssPropertyMode(txt) {
var rest = txt, done = "", s, e, n, loop;
if (rest.indexOf("{") > -1 ) { return cssMode(rest); }
while (rest.search(":") > -1) {
s = rest.search(":");
loop = true;
n = s;
while (loop == true) {
loop = false;
e = rest.indexOf(";", n);
if (rest.substring(e - 5, e + 1) == " ") {
loop = true;
n = e + 1;
}
}
if (e == -1) {e = rest.length;}
done += rest.substring(0, s);
done += cssPropertyValueMode(rest.substring(s, e + 1));
rest = rest.substr(e + 1);
}
return "<span style=color:" + csspropertycolor + ">" + done + rest + "</span>";
}
function cssPropertyValueMode(txt) {
var rest = txt, done = "", s;
rest = "<span style=color:" + cssdelimitercolor + ">:</span>" + rest.substring(1);
while (rest.search(/!important/i) > -1) {
s = rest.search(/!important/i);
done += rest.substring(0, s);
done += cssImportantMode(rest.substring(s, s + 10));
rest = rest.substr(s + 10);
}
result = done + rest;
if (result.substr(result.length - 1, 1) == ";" && result.substr(result.length - 6, 6) != " " && result.substr(result.length - 4, 4) != "<" && result.substr(result.length - 4, 4) != ">" && result.substr(result.length - 5, 5) != "&") {
result = result.substring(0, result.length - 1) + "<span style=color:" + cssdelimitercolor + ">;</span>";
}
return "<span style=color:" + csspropertyvaluecolor + ">" + result + "</span>";
}
function cssImportantMode(txt) {
return "<span style=color:" + cssimportantcolor + ";font-weight:bold;>" + txt + "</span>";
}
function jsMode(txt) {
var rest = txt, done = "", esc = [], i, cc, tt = "", sfnuttpos, dfnuttpos, compos, comlinepos, keywordpos, numpos, mypos, dotpos, y;
for (i = 0; i < rest.length; i++) {
cc = rest.substr(i, 1);
if (cc == "\\") {
esc.push(rest.substr(i, 2));
cc = "W3JSESCAPE";
i++;
}
tt += cc;
}
rest = tt;
y = 1;
while (y == 1) {
sfnuttpos = getPos(rest, "'", "'", jsStringMode);
dfnuttpos = getPos(rest, '"', '"', jsStringMode);
compos = getPos(rest, /\/\*/, "*/", commentMode);
comlinepos = getPos(rest, /\/\//, "<br>", commentMode);
numpos = getNumPos(rest, jsNumberMode);
keywordpos = getKeywordPos("js", rest, jsKeywordMode);
dotpos = getDotPos(rest, jsPropertyMode);
if (Math.max(numpos[0], sfnuttpos[0], dfnuttpos[0], compos[0], comlinepos[0], keywordpos[0], dotpos[0]) == -1) {break;}
mypos = getMinPos(numpos, sfnuttpos, dfnuttpos, compos, comlinepos, keywordpos, dotpos);
if (mypos[0] == -1) {break;}
if (mypos[0] > -1) {
done += rest.substring(0, mypos[0]);
done += mypos[2](rest.substring(mypos[0], mypos[1]));
rest = rest.substr(mypos[1]);
}
}
rest = done + rest;
for (i = 0; i < esc.length; i++) {
rest = rest.replace("W3JSESCAPE", esc[i]);
}
return "<span style=color:" + jscolor + ">" + rest + "</span>";
}
function jsStringMode(txt) {
return "<span style=color:" + jsstringcolor + ">" + txt + "</span>";
}
function jsKeywordMode(txt) {
return "<span style=color:" + jskeywordcolor + ">" + txt + "</span>";
}
function jsNumberMode(txt) {
return "<span style=color:" + jsnumbercolor + ">" + txt + "</span>";
}
function jsPropertyMode(txt) {
return "<span style=color:" + jspropertycolor + ">" + txt + "</span>";
}
function getDotPos(txt, func) {
var x, i, j, s, e, arr = [".","<", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/" ,"-", "*", "|", "%"];
s = txt.indexOf(".");
if (s > -1) {
x = txt.substr(s + 1);
for (j = 0; j < x.length; j++) {
cc = x[j];
for (i = 0; i < arr.length; i++) {
if (cc.indexOf(arr[i]) > -1) {
e = j;
return [s + 1, e + s + 1, func];
}
}
}
}
return [-1, -1, func];
}
function getMinPos() {
var i, arr = [];
for (i = 0; i < arguments.length; i++) {
if (arguments[i][0] > -1) {
if (arr.length == 0 || arguments[i][0] < arr[0]) {arr = arguments[i];}
}
}
if (arr.length == 0) {arr = arguments[i];}
return arr;
}
function getKeywordPos(typ, txt, func) {
var words, i, pos, rpos = -1, rpos2 = -1, patt;
if (typ == "js") {
words = ["abstract","arguments","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete",
"do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import",
"in","instanceof","int","interface","let","long","NaN","native","new","null","package","private","protected","public","return","short","static",
"super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield"];
}
for (i = 0; i < words.length; i++) {
pos = txt.indexOf(words[i]);
if (pos > -1) {
patt = /\W/g;
if (txt.substr(pos + words[i].length,1).match(patt) && txt.substr(pos - 1,1).match(patt)) {
if (pos > -1 && (rpos == -1 || pos < rpos)) {
rpos = pos;
rpos2 = rpos + words[i].length;
}
}
}
}
return [rpos, rpos2, func];
}
function getPos(txt, start, end, func) {
var s, e;
s = txt.search(start);
e = txt.indexOf(end, s + (end.length));
if (e == -1) {e = txt.length;}
return [s, e + (end.length), func];
}
function getNumPos(txt, func) {
var arr = ["<br>", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/" ,"-", "*", "|", "%", "="], i, j, c, startpos = 0, endpos, word;
for (i = 0; i < txt.length; i++) {
for (j = 0; j < arr.length; j++) {
c = txt.substr(i, arr[j].length);
if (c == arr[j]) {
if (c == "-" && (txt.substr(i - 1, 1) == "e" || txt.substr(i - 1, 1) == "E")) {
continue;
}
endpos = i;
if (startpos < endpos) {
word = txt.substring(startpos, endpos);
if (!isNaN(word)) {return [startpos, endpos, func];}
}
i += arr[j].length;
startpos = i;
i -= 1;
break;
}
}
}
return [-1, -1, func];
}
}
</script>
Implementing your own javascript text editor is very challenging, I would recommend you to have a look at the medium editor
If you really want to build your own, and you want to know what element the users cursor is in. You will need to use the selection API which overall has great browsers support.
Try this simple text editor:
<div class="hb-editor">
<div id="editor-element"></div>
<textarea id="editor" class="hb-text-editor" style="direction: ltr;"></textarea>
<div id="editor-view-raw" style="margin: 15px; display: none;"></div>
</div>
$(document).ready(function(){
let editor = new TextEditor(
'#editor',
'#editor-view-raw',
'#editor-element'
);
editor.start();
});
Visit https://github.com/Ho3ein83/texteditor for more
This code is about "Simple Text editor". This html code submit to upload.php.
This js code converts what <div id="editor1" contenteditable="true"></div> typed into a <textarea id="my-textarea" name="t" style="display:none"></textarea> value. :
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("editor1").innerHTML;
}
When this button
<button class="fontStyle save" onclick="save()"><save>fas fa-save</save></button> is clicked will direct the relevant data to upload.php from this code. :
function save() {
getContent();
document.getElementById("save").submit();
}
The source code is Editor.html :
<html>
<head>
<style>
body {
font: 400 16px/1.4 'serif';
}
#container #containerHeader{
text-align: center;
cursor:move;
}
#container #editor1 {
border: 1px solid grey;
height: 80%;
width: 80%;
margin: 0px auto 0;
padding:10px;
}
#container fieldset {
margin: 2px auto 0px;
width: 80%;
height:10%;
background-color: #fafafa;
border:none;
}
#container button {
width: 5ex;
text-align: center;
padding: 1px 3px;
height:30px;
width:40px;
background-repeat: no-repeat;
background-size: cover;
border:none;
}
#container img{
width:100%;
}
</style>
<script>
function chooseColor(){
var mycolor = document.getElementById("myColor").value;
document.execCommand('foreColor', false, mycolor);
}
function backColor(){
var nColor = document.getElementById("nColor").value;
document.execCommand('backColor', false, nColor);
}
function changeFont(){
var myFont = document.getElementById("input-font").value;
document.execCommand('fontName', false, myFont);
}
function changeSize(){
var mysize = document.getElementById("fontSize").value;
document.execCommand('fontSize', false, mysize);
}
function checkDiv(){
var editorText = document.getElementById("editor1").innerHTML;
if(editorText === ''){
document.getElementById("editor1").style.border = '5px solid red';
}
}
function removeBorder(){
document.getElementById("editor1").style.border = '1px solid transparent';
}
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("editor1").innerHTML;
}
function save() {
getContent();
document.getElementById("save").submit();
}
</script>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
</head>
<body>
<div id="container" >
<fieldset>
<button class="fontStyle cut" onclick="document.execCommand('cut',false,null);" title="cut(Ctrl+x)"></button>
<button class="fontStyle copy" onclick="document.execCommand('copy',false,null);" title="copy(ctrl+c)"></button>
<button class="fontStyle italic" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"></button>
<button class="fontStyle bold" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"></button>
<button class="fontStyle underline" onclick="document.execCommand( 'underline',false,null);"> </button>
<select id="input-font" class="input" onchange="changeFont (this);">
<option value="Arial">Arial</option>
<option value="Helvetica">Helvetica</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Sans serif">Sans serif</option>
<option value="Courier New">Courier New</option>
<option value="Verdana">Verdana</option>
<option value="Georgia">Georgia</option>
<option value="Palatino">Palatino</option>
<option value="Garamond">Garamond</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Arial Black">Arial Black</option>
<option value="Tahoma">Tahoma</option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<button class="fontStyle subscript" onclick="document.execCommand( 'subscript',false,null);"><subscript>  </subscript></button>
<button class="fontStyle superscript" onclick="document.execCommand( 'superscript',false,null);"><superscript>  </superscript></button>
<button class="fontStyle strikethrough" onclick="document.execCommand( 'strikethrough',false,null);"><strikethrough> </strikethrough></button>
<button class="fontStyle align-left" onclick="document.execCommand( 'justifyLeft',false,null);"><justifyLeft> </justifyLeft></button>
<button class="fontStyle align-center" onclick="document.execCommand( 'justifyCenter',false,null);"><justifyCenter>  </justifyCenter></button>
<button class="fontStyle align-right" onclick="document.execCommand( 'justifyRight',false,null);"><justifyRight>  </justifyRight></button>
<button class="fontStyle redo-apply" onclick="document.execCommand( 'redo',false,null);"><redo></redo></button>
<button class="fontStyle undo-apply" onclick="document.execCommand( 'undo',false,null);"><undo></undo></button>
<button class="fontStyle createlink" onclick="document.execCommand( 'createLink',false,null);"><link> </link></button>
<button class="fontStyle unlink" onclick="document.execCommand( 'unlink',false,null);"><link> </link></button>
<button class="fontStyle orderedlist" onclick="document.execCommand('insertOrderedList', false, null);"><insertOrderedList></insertOrderedList></button>
<button class="fontStyle unorderedlist" onclick="document.execCommand('insertUnorderedList',false, null)"><insertUnorderedList></insertUnorderedList></button>
<button class="fontStyle save" onclick="save()"><save>fas fa-save</save></button>
<input class="color-apply" type="color" onchange="backColor()" id="nColor" title="highlight">
<input class="color-apply" type="color" onchange="chooseColor()" id="myColor" title="font color">
<!-- font size start -->
<br>
font size :
<select id="fontSize" onclick="changeSize()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<!-- font size end -->
</fieldset>
<form method="get" id ="save" action="upload.php">
<div id="editor1" contenteditable="true">
</div>
<textarea id="my-textarea" name="t" style="display:none"></textarea>
</form>
</div>
</body>
</html>
The document.execCommand() function is deprecated. So these answers are also deprecated.
The thing you need now is document.getSelection() function.
I make a text editor. Its very super simple editor. Using just simple tricks. Here is jquery full source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML page editor</title>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Lato" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="http://localhost/funnel_v2/files/editorscript/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<div class="row">
<div class="col-sm-6">
<h1 class="edit_me_plz" id="jakir">header</h1>
</div>
<div class="col-sm-6">
<button class="edit_me_plz btn btn-info" id="button2">Button</button>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".edit_me_plz").dblclick(function(){
make_element_editable(this);
});
});
function make_element_editable(me){
$( '<textarea onblur="set_my_new_text_with_tag(\''+$(me)[0].localName+'\',\''+$(me)[0].id+'\',this)" style="display: block; width: 100%;">'+$(me)[0].innerHTML+'</textarea>' ).insertAfter(me);
$(me).hide();
}
function set_my_new_text_with_tag(prev_ele,id,me){
$(me).remove();
$("#"+id)[0].innerHTML = $(me)[0].value;
$("#"+id).show();
}
</script>
</body>
</html>
hope you like it. Happy coding. :)
<script>
window.addEventListener('load', function(){
document.getElementById('sampleeditor').setAttribute('contenteditable', 'true');
document.getElementById('sampleeditor2').setAttribute('contenteditable', 'true');
});
function format(command, value) {
document.execCommand(command, false, value);
}
function setUrl() {
var url = document.getElementById('txtFormatUrl').value;
var sText = document.getSelection();
document.execCommand('insertHTML', false, '' + sText + '');
document.getElementById('txtFormatUrl').value = '';
}
</script>
<script>
function changeFont(){
var myFont = document.getElementById("input-font").value;
document.execCommand('fontName', false, myFont);
}
function changeSize(){
var mysize = document.getElementById("fontSize").value;
document.execCommand('fontSize', false, mysize);
}
function changeColor(){
var mysize = document.getElementById("fontColor").value;
document.execCommand('fontColor', false, myColor);
}
function chooseColor(){
var mycolor = document.getElementById("myColor").value;
document.execCommand('foreColor', false, mycolor);
}
</script>
<style>
.editor
{
border:solid 1px #ccc;
padding: 20px;
outline: none;
height: 80%;
}
.sample-toolbar
{
border:solid 1px #ddd;
background:#0055FF;
padding-left: 5px;
padding-bottom: 15px;
padding-top: 15px;
border-radius:3px;
}
a {
padding: 10px 15px;
background: #0055FF;
border: 1px solid #0000;
color: white;
text-decoration: none;
font-size: 15px;
border-radius:3px;
}
a:hover {
color: #ffff;
background: #000EFF;
}
input {
padding: 10px 15px;
background: #0055FF;
border: 1px solid #0000;
color: white;
cursor: pointer;
text-decoration: none;
font-size: 15px;
border-radius:3px;
}
input:hover {
color: #ffff;
background: #000EFF;
}
</style>
<div class="sample-toolbar">
<i class="fa fa-bold fa-fw"></i>old
<i class="fa fa-italic fa-fw"></i>talic
<i class="fa fa-underline"></i> nderline
<i class="fa fa-list fa-fw"></i> List 1
<i class="fa fa-list-ol"></i> List 2
<i class="fa fa-strikethrough"></i> Strikethrough
<i class="fa fa-undo"></i> Undo
<i class="fa fa-redo"></i> Redo
<i class="fas fa-align-left"></i> Align Left
<i class="fas fa-align-center"></i> Align Center
<i class="fas fa-align-right"></i> Align Right
<select id="input-font" class="input" title="Change Font" onchange="changeFont (this);" style= "outline: none;height: 30px;" >
<option value="Arial">Arial</option>
<option value="Helvetica">Helvetica</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Sans serif">Sans serif</option>
<option value="Courier New">Courier New</option>
<option value="Verdana">Verdana</option>
<option value="Georgia">Georgia</option>
<option value="Palatino">Palatino</option>
<option value="Garamond">Garamond</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Arial Black">Arial Black</option>
<option value="Tahoma">Tahoma</option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<select id="fontSize" onclick="changeSize()" title= "Change Font Size" style= "outline: none;height: 30px;" >
<option value selected disabled> Change Font Size</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">6</option>
<option value="5">9</option>
<option value="6">10</option>
<option value="7">12</option>
<option value="8">16</option>
</select>
<input draggable="false" type="color" onchange="chooseColor()" id="myColor" value= "text color" title= "Change Text Color">
</div>
<div class="editor" id="sampleeditor">
</div>
for(let i = 0; i < yourCodeOptions.length; i++) {
document.querySelectorAll("yourCodeOptions")[i].addEventListener("mouseover", function()
{
switch(this.id) {case "ul": document.querySelector("button.li").style.display="block"; //li tag should be "display: none;" before this}
}

Button disabilitation based on class + data-attribute

I'm writing an <input type="number"> with - and + button for an ecommerce cart.
The structure of each group is:
1x <button class="minus" data-prod="prod_id_int">
1x <input type="number" id="prod_id_int">
1x <button class="plus" data-prod="prod_id_int">
What I'm trying to do now is disabling the button - if the value of the input type number is < 1.
To achieve it, based on my script, I have to disable not the general <button class="minus"> but the specific <button class="minus" data-prod="prod_id_int">.
I tried this
$(buttonClass).data('prod', dataProd).prop('disabled', true);
and it actually prevents the quantity from being < 1 BUT it doesn't really add the property disabled to the button. I'm not sure, then, that it's the right way. Can someone explain me how to achieve it?
Here the working snippet
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = parseInt(inputToChangeValue) - parseInt(1);
if (newValue < 1) {
$(buttonClass).data('prod', dataProd).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 1.5%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="62">
<button class="plus" data-prod="90">+</button>
Here is solution.
$('.'+buttonClass).data('prod', dataProd).prop('disabled', true);
All you need is to concatenate . symbol to your class.
buttonClass returns only the className, such as minus and you need jquery selector, like this: $('.minus')
Also, I recommend you to use this: var newValue = --inputToChangeValue; for a simply way to decrement value, instead var newValue = parseInt(inputToChangeValue) - parseInt(1);
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = --inputToChangeValue;
if (newValue < 1) {
$('.'+buttonClass).filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
$('.minus').filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', false);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 10%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="12">
<button class="plus" data-prod="90">+</button>

Categories