Create simple text editor (javascript) - 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/xmNcEgLjQh1AlmwRA25RZpl1nXVa8trbYB7MbLRL4uHMlbcn7OmfzBfG2a+frxKJHzO/pmWO+UlDYNR1RTbjLmYHtO8dLMggd4nogtyylcolnwKnF9IKdoqWb1J65/yilaolkLsSERe5tTuESzjmJeInY3p3BJZvXgDPYn4k+ln2W10K5V+3pcarFvN5ZgCxZM0e/sTItqN6mX0rrbYw3MkpKmYYrP2IWfuYU6wayTeNaEUCeYdQhrmxDqBLP6cFW1NsxKu/4NX+Nmi327VcuYrdK7CmuwFxdnXFkbqXOLpgenE/km8KKGeqekpGk4ioM4n4ivxOqcBZRk1h+OYSwRG8wpXKJZH1W7pZOxPKdwiWaR/ozfnVO0VLNWJK5/ySlaolmbsSoRG84pXJpZ/biciI3jTk7xEszqUp2a2YP7WJfod1t1NKlYmtqimcC23IMp4c5qhSsyT0E6w6yHONCEUG6zPmTOfw87VRuAxZPr5N8YTmlgW6ZphvBNPSYN4wSWNjqC3zR1WrlXtZs5ndPK46rp/Ea1LgyCIAiCIAiCIAiCIAiCIAjaxi96FfJoiZEgRAAAAABJRU5ErkJggg==');
}
#container .italic{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAGDSURBVHic7do7SgRBFEbh0z5BwUhQTMxEMDAXQ1EXIS7AHehWBBMznQ0YizsQJhBfiIGB4Rjo4BiMRnZD11BV3eL5oNJbdS/VfyUNkiRJkiRJkvTfFU0f4Ns8sAZMRqr3AnSBfqR6rTABnACDBOsZ2MjXSnoHpBnUz3oApmIddixWoRFtJ66/DKzGKtb0sN4y7NHLsEcWW6T9DK9ozyMWxT5wC3wSb0g94BxYyNhHoxaBd8qH0WnwXK10RPXNSf0w/CkFcEP5oO5o/mFqlR2qb9Vhg+dqpQ7lg/oAlho8V+sY7AEM9poM9gAGewCDvSaDPYDBXpPBHsBgD2Cw12SwBzDYazLYAxjsAQz2mgz2AAZ7TQZ7AIM9gMHOMLTPgFeqb07o6gPXwF7GPpIrgEviDals7WbrJrEV0g5qAJxm66ZEzFdnJmKtKrMZ9qgUc1hd4ClivTIXietntcnwX84Un+AxMJ6vld9S/Og1DawDc5Hq9YF74DFSPUmSJEmSJEnSyL4AJ3NtCSNV9DYAAAAASUVORK5CYII=');
}
#container .underline{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAJhSURBVHic7drNahNRGMbxfw1WLBaiVtSioLiQrHSpWxERxAvQCxDcqjdRRBBX4qbriis3ikLxAhR3UhRcKC3FD6wgtmJ1XJwUnGTONCd5z5yZ8PzgUEjI+57zdD6SmQERERERERERkaaZAuaAd90x132taT0qMQ9kPWO+gT2i2wls0L+QTWBPg3rk7IhRFJgFdhW83gL2N6hHTqywJoZ8r249cmKFNZYUVgCFFUBhBVBYARRWAIUVQGEFUFgBFFYAhRVAYQVQWAEUVoBYYW2UvLfXqEfZNaufRj1yYoW1hrtqWeSIUQ9fnb/Ad6MeOTG3rI+e984Z9fDV+QD8MupRmUf0Xx/PcIuZHLH2JO6fUVR/YcTaXjEP8M88rx8Fro1Y+zr+3dDXt9b2UXz3JQO+ASeHrNvBHZOK6q5jdwKp3D2KF5UBb4FjgfWO426m+mretZh0KgfwbwUZ8Am4NGCty8DnklprwIzh3JO4hX+BW2MRuAK0ez7bBq4CLwaocSPuMqoxATxk+8VujVXgTffvoJ9ZINK9whSmgFcMvviQ8ZKGPgxSZhp4jG1QT+nfdcdGC7gN/GG0kDZxjxe1qp1+Gh3CjmP/j+fAqeqnnN5Z4AGwTHlAy8B94EyaaTp1OoOcwH2rn8U9e/UbWAGWgPcJ5yUiIuMuxtlwGjgNHIpQe1CrwGvgR8I5bOsC8JU4vwFDxxfgfNzlDm83YVcKqhgrFD/+PRTLa/Ad4KBhPQuHcfMyYRlWlHt1Buo6LxZJv+v1/ug2Y302bAN3gIu4Y1gq68AT4CY13rJERERERERERJx/gYhfcxk8X00AAAAASUVORK5CYII=');
}
#container .align-left{
background-image : url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAAA1CAAAAAAsDUmHAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAAAqo0jMgAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+MIHAYHAD13ih8AAAIrSURBVEjHzZaxTxRBFMa/N7OH0FJqSwnChsTYnomKnJUKFOo1JrbGwpBYmwCV0X9AvMRK1IJ4OTtjYyCQ44xWtNpaa9x5z+IIt7vHbGYeV3DlJvfLm2++b76XCEb2S3DGWeJIRxBLJZboJxShAkvo94uuajBJH00ewZIj1J8bu4Y1LLPd/jLRh/VZLtnaPacTjGp7b5suyev1C5zp5CL8LGhPuASnFJ9xGXm9rNRXN0QVAZInV8Tm75FkfeWHSi+eTkueAHGaKv3Fpux7w6xDGTOcx8G3EeQx5m+WKlgiUZZgkJ9Ff9/sB9+jzN8dF/KwhOR2OzyPhrc+mmFYn8X2fXuMw8VPOu+W2HrmwmFUHhMcQjxnJMyAasEZIuAifHpZaTRbMXrduwnru0fCq5WDYL14bqHKq4LFxRh/SZW/yEU8OWQrMwR72jjmWE65DQxmHORRPRdT+S2UT10dKr1a6m2hB5vKfuTm60LXOtveTEj1GJJpLTeczefxG/BPe3u9hhTyOAWj7EeDqUI/Gtxa6Cj1yq7dgcnPJeZDq6vSi9P7pqA9SMYeqv011LXItKyhvRB0+s11QIjp7ZN7+ZjFUb19Ys8cZ9v0voejpmcr3kKhp2sU3h2yuu7tWmc/r8WckTeu1523H3dgI/JY46918ep1HiYJP6PBBa/2Fksv9yL6MZtf9vYjyXjneS+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/jhWB3aTLTEpNLoBRdwFlgLbgJnAbeBZhBxiYsgCeAucjFS7NMk9CUkZkyXAZAkwWQJMlgCTJcBkCTBZAkyWAJMlwGQJMFkCTJYAkyXAZAkwWQJMlgCTJcBkCTBZAkyWAJMlYLLLGs853igz2WSX9Tzn+HCVIf4V5gBv+Pt1o/dAZ5nJtF+1js0ocB0nqQbcAXZi/31jGIZhGCX5DTQy/pTFeqp6AAAAAElFTkSuQmCC');
}
#container .unorderedlist{
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAI0SURBVHic7dq7axRBGADw30UloEaICAbBQoVgwEcvKWx8gEh6sUqhf4jYaauFVtFGwUK00MrOR2ER8ZFCFBUj+ERFET2NxSgiZHbv9kJul3w/+JrZb4eZ79i527khhBBCCCGEEEIIIYQQlrpWBzkbMIIZfO0gfznGsL6HcS22H3iAt1U7aOEUfmIOH3Co5J5xzP7Jb2KcxbIu6wQOz9PZN2zJ5A/ieQ0m3GsczRVkoKBYE5mC7M/kj2FjQX9NsS93oahYnzPtnzLtnaxnTfClyk27/Fuv/sYrDGfyW7ipP4/OQsaeKsUiPYrT+Igb2FmSP4JL0qfT70l3E7/wWFqnQwghhBBCqK+y/awhHMEo7mAK7ZJ7DmA31vQ6uEU0J/2Cn8LrKh2sxVP/vxZcUVzgYxb/VWUhY1ba7Oza8UyHuRfNdfhegwn3GidyBSnaotmRad+ead+MFQX9NcXW3IWiYk1n2u9l2p9Ie9lNN1PlpvnWrMuW8JrVybfhpPSI3cYFae+nyEFpa7Zpj+RLnMabfg8khBBCCCGEyiZwF+9xDdtK8kdwEe/0/9Wlm2jjvh7+ka5y1uFWDSbea+ytUqzzmc4mM/mjNZjoQsS5XEGKtmiGMu2rM+0rC/pqklW5C0XFujpPWxvXM/mP8KKLQdVVbn6FBnBSKtCcdKa0bAEcl7Y6+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() == "<STYLE") {note = "css";}
if (rest.substr(startpos, 10).toUpperCase() == "<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}
}
Related
Change color based on even / odd answer
My problem is that I'd like the color to switch depending on what the value is, either odd, even or just 0. I've search on stackoverflow for some answers but none really helped.. So, if the answer is odd, the color shall be blue. If the answer is even, the color shall be red. If the answer is 0, the color shall be yellow. Any clues that could help me keep going? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> body { background-color: #0D1112; } form { display: flex; height: 30px; gap: 30px; align-items: center; justify-content: center; } p { color: white; } h1 { color: white; text-align: center; } #svar { background-color: #0D1112; } h4 { color: white; } </style> </head> <body> <form id="f0rm"> <input name="nummer1" id="nummer1" type="text" size="5"> <select id="dropDown" name="thing" id="dropID"> <option>choose</option> <option value="+">+</option> <option value="-">-</option> <option value="x">x</option> <option value="/">/</option> </select> <input name="nummer2" id="nummer2" type="text" size="5"> = <input type="button" id="calculator" value="Submit"> </form> <div id="svar"> <p>Your answer is...</p> <h4>Blue = odd answer</h4> <h4>Red = even answer</h4> <h4>Yellow = your answer is just 0</h4> </div> <script> $(function() { $('#calculator').click(function() { var value = $("#dropDown").val(); var number1 = $("#nummer1").val(); var number2 = $("#nummer2").val(); var int1 = parseInt(number1); var int2 = parseInt(number2); if (value === "+") $("#svar p").text(int1 + int2); else if (value === "-") $("#svar p").text(int1 - int2); else if (value === "/") $("#svar p").text(int1 / int2); else if (value === "x") $("#svar p").text(int1 * int2); if (value % 2 == 0) $("#svar p").css("background-color", "red") else(value % 2 == 1) $("#svar p").css("background-color", "blue") }); }); </script> </body> </html>
Just debugged your code a little bit <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> body { background-color: #0D1112; } form { display: flex; height: 30px; gap: 30px; align-items: center; justify-content: center; } p { color: white; } h1 { color: white; text-align: center; } #svar { background-color: #0D1112; } h4 { color: white; } </style> </head> <body> <form id="f0rm"> <input name="nummer1" id="nummer1" type="text" size="5"> <select id="dropDown" name="thing" id="dropID" required> <option>choose</option> <option value="+">+</option> <option value="-">-</option> <option value="x">x</option> <option value="/">/</option> </select> <input name="nummer2" id="nummer2" type="text" size="5"> = <input type="button" id="calculator" value="Submit"> </form> <div id="svar"> <p>Your answer is...</p> <h4>Blue = odd answer</h4> <h4>Red = even answer</h4> <h4>Yellow = your answer is just 0</h4> </div> <script> $(function() { $('#calculator').click(function() { var value = $("#dropDown").val(); var number1 = $("#nummer1").val(); var number2 = $("#nummer2").val(); var int1 = parseInt(number1); var int2 = parseInt(number2); let result = 0; if (value === "+") result = int1 + int2; else if (value === "-") result = int1 - int2; else if (value === "/") result = int1 / int2; else if (value === "x") result = int1 * int2; $("#svar p").text(result) if (result % 2 == 0){ $("#svar p").css("background-color", "red"); } else { $("#svar p").css("background-color", "blue"); } }); }); </script> </body> </html>
how to hide a div container if input dynamically added with choice in checkbox are empty
how to hide a div container if input dynamically added with choice in checkbox are empty So here what I looked on the forums but I did not find a subject similar to mine As I explained, I created a booking form for an evening with dynamic inputs to choose on a checkbox example: I choose the number of adults / number of children and depending on the number of inputs created creates appear ... until all is well ... I add a PayPal object api (dynamic payment method depending on choice) from their site what I would like to do option 1: it is a "required" on the inputs if the fields are all filled the PayPal button (which is a div) gets gray or option 2: hide the button if empty input. Friends if you could give me a hand this would be super nice thank you !! /* set global variable i */ var i=0; const adult_price = 20; const child_price = 10; /* --------------------------------------------- function to remove fom elements dynamically --------------------------------------------- */ function updateIds(type) { if ( type == "adult" ) { var j=1; // Replace all id_adult_x by id_adult_j, with "j" an ordered list starting with j=1 $('[id^=id_adult_]').each(function() { // Replace the LABEL text document.getElementById("lbl_"+this.id).innerHTML = "<hr>"+"Adulte"+" "+j; var res = this.id.split("id_adult_").join(''); var spanContent = document.getElementById(this.id).innerHTML; var strToReplace = new RegExp('_adult_'+res, "gi"); document.getElementById(this.id).innerHTML = spanContent.replace( strToReplace, '_adult_'+j); this.id = "id_adult_"+j; j= ++j; }); } else if ( type == "child" ) { var j=1; $('[id^=id_child_]').each(function() { // Replace the LABEL text document.getElementById("lbl_"+this.id).innerHTML = "<hr>"+"Enfant"+" "+j; var res = this.id.split("id_child_").join(''); var spanContent = document.getElementById(this.id).innerHTML; var strToReplace = new RegExp('_child_'+res, "gi"); document.getElementById(this.id).innerHTML = spanContent.replace( strToReplace, '_child_'+j); this.id = "id_child_"+j; j= ++j; }); } } /* --------------------------------------------- function to remove fom elements dynamically ---------------------------------------------^ */ function removeElement(parentDiv, childDiv){ if (childDiv == parentDiv) { alert("The parent div cannot be removed."); } else if (document.getElementById(childDiv)) { var child = document.getElementById(childDiv); var parent = document.getElementById(parentDiv); parent.removeChild(child); if (childDiv.includes("adult")) { document.getElementById("nbrAdult").value = $("[id^=id_adult_]").length ; // Calculate the new total price setTotalPrice(); // Update IDs updateIds("adult"); } else if (childDiv.includes("child")) { document.getElementById("nbrChild").value = $("[id^=id_child_]").length ; // Calculate the new total price setTotalPrice(); // Update IDs updateIds("child"); } else { /* do nothing */ } } else { alert("Child div has already been removed or does not exist."); return false; } } /* ---------------------------------------------------------------------------- functions that will be called upon, when user change the list "Nombre Adulte(s)" --------------------------------------------------------------------------- */ function onAdultChange() { // Retrieve the number of "Adult" selected by the user var nbrAdultValue = document.getElementById("nbrAdult").value; // Count the total number of "Adult" Div that are actually created on the html file var idAdultCount = $("[id^=id_adult_]").length; // Calculate the delta btw these variables, in order to create or delete the right number of "Adult" Div var x = nbrAdultValue - idAdultCount; // Check if the delta is negative, if so, we must delete the last "x" number of "Adult" Div if ( x < 0 ) { // Convert "x" from negative to absolute x = Math.abs(x); // alert("This action will remove last "+x+" Adult Fields"); // Remove the last "x" "Adult" Div for (j = 0; j < x ; j++) { var max = 0; $("[id^=id_adult_]").each(function() { var res = this.id.split("id_adult_").join(''); max = Math.max(res, max); }); removeElement("myForm","id_adult_"+max); } } else { // Create "x" new "Adult" Div for (j = 0; j < x; j++) { i = ++i; var r = document.createElement('span'); r.setAttribute("id", "id_adult_"+i); document.getElementById("myForm").appendChild(r); var l = document.createElement("LABEL"); l.setAttribute("id", "lbl_id_adult_"+i); l.innerHTML = "Adulte "+i; document.getElementById("id_adult_"+i).appendChild(l); lastNameFunction("adult_"+i); firstNameFunction("adult_"+i); emailFunction("adult_"+i); telFunction("adult_"+i); var g = document.createElement("IMG"); g.setAttribute("src", "delete.jpg"); g.setAttribute("onclick", "removeElement('myForm','id_adult_"+ i +"')"); document.getElementById("id_adult_"+i).appendChild(g); } } // Calculate the new total price setTotalPrice(); // Update IDs updateIds("adult"); } /* ---------------------------------------------------------------------------- functions that will be called upon, when user change the list "Nombre Enfant(s)" --------------------------------------------------------------------------- */ function onChildChange() { // Retrieve the number of "Child" selected by the user var nbrChildValue = document.getElementById("nbrChild").value; // Count the total number of "Child" Div that are actually created on the html file var idChildCount = $("[id^=id_child_]").length; // Calculate the delta btw these variables, in order to create or delete the right number of "Child" Div var x = nbrChildValue - idChildCount; // Check if the delta is negative, if so, we must delete the last "x" number of "Child" Div if ( x < 0 ) { // Convert "x" from negative to absolute x = Math.abs(x); // alert("This action will remove last "+x+" Child Fields"); // Remove the last "x" "Child" Div for (j = 0; j < x ; j++) { var max = 0; $("[id^=id_child_]").each(function() { var res = this.id.split("id_child_").join(''); max = Math.max(res, max); }); removeElement("myForm","id_child_"+max); } } else { // Create "x" new "Child" Div for (j = 0; j < x; j++) { i = ++i; var r = document.createElement('span'); r.setAttribute("id", "id_child_"+i); document.getElementById("myForm").appendChild(r); var l = document.createElement("LABEL"); l.setAttribute("id", "lbl_id_child_"+i); l.innerHTML = "Enfant "+i; document.getElementById("id_child_"+i).appendChild(l); lastNameFunction("child_"+i); firstNameFunction("child_"+i); var g = document.createElement("IMG"); g.setAttribute("src", "delete.jpg"); g.setAttribute("onclick", "removeElement('myForm','id_child_"+ i +"')"); document.getElementById("id_child_"+i).appendChild(g); } } // Calculate the new total price setTotalPrice(); // Update IDs updateIds("child"); } /* ---------------------------------------------------------------------------- functions that will create an input field for the lastName --------------------------------------------------------------------------- */ function lastNameFunction(type) { var y = document.createElement("INPUT"); y.setAttribute("type", "text"); y.setAttribute("id","nom-de-famille"); y.setAttribute("placeholder","Nom"); y.setAttribute("Name","lastname_"+type); document.getElementById("id_"+type).appendChild(y); document.getElementById("nom-de-famille").required=true; } /* ---------------------------------------------------------------------------- functions that will create an input field for the firstName --------------------------------------------------------------------------- */ function firstNameFunction(type) { var y = document.createElement("INPUT"); y.setAttribute("type", "text"); y.setAttribute("placeholder","Prenom"); y.setAttribute("Name","firstname_"+type); document.getElementById("id_"+type).appendChild(y); } /* ---------------------------------------------------------------------------- functions that will create an input field for the Email --------------------------------------------------------------------------- */ function emailFunction(type) { var y = document.createElement("INPUT"); y.setAttribute("type", "email"); y.setAttribute("placeholder", "Email"); y.setAttribute("Name","email_"+type); document.getElementById("id_"+type).appendChild(y); } /* ---------------------------------------------------------------------------- functions that will create an input field for the phone number --------------------------------------------------------------------------- */ function telFunction(type) { var y = document.createElement("INPUT"); y.setAttribute("type", "tel"); y.setAttribute("placeholder", "Tel"); y.setAttribute("Name","tel_"+type); document.getElementById("id_"+type).appendChild(y); } /* --------------------------------------------- function that calculate the total price --------------------------------------------- */ function setTotalPrice() { document.getElementById("totalPrice").value = document.getElementById("nbrAdult").value*adult_price + document.getElementById("nbrChild").value*child_price; } /* --------------------------------------------- function that create the Items List formatted for Paypal --------------------------------------------- */ function getJsonItemsList() { var itemsList = []; var j=0; $('[id^=id_adult_]').each(function() { itemsList.push({ "name":"Adulte "+(j+1) , "description": document.getElementsByName ("lastname_adult_"+(j+1))[0].value + " " + document.getElementsByName("firstname_adult_" +(j+1))[0].value + " " + document.getElementsByName ("email_adult_"+(j+1))[0].value + " " + document.getElementsByName("tel_adult_" +(j+1))[0].value , "quantity": "1", "price": + adult_price , "currency":"EUR" }); j= ++j; }); var h=0; $('[id^=id_child_]').each(function() { itemsList.push({ "name":"Enfant "+(h+1) , "description": document.getElementsByName("lastname_child_"+(h+1))[0].value + " " + document.getElementsByName("firstname_child_"+(h+1))[0].value , "quantity": "1", "price": + child_price , "currency":"EUR" }); h= ++h; }); if ( j == "0" && h == "0") { itemsList ="' '"; } return itemsList ; } /* ----------------------------------------------------------------------------- functions that will be called upon, when user click on the Reset Button ------------------------------------------------------------------------------ */ function resetElements(){ document.getElementById('myForm').innerHTML = ''; document.getElementById("nbrAdult").value = "0"; document.getElementById("nbrChild").value = "0"; document.getElementById("totalPrice").value = "0"; i = 0; } .three { width: 80%; border: solid 1px lightgray; margin-top: 30px ; margin-bottom: 30px ; margin-left: auto; margin-right: auto; background-color: #FFFFFF; } .jta-before-form { text-align: center; } .jta-form-layout { line-height: 30px; margin: 20px; } #mainform > .jta-form-content { padding: 10px; } #myForm { display: inline; padding: 10px; } input { width: 40%; padding: 12px 20px; margin: 20px; box-sizing: border-box; border-radius: 4px; display: inline-block; } input:focus { background-color: lightgoldenrodyellow; border-radius: 4px; } #lbl_id_adult_1, #lbl_id_adult_2, #lbl_id_adult_3, #lbl_id_adult_4, #lbl_id_adult_5, #lbl_id_adult_6, #lbl_id_adult_7, #lbl_id_adult_8, #lbl_id_adult_9 { margin: 15px 0px 15px 0px ; border-bottom: solid 1px lightgray; display: block; } #id_adult_1> img, #id_adult_2> img, #id_adult_3> img, #id_adult_4> img, #id_adult_5> img, #id_adult_6> img, #id_adult_7> img, #id_adult_8> img, #id_adult_9 > img { float: right; } #lbl_id_child_1, #lbl_id_child_2, #lbl_id_child_3, #lbl_id_child_4, #lbl_id_child_5, #lbl_id_child_6, #lbl_id_child_7, #lbl_id_child_8, #lbl_id_child_9 { margin: 15px 0px 15px 0px ; border-bottom: solid 1px lightgray; display: block; } #id_child_1> img, #id_child_2> img, #id_child_3> img, #id_child_4> img, #id_child_5> img, #id_child_6> img, #id_child_7> img, #id_child_8> img, #id_child_9 > img { float: right; } #totalPrice { border: solid 1px; border-radius: 20px; width: 150px; margin-top: 40px; margin-left: 10px; display: inline-block; text-align: center; } #paypal-button-container { width: 100%; text-align: center; margin-bottom: 20px; } <!DOCTYPE html> <html> <head> <title>Create Dynamic form Using JavaScript - Demo Preview</title> <meta name="robots" content="noindex, nofollow" /> <script src="js/repas-annuel-form.js" type="text/javascript"></script> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="form-style.css"> </head> <body> <div class ="main_content"> <div class="three"> <div class="jta-before-form"> <span id="jta-form-title" class="jta-form-title"> <h3>reservation</h3></span> <div class="">Les champs marqués d’un astérisque * sont obligatoires</div> </div> <div class="jta-form-layout"> <form action="#" type="sbubmit" method="get" id="mainform" > <div class="jta-before-form-content" > <div class="label" > <label for="nbrAdult" >Nombre Adulte(s)</label> </div> <select id="nbrAdult" onchange="onAdultChange()"> <option value="0" selected=>0</option> <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> <option value="9">9</option> </select> </div> <div class="label"> <label for="nbrChild">Nombre Enfant(s)</label> </div> <select id="nbrChild" onchange="onChildChange()" > <option value="" >0</option> <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> <option value="9">9</option> </select> </div> </div> <div class="jta-form-content "> <span id="myForm"></span> </div> <div class="jta-after-form-content">Prix Total (Euro) <INPUT id="totalPrice" type="text" disabled="disabled" placeholder="0" Size=8></INPUT> </div> </form> <div class="jta-after-form"> <div name="button-paypal" id="paypal-button-container"></div> <script src="https://www.paypalobjects.com/api/checkout.js"></script> <script> // Render the PayPal button paypal.Button.render({ // Set your environment env: 'production', // sandbox | production // Specify the style of the button style: { layout: 'vertical', // horizontal | vertical size: 'medium', // medium | large | responsive shape: 'pill', // pill | rect color: 'silver' // gold | blue | silver | white | black }, // Specify allowed and disallowed funding sources // // Options: // - paypal.FUNDING.CARD // - paypal.FUNDING.CREDIT // - paypal.FUNDING.ELV funding: { allowed: [ paypal.FUNDING.CARD, ], disallowed: [ paypal.FUNDING.CREDIT, ], }, // Enable Pay Now checkout flow (optional) commit: true, // PayPal Client IDs - replace with your own // Create a PayPal app: https://developer.paypal.com/developer/applications/create client: { sandbox: 'AXnE7qNrnFxL4IsXrCSFP_mQPvjPNdGo_UA1pHvcw0p_hnmrLQR3_XOlqRTGe7POwHj8urXcd1DmmwWo', production: 'Afe_0oViyEcryagJtFBf34Gkf_hbTgsIjPBkCKIdyD5jYNQF_Kyu3s1nawS46kTMBRoT25STeSnNkFF7' }, // Set up a payment payment: function(data, actions) { return actions.payment.create({ transactions: [{ amount: { total: document.getElementById("totalPrice").value,currency: 'EUR'}, description: 'Reservation - Repas Annuel 2018.', item_list: { items: getJsonItemsList() } }], note_to_payer: 'Contact us for any questions on your order.' }); }, onAuthorize: function (data, actions) { return actions.payment.execute() .then(function () { window.alert('Merci pour votre réservation !'); }); } }, '#paypal-button-container'); </script> </script> </div> </body> </html>
I am going to go out on a limb here and say all this ID management is pretty messy, difficult to maintain and frankly really unnecessary here. Use classes instead and make life a lot simpler for yourself. I modified your markup to use a pair of hidden cloned input groups that I append to the form. I removed a good bit of excess code - still pretty verbose but that is to allow you to see what is happening on each action. I did NOT wire up the reset but that should be easy if you have the button somewhere. I removed a good bit of markup for extra jQuery and unknown js etc. I found and fixed a few (more than a few maybe) typos as well. /* set global variable i */ //var i = 0; const adult_price = 20; const child_price = 10; /* --------------------------------------------- function to remove form elements dynamically --------------------------------------------- */ function updateIds() { let adults = ".adult-container"; let children = ".child-container" let containers = $('#myForm').find('.container-group'); containers.each(function() { let containerDiv = $(this); let idx = 0; if (containerDiv.is(adults)) { idx = $(adults).index($(this)) + 1; } if (containerDiv.is(children)) { idx = $(children).index($(this)) + 1; } containerDiv.find('.numerator').html(idx); }); } /* --------------------------------------------- function to remove form elements dynamically ---------------------------------------------^ */ function removeElement(event) { var parentDiv = $(event.delegateTarget); let containerDiv = $(this).closest('.container-group'); if (containerDiv.is('.adult-container')) { containerDiv.remove(); document.getElementById("nbrAdult").value = $('#myForm').find('.adult-container').length; } if (containerDiv.is('.child-container')) { containerDiv.remove(); document.getElementById("nbrChild").value = $('#myForm').find('.child-container').length; } // Calculate the new total price setTotalPrice(); updateIds(); $('#mainform').trigger('setpaypal'); } /* ---------------------------------------------------------------------------- functions that will be called upon, when user change the list "Nombre" --------------------------------------------------------------------------- */ function onSelectChange(e) { let containerSel = $(this).data('target'); let nbrValue = this.value; let formid = "#myForm"; let myform = $(formid); let items = myform.find(containerSel); let itemsCount = items.length; // Calculate the delta var x = nbrValue - itemsCount; // If the delta is negative, delete x if (x < 0) { let el = items.slice(x).remove(); } else { // Create "x" new let j = 0; let clonex = $('#holder').find(containerSel).eq(0); for (j; j < x; j++) { let c = clonex.clone(true); c.appendTo(formid); } } updateIds(); setTotalPrice(); $('#mainform').trigger('setpaypal'); } /* --------------------------------------------- function that calculate the total price --------------------------------------------- */ function setTotalPrice() { document.getElementById("totalPrice").value = document.getElementById("nbrAdult").value * adult_price + document.getElementById("nbrChild").value * child_price; } /* --------------------------------------------- function that create the Items List formatted for Paypal --------------------------------------------- */ function getJsonItemsList() { var itemsList = []; var selAdultTarget = $('#nbrAdult').data('target'); var adults = $(selTarget); adults.each(function() { let item = { "name": $(this).find('.type-text') + " " + $(this).find('.numerator').text(), "description": $(this).find('.nom-de-famille').val() + "," + $(this).find('.firstname-input').val() + " " + $(this).find('.email-input').val() + " " + $(this).find('.tel-input').val(), "quantity": "1", "price": +adult_price, "currency": "EUR" }; itemsList.push(item); }); var selChildTarget = $('#nbrChild').data('target'); var children = $(selChildTarget); children.each(function() { let item = { "name": $(this).find('.type-text') + " " + $(this).find('.numerator').text(), "description": $(this).find('.nom-de-famille').val() + "," + $(this).find('.firstname-input').val(), "quantity": "1", "price": +child_price, "currency": "EUR" }; itemsList.push(item); }); if (!!children.length && !!adults.length) { itemsList = "' '"; } return itemsList; } /* ----------------------------------------------------------------------------- functions that will be called upon, when user click on the Reset Button ------------------------------------------------------------------------------ */ function resetElements() { // the select change events do this in a controlled way // document.getElementById('myForm').innerHTML = ''; document.getElementById("nbrAdult").value = "0"; document.getElementById("nbrChild").value = "0"; //when you change the selects they do this, i not needed any more //document.getElementById("totalPrice").value = "0"; // i = 0; } function setPayPal() { // put other custom stuff here let showhide = !$('#myForm').find('.container-group').length; // hide if we have none, show if we have some $('.length paypal-button-container') .toggleClass('hidden', showhide); } $(function() { $('#myForm').on("click", ".remove-group", removeElement); $('#mainform').on('change', "#nbrAdult, #nbrChild", onSelectChange); $('#mainform').on('setpaypal', setPayPal); }); .three { width: 80%; border: solid 1px lightgray; margin-top: 30px; margin-bottom: 30px; margin-left: auto; margin-right: auto; background-color: #FFFFFF; } .numerator { margin-left: 1em; } .jta-before-form { text-align: center; } .jta-form-layout { line-height: 30px; margin: 20px; } #mainform>.jta-form-content { padding: 10px; } #myForm { display: inline; padding: 10px; } input { width: 40%; padding: 12px 20px; margin: 20px; box-sizing: border-box; border-radius: 4px; display: inline-block; } input:focus { background-color: lightgoldenrodyellow; border-radius: 4px; } #myForm .group-container .adult-label, #myForm .group-container .child-label { margin: 15px 0px 15px 0px; border-bottom: solid 1px lightgray; display: block; } #myForm img { float: right; } #myForm .group-container .adult-label, #myForm .group-container .child-label { margin: 15px 0px 15px 0px; border-bottom: solid 1px lightgray; display: block; } #totalPrice { border: solid 1px; border-radius: 20px; width: 150px; margin-top: 40px; margin-left: 10px; display: inline-block; text-align: center; } #paypal-button-container { width: 100%; text-align: center; margin-bottom: 20px; } .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div class="main_content"> <div class="three"> <div class="jta-before-form"> <span id="jta-form-title" class="jta-form-title"> <h3>reservation</h3></span> <div class="">Les champs marqués d’un astérisque * sont obligatoires</div> </div> <div class="jta-form-layout"> <form action="#" type="submit" method="get" id="mainform"> <div class="jta-before-form-content"> <div class="label"> <label for="nbrAdult">Nombre Adulte(s)</label> </div> <select id="nbrAdult" data-target='.adult-container'> <option value="0" selected=>0</option> <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> <option value="9">9</option> </select> <div class="label"> <label for="nbrChild">Nombre Enfant(s)</label> </div> <select id="nbrChild" data-target='.child-container'> <option value="">0</option> <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> <option value="9">9</option> </select> </div> <div class="jta-form-content "> <span id="myForm"></span> </div> <div class="jta-after-form-content">Prix Total (Euro) <input id="totalPrice" type="text" disabled="disabled" placeholder="0" Size=8 /> </div> </form> <div class="jta-after-form"> <div name="button-paypal" id="paypal-button-container">Paypal Pal</div> </div> <div id="holder" class="hidden"> <div class="adult-container container-group"> <hr /><label class="adult-label"><span class="type-text">Adulte</span><span class="numerator"></span></label><input type="text" class="nom-de-famille" placeholder="Nom" name="lastname_adult" required=""><input type="text" class="firstname-input" placeholder="Prenom" name="firstname_adult" /><input type="email" class="email-input" placeholder="Email" name="email_adult" /><input type="tel" class="tel-input" placeholder="Tel" name="tel_adult" /><img class="remove-group" src="delete.jpg" /></div> <div class="child-container container-group"> <hr /><label class="child-label"><span class="type-text">Enfant</span><span class="numerator"></span></label><input type="text" class="nom-de-famille" placeholder="Nom" name="lastname_child" /><input type="text" placeholder="Prenom" name="firstname_child" /><img src="delete.jpg" /></div> </div> </body>
You can accomplish this by adding an event listener to your form that listens for keypresses. The listener will listen to all the dynamically created fields and the input elements in them. var filledInputs = [] $("document").ready(function() { $("#myForm").on("keypress", function(e) { var elem = e.target.name + " " + e.target.id if (e.target.value.length > 0) { if (filledInputs.indexOf(elem) === -1) { filledInputs.push(elem) } } else { var elemIndex = filledInputs.indexOf(elem) if (elemIndex !== -1) { filledInputs.splice(elemIndex, 1) } } }) }) EDITTED NOTE: there are two global variables to keep track of all the available inputs in the form, "allInputElements", and the ones that are currently filled "filledInputs". You need to increase "allInputElements" by the number of inputs elements for a field that's being added to the form during it's creation (4 for adults, 2 for children). The code above will add and remove names of the inputs to filledInputs whenever the user types in one. function onAdultChange() { // ... if (x < 0) { // ... for (j = 0; j < x; j++) { // ... removeElement("myForm", "id_adult_" + max); // decrease the global variable when removing input elements allInputElements -= 4 } } else { for (j = 0; j < x; j++) { // ... document.getElementById("id_adult_" + i).appendChild(g); // increase the global variable when adding input elements allInputElements += 4 } } // ... } // ... function onChildChange() { // ... if (x < 0) { // ... for (j = 0; j < x; j++) { // ... removeElement("myForm", "id_child_" + max); // decrease the global variable when adding input elements allInputElements -= 2 } } else { for (j = 0; j < x; j++) { // ... document.getElementById("id_child_" + i).appendChild(g); // increase the global variable when adding input elements allInputElements += 2 } } } Aswell as setting allInputElements and filledInputs back to 0 when you clear the form of all input elements: function resetElements() { // ... allInputElements = 0 filledInputs = [] } PS: if "$(document).ready" doesn't work, move your jQuery to the very bottom of your HTML body element. EDIT: your options for "disabling" the paypal button are to hide it with css' "display: none" or, the better alternative is to simply check if all inputs are filled before running your paypal code. if (filledInputs.length === allInputElements) { // paypal code } // else nothing happens
.html() not showing the whole text that contains the ' character
When i try to edit the value on fields that contain the ' character in them, it cuts the string to that character. For example if I put O'Hara as name a try to edit it, it will give me only the O from O'Hara. Also on a side note is this "valid", correct way to edit the values of the properties on the the contact objects? Thanks in advance. class Contact{ constructor(id, first, last, email, password, phone) { this.id = id || "WTF"; this.first = first || this.get_Random_F_name(); this.last = last || this.get_Random_F_name(); this.email = email || (this.get_Random_F_name() + "#hotmail.com"); this.password = password || Math.floor(Math.random() * Math.floor(90000)); this.phone = phone || Math.floor(Math.random() * Math.floor(500)); } get_Random_F_name(){ let cityIndex = Math.floor(Math.random() * Math.floor(9)); if(cityIndex == 0){ return "O'mara" } else if(cityIndex == 1){ return "F'airfax" } else if(cityIndex == 2){ return "C'harlie" } else if(cityIndex == 3){ return "Evereteze" } else if(cityIndex == 4){ return "H'errera" } else if(cityIndex == 5){ return "Guerriero" } else if(cityIndex == 6){ return "I'mperio" } else if(cityIndex == 7){ return "Levitan" } else { return "A'mato" } } } function dontCoptThatFloppy(id, first, last, email, password, phone) { let proactiveBitch = ("<tr><td class='td-id'>"+ id + "</td><td class='f_Name'>"+first+ "</td><td class='l_Name'>"+last+ "</td><td class='e_mail'>"+email+ "</td><td class='pass_in'>"+password+ "</td><td class='phone_in'>"+phone+ "</td><td class='td-three-Btn'><button class='save-Btn'>save</button>"+ "<button class='edit-Btn'>edit</button><button class='del-Btn'>Broken</button></td>"+ "<td class='td-del'><button class='del-row'>Del</button></td>"+"</tr>") return proactiveBitch; } $(document).ready(function(){ let idCounter = 1; let a_contacts = []; let a_contacts2 = []; let a_contacts3 = []; let contacts_arr_obj = []; let new_contacts_arr_obj = contacts_arr_obj; $('#new-row-btn').click(function(){ let newContact = new Contact(idCounter, $("#name-input").val(), $("#lastname-input").val(), $("#email-input").val(), $("#pass-input").val(), $("#phone-input").val()); $("#my-table").append(dontCoptThatFloppy(idCounter, newContact.first, newContact.last, newContact.email, newContact.password, newContact.phone)) a_contacts.push(newContact); $("#name-input").val("") $("#lastname-input").val("") $("#email-input").val("") $("#pass-input").val("") $("#phone-input").val("") idCounter++; }); $(document).on('click', '.del-row', function (event) { $(event.target).parent().parent().remove() }); $(document).on('click', '.edit-Btn', function (event) { var $row = $(this).closest('tr'); var id = $row.find('.td-id').text(); var fName = a_contacts[id-1].first; var lName = a_contacts[id-1].last; var email = a_contacts[id-1].email; var pass = a_contacts[id-1].password; var phone = a_contacts[id-1].phone; let my_input_f_Name = "<input class='in_f_name' type='text' value='"+fName+"'>" let my_input_l_Name = "<input class='in_l_name' type='text' value='"+lName+"'>" let my_input_e_mail = "<input class='in_e_mail' type='text' value='"+email+"'>" let my_input_pass = "<input class='in_pass_in' type='text' value='"+pass+"'>" let my_input_phone = "<input class='in_phone_in' type='text' value='"+phone+"'>" $row.find('.f_Name').html(my_input_f_Name) $row.find('.l_Name').html(my_input_l_Name) $row.find('.e_mail').html(my_input_e_mail) $row.find('.pass_in').html(my_input_pass) $row.find('.phone_in').html(my_input_phone) let edit = $row.find('.edit-Btn') let del_btn = $row.find('.del-Btn') let save_btn = $row.find('.save-Btn') edit.css('display','none'); del_btn.css('display','none'); save_btn.css('display','block'); }); $(document).on('click', '.save-Btn', function (event) { var $row = $(this).closest('tr'); var id = $row.find('.td-id').text(); a_contacts[id-1].first = $row.find('.in_f_name').val(); a_contacts[id-1].last = $row.find('.in_l_name').val(); a_contacts[id-1].email = $row.find('.in_e_mail').val(); a_contacts[id-1].password = $row.find('.in_pass_in').val(); a_contacts[id-1].phone = $row.find('.in_phone_in').val(); $row.find('.f_Name').html( a_contacts[id-1].first); $row.find('.l_Name').html(a_contacts[id-1].last); $row.find('.e_mail').html(a_contacts[id-1].email); $row.find('.pass_in').html(a_contacts[id-1].password); $row.find('.phone_in').html(a_contacts[id-1].phone); let edit = $row.find('.edit-Btn') let del_btn = $row.find('.del-Btn') let save_btn = $row.find('.save-Btn') edit.css('display','inline'); del_btn.css('display','inline'); save_btn.css('display','none'); }); $(document).on('click', '#sup', function (event) { console.log(a_contacts); }); $("#sort").on("change", function(event){ let pickedValue = event.target.value; let table = $('#my-table') let rows = table.find('.td-id').toArray() if (pickedValue === "1"){ a_contacts.sort(function(a, b){ return a.id - b.id; }); } else if (pickedValue === "2"){ a_contacts.sort(function(a,b) { return a.first.localeCompare(b.first); }); } else if (pickedValue === "3"){ a_contacts.sort(function(a,b) { return a.last.localeCompare(b.last); }); } else if (pickedValue === "4"){ a_contacts.sort(function(a,b) { return a.email.localeCompare(b.email); }); } else if (pickedValue === "5"){ a_contacts.sort(function(a, b){ return a.password - b.password; }); } else if (pickedValue === "6"){ a_contacts.sort(function(a, b){ return a.phone - b.phone; }); } else{} $(tbody).html(""); for (var i = 0; i < rows.length; i++){ $("#my-table").append(dontCoptThatFloppy(a_contacts[i].id, a_contacts[i].first, a_contacts[i].last, a_contacts[i].email, a_contacts[i].password, a_contacts[i].phone)) } }); }); <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" type="text/css" media="screen" href="CSS/style.css" /> </head> <body> <div id="inputs-div"> <input type="text" placeholder="Your Name Sir" id="name-input"> <input type="text" placeholder="Your Last Name Sir" id="lastname-input"> <input type="text" placeholder="Your Email Sir" id="email-input"> <input type="password" placeholder="Your Password Sir" id="pass-input" > <input type="text" placeholder="Your Phone Number" id="phone-input" > <button id="new-row-btn">Add Contact</button> <button id="sup">Console.Log</button> </div> <select class="custom-select" id="sort"> <option selected>Choose...</option> <option value="1">ID</option> <option value="2">First Name</option> <option value="3">Last Name</option> <option value="4">Email</option> <option value="5">Password</option> <option value="6">Phone</option> </select> <div> <table id="my-table"> <thead> <tr id="first-row"> <th>ID</th> <th>First name</th> <th>Last name</th> <th>Email</th> <th>Password</th> <th>Phone</th> <th>Action</th> <th>Delete</th> </tr> </thead> <tbody id="tbody"> </tbody> </table> </div> <script src="JS/jquery-3.2.1.js"></script> <script src="JS/script.js"></script> </body> </html> *{ margin: 0px; padding: 0px; } body{ background-color: black; color: wheat; } input{ display: block; margin: 2px; border: 2px solid #ac7b11; background-color: rgba(44, 42, 42, 0.863); color: #bebe35; } ::placeholder { color: #bebe35; } button{ background-color: #1a64a0; border: 2px solid #1a64a0; color: white; border-radius: 3px; outline:none; /* text-align: center; display:table-cell; vertical-align:middle; */ } #new-row-btn, #sup{ width: 100px; height: 30px; margin: 3px; } .del-row{ /* display: flex; */ width: 100%; height: 100%; /* margin: 0px auto; */ /* text-align: 0px auto; */ } .small-Btn, .medium-Btn{ display: none; } .del-Btn, .edit-Btn{ background-color: #10b133; border: 2px solid #10b133; width: 50%; height: 100%; } .save-Btn{ background-color: #a1b110; border: 2px solid #a1b110; display: none; width: 100%; height: 100%; } th{ height: 30px; width: 100px; } td{ height: 30px; width: 100px; } .td-id{ width: 30px; text-align: center; } #my-table tbody tr td { background-color: #a35635; } #my-table tbody tr td:nth-child(odd) { background-color: #828e20; } .td-del, .td-three-Btn{ background-color: transparent !important; } td input{ box-sizing: border-box; width: 100%; height: 100%; margin:0px; }
When you write something like this: let my_input_f_Name = "<input class='in_f_name' type='text' value='"+fName+"'>" if the value of fName is O'hara, the resulting HTML is: <input class='in_f_name' type='text' value='O'hara'> The ' in the name matches the ' that starts the value attribute, so it ends the attribute; it's equivalen to writing <input class='in_f_name' type='text' value='O' hara'> Since you're using jQuery, you can use its methods to create your elements instead of concatenating strings: let my_input_f_Name = $("<input>", { "class": "in_f_name", type: "text", value: fName });
how to display the selected text instead of values
Hi i have a piece of code & i couldn't display the selected text instead of values in fourth list box. Now, It displays the values of the option but i want to display the text i.e Paper Manufacturers << Paper Converters << Molded Pulp Products. $(document).ready(function() { var firstCategorySelector = '.select-manage-category'; var secondCategorySelector = '.select-manage-category1'; var thirdCategorySelector = '.select-manage-category2'; var firstCategory = $(firstCategorySelector); var secondCategory = $(secondCategorySelector); var thirdCategory = $(thirdCategorySelector); var addCategoryButton = $("#add-category"); var removeCategoryButton = $('#remove-category'); var selectedList = $('#selected-lst-values'); var choice = $("#tget"); $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() { AddCategoryButtonEnable(); }); function getCategoryValues() { var firstCategoryValue = firstCategory.val(); var secondCategoryValue = secondCategory.val(); var thirdCategoryValue = thirdCategory.val(); return [firstCategoryValue, secondCategoryValue, thirdCategoryValue]; } function isDisableAddButton() { var values = getCategoryValues(); return (!values[0] || !values[1] || !values[2]); } function AddCategoryButtonEnable() { var isDisableAddCategoryButton = isDisableAddButton(); addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton); } function getNumberOfSelectedOption() { return selectedList.find("option").length; } function getAvailableChoice() { return 20 - parseInt(getNumberOfSelectedOption()); } function setAvailableChoice($numChoice) { var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 "; choice.text(strText); } function appendChoice() { var count=""; var givenCategoryArrayValue = getCategoryValues(); if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.'); return count=1; } else { selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>'); return count=2; } } addCategoryButton.click(function() { var availableChoice = getAvailableChoice(); if (availableChoice >= 1) { var a=appendChoice(); if(a==2){ setAvailableChoice(availableChoice - 1); } } else { setAvailableChoice(0); } }); var option = selectedList.find('option:selected'); selectedList.change(function() { removeCategoryButton.prop("disabled", false); addCategoryButton.prop("disabled", true); _addRemoveButtonClickListener(); }); function _addRemoveButtonClickListener() { removeCategoryButton.click(function() { selectedList.find('option:selected').remove(); var availableChoice = getAvailableChoice(); if (0 < availableChoice < 6) { setAvailableChoice(availableChoice); } else { setAvailableChoice(0); } removeCategoryButton.prop("disabled", true); }); } }); .select-manage-category, .select-manage-category1, .select-manage-category2 { width: 100px; float: left; margin-right: 4px; } p { clear: left; text-align: center; } #selected-lst-values { width: 100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <select class="form-control select-manage-category" size="5"> <option value="1">Paper Manufacturers</option> <option value="2">Paper Products Suppliers</option> <option value="3">Paper Chemicals Suppliers</option> </select> </div> <div> <select class="form-control select-manage-category1" size="5"> <option value="1">Paper Converters</option> <option value="2">Lab Apparatus & Supplies</option> <option value="3">Service Providers</option> </select> </div> <div> <select class="form-control select-manage-category2" size="5"> <option value="1">Molded Pulp Products</option> <option value="2">Software Vendors</option> <option value="3">Information Services</option> </select> </div> <p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p> </div> <input id="add-category" name="add" type="button" value="Add Category" disabled="true"> <input id="remove-category" name="add" type="button" value="Remove Category" disabled="true"> <div> <select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple"> </select> </div> <button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"> <strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span> </button>
You should assign these texts which you want to get as the value of each options: $(document).ready(function() { var firstCategorySelector = '.select-manage-category'; var secondCategorySelector = '.select-manage-category1'; var thirdCategorySelector = '.select-manage-category2'; var firstCategory = $(firstCategorySelector); var secondCategory = $(secondCategorySelector); var thirdCategory = $(thirdCategorySelector); var addCategoryButton = $("#add-category"); var removeCategoryButton = $('#remove-category'); var selectedList = $('#selected-lst-values'); var choice = $("#tget"); $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() { AddCategoryButtonEnable(); }); function getCategoryValues() { var firstCategoryValue = firstCategory.val(); var secondCategoryValue = secondCategory.val(); var thirdCategoryValue = thirdCategory.val(); return [firstCategoryValue, secondCategoryValue, thirdCategoryValue]; } function getCategoryDisplay() { var firstCategoryDisplay = $(firstCategorySelector+" option:selected").text(); var secondCategoryDisplay = $(secondCategorySelector+" option:selected").text(); var thirdCategoryDisplay = $(thirdCategorySelector+" option:selected").text(); return [firstCategoryDisplay, secondCategoryDisplay, thirdCategoryDisplay]; } function isDisableAddButton() { var values = getCategoryValues(); return (!values[0] || !values[1] || !values[2]); } function AddCategoryButtonEnable() { var isDisableAddCategoryButton = isDisableAddButton(); addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton); } function getNumberOfSelectedOption() { return selectedList.find("option").length; } function getAvailableChoice() { return 20 - parseInt(getNumberOfSelectedOption()); } function setAvailableChoice($numChoice) { var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 "; choice.text(strText); } function appendChoice() { var count=""; var givenCategoryArrayValue = getCategoryValues(); var givenCategoryArrayDisplay = getCategoryDisplay(); if ($('#selected-lst-values option:contains("' + givenCategoryArrayDisplay[0] + ' << ' + givenCategoryArrayDisplay[1] + ' << ' + givenCategoryArrayDisplay[2] + '")').length > 0) {alert('This category has already been added.'); return count=1; } else { selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayDisplay[0] + ' << ' + givenCategoryArrayDisplay[1] + ' << ' + givenCategoryArrayDisplay[2] + '</option>'); return count=2; } } addCategoryButton.click(function() { var availableChoice = getAvailableChoice(); if (availableChoice >= 1) { var a=appendChoice(); if(a==2){ setAvailableChoice(availableChoice - 1); } } else { setAvailableChoice(0); } }); var option = selectedList.find('option:selected'); selectedList.change(function() { removeCategoryButton.prop("disabled", false); addCategoryButton.prop("disabled", true); _addRemoveButtonClickListener(); }); function _addRemoveButtonClickListener() { removeCategoryButton.click(function() { selectedList.find('option:selected').remove(); var availableChoice = getAvailableChoice(); if (0 < availableChoice < 6) { setAvailableChoice(availableChoice); } else { setAvailableChoice(0); } removeCategoryButton.prop("disabled", true); }); } }); .select-manage-category, .select-manage-category1, .select-manage-category2 { width: 100px; float: left; margin-right: 4px; } p { clear: left; text-align: center; } #selected-lst-values { width: 100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><select class="form-control select-manage-category" size="5"> <option value="1">Paper Manufacturers</option> <option value="2">Paper Products Suppliers</option> <option value="3">Paper Chemicals Suppliers</option> </select></div> <div><select class="form-control select-manage-category1" size="5"> <option value="1">Paper Converters</option> <option value="2">Lab Apparatus & Supplies</option> <option value="3">Service Providers</option> </select></div> <div><select class="form-control select-manage-category2" size="5"> <option value="1">Molded Pulp Products</option> <option value="2">Software Vendors</option> <option value="3">Information Services</option> </select> </div> <p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p> </div> <input id="add-category" name="add" type="button" value="Add Category" disabled="true"> <input id="remove-category" name="add" type="button" value="Remove Category" disabled="true"> <div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple"> </select></div> <button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button> Updated: Defined new function getCategoryDisplay to get text of selected option as per your expected output in below comment.
It's a bit hard to tell how you want your final category data to be stored, but you can get the options to hold text descriptions instead of numbers by creating a getCategoryNames function and using it in place of getCategoryValues in appendChoice: function getCategoryNames() { return [].map.call(categories, function(e) { return $(':selected', e).text() }) } It's also probably a good idea to give your selects a common class of .select-manage-category (without adding any numeric suffixes), because this simplifies your jQuery element selection: var categories = $('.select-manage-category') Demo Snippet: $(document).ready(function() { var categories = $('.select-manage-category') var addCategoryButton = $("#add-category") var removeCategoryButton = $('#remove-category') var selectedList = $('#selected-lst-values') var choice = $("#tget") categories.change(AddCategoryButtonEnable) function getCategoryValues() { return [].map.call(categories, function(e) { return e.value }) } function getCategoryNames() { return [].map.call(categories, function(e) { return $(':selected', e).text() }) } function isDisableAddButton() { var values = getCategoryValues(); return (!values[0] || !values[1] || !values[2]); } function AddCategoryButtonEnable() { var isDisableAddCategoryButton = isDisableAddButton(); addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton); } function getNumberOfSelectedOption() { return selectedList.find("option").length; } function getAvailableChoice() { return 20 - parseInt(getNumberOfSelectedOption()); } function setAvailableChoice($numChoice) { var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 "; choice.text(strText); } function appendChoice() { var count = ""; var givenCategoryArrayValue = getCategoryValues().join(' << '); if ($('#selected-lst-values option[value="' + givenCategoryArrayValue + '"]').length > 0) { alert('This category has already been added.'); return count = 1; } else { selectedList.append(new Option(getCategoryNames().join(' << '), givenCategoryArrayValue)); return count = 2; } } addCategoryButton.click(function() { var availableChoice = getAvailableChoice(); if (availableChoice >= 1) { var a = appendChoice(); if (a == 2) { setAvailableChoice(availableChoice - 1); } } else { setAvailableChoice(0); } }); var option = selectedList.find(':selected'); selectedList.change(function() { removeCategoryButton.prop("disabled", false); addCategoryButton.prop("disabled", true); _addRemoveButtonClickListener(); }); function _addRemoveButtonClickListener() { removeCategoryButton.click(function() { selectedList.find('option:selected').remove(); var availableChoice = getAvailableChoice(); if (0 < availableChoice < 6) { setAvailableChoice(availableChoice); } else { setAvailableChoice(0); } removeCategoryButton.prop("disabled", true); }); } }); .select-manage-category { width: 100px; float: left; margin-right: 4px; } p { clear: left; text-align: center; } #selected-lst-values { width: 100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><select class="form-control select-manage-category" size="5"> <option value="1">Paper Manufacturers</option> <option value="2">Paper Products Suppliers</option> <option value="3">Paper Chemicals Suppliers</option> </select></div> <div><select class="form-control select-manage-category" size="5"> <option value="1">Paper Converters</option> <option value="2">Lab Apparatus & Supplies</option> <option value="3">Service Providers</option> </select></div> <div><select class="form-control select-manage-category" size="5"> <option value="1">Molded Pulp Products</option> <option value="2">Software Vendors</option> <option value="3">Information Services</option> </select> </div> <p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p> <input id="add-category" name="add" type="button" value="Add Category" disabled="true"> <input id="remove-category" name="add" type="button" value="Remove Category" disabled="true"> <div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple"> </select></div> <button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
var firstCategoryValue = firstCategory.val(); will return the array of selected values. To get the array of selected text use $('.select-manage-category :selected').each(function(i, v) { firstCategoryValue[i] = $(v).text(); }); Updated Snippet: $(document).ready(function() { var firstCategorySelector = '.select-manage-category'; var secondCategorySelector = '.select-manage-category1'; var thirdCategorySelector = '.select-manage-category2'; var firstCategory = $(firstCategorySelector); var secondCategory = $(secondCategorySelector); var thirdCategory = $(thirdCategorySelector); var addCategoryButton = $("#add-category"); var removeCategoryButton = $('#remove-category'); var selectedList = $('#selected-lst-values'); var choice = $("#tget"); $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() { AddCategoryButtonEnable(); }); function getCategoryValues() { var firstCategoryValue = []; var secondCategoryValue = []; var thirdCategoryValue = []; $('.select-manage-category :selected').each(function(i, v) { firstCategoryValue[i] = $(v).text(); }); $('.select-manage-category1 :selected').each(function(i, v) { secondCategoryValue[i] = $(v).text(); }); $('.select-manage-category2 :selected').each(function(i, v) { thirdCategoryValue[i] = $(v).text(); }); return [firstCategoryValue, secondCategoryValue, thirdCategoryValue]; } function isDisableAddButton() { var values = getCategoryValues(); return (!values[0] || !values[1] || !values[2]); } function AddCategoryButtonEnable() { var isDisableAddCategoryButton = isDisableAddButton(); addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton); } function getNumberOfSelectedOption() { return selectedList.find("option").length; } function getAvailableChoice() { return 20 - parseInt(getNumberOfSelectedOption()); } function setAvailableChoice($numChoice) { var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 "; choice.text(strText); } function appendChoice() { var count = ""; var givenCategoryArrayValue = getCategoryValues(); if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) { alert('This category has already been added.'); return count = 1; } else { selectedList.append('<option value="' + givenCategoryArrayValue[0].value + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>'); return count = 2; } } addCategoryButton.click(function() { var availableChoice = getAvailableChoice(); if (availableChoice >= 1) { var a = appendChoice(); if (a == 2) { setAvailableChoice(availableChoice - 1); } } else { setAvailableChoice(0); } }); var option = selectedList.find('option:selected'); selectedList.change(function() { removeCategoryButton.prop("disabled", false); addCategoryButton.prop("disabled", true); _addRemoveButtonClickListener(); }); function _addRemoveButtonClickListener() { removeCategoryButton.click(function() { selectedList.find('option:selected').remove(); var availableChoice = getAvailableChoice(); if (0 < availableChoice < 6) { setAvailableChoice(availableChoice); } else { setAvailableChoice(0); } removeCategoryButton.prop("disabled", true); }); } }); .select-manage-category, .select-manage-category1, .select-manage-category2 { width: 100px; float: left; margin-right: 4px; } p { clear: left; text-align: center; } #selected-lst-values { width: 100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><select class="form-control select-manage-category" size="5"> <option value="1">Paper Manufacturers</option> <option value="2">Paper Products Suppliers</option> <option value="3">Paper Chemicals Suppliers</option> </select></div> <div><select class="form-control select-manage-category1" size="5"> <option value="1">Paper Converters</option> <option value="2">Lab Apparatus & Supplies</option> <option value="3">Service Providers</option> </select></div> <div><select class="form-control select-manage-category2" size="5"> <option value="1">Molded Pulp Products</option> <option value="2">Software Vendors</option> <option value="3">Information Services</option> </select> </div> <p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p> </div> <input id="add-category" name="add" type="button" value="Add Category" disabled="true"> <input id="remove-category" name="add" type="button" value="Remove Category" disabled="true"> <div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple"> </select></div> <button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
How to assign a class or ID to a table within a JavaScript function?
I have to use HTML, CSS and JavaScript (so no jQuery). I have created a table that receives JSON data via API. I have a function to show/hide each of the table rows by clicking a check box. I already included the JavaScript function, but I cannot figure out where to place a class or id, so I can connect the function to each of the table rows. Generally, I would add a class to <td> for example, like this: <td class="example"> but in this case it won't work. The code breaks when I do this. I did search online for hours, but wasn't able to find an answer. I'm not looking for finished code, but rather a hint/help how to achieve this. This table is created using: body { background: white; } h1 { color: black; font-size: 35px; text-align: center; font-family: 'Quicksand', sans-serif; } h2 { font-family: 'Quicksand', sans-serif; margin-left: 3.3em; } table, th , td { border: none; border-collapse: collapse; padding: 15px; margin-left: 5em; margin-top: -25em; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } #form { font-family: 'Quicksand', sans-serif; margin-left: 5em; } #googleMap { margin-left: 45em;; margin-right: auto; } #chkbox_display { margin-left: 5em; margin-top: 3em; font-family: 'Quicksand', sans-serif; } .hidden { display: none; } <html> <head> <link rel="stylesheet" type="text/css" href="main.css"> <link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'> <title>Weather App</title> </head> <body> <h1>Weather Forecast</h1> <div id="id01"></div> <h2>Please enter the following information:</h2> <form id="form" onsubmit ="return fetchUrl()"> Enter your City:<br> <input id="weather_city" placeholder="Entere here..."><br> How to display values: <br> <select id="weather_scale"> <option value="Metric">Metric Units (Celcius/mm)</option> <option value="Imperial">Imperial Units (Fahrenheit/inch)</option> </select><br> Number of days to show weather:<br> <select id="weather_numberOfDays"> <option value="1">Today only</option> <option value="2">2 days</option> <option value="3">3 days</option> <option value="4">4 days</option> <option value="5">5 days</option> </select> <br><br> <button onclick="initialize">Submit</button> </form> <div id="chkbox_display"> <form action="#"> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Max. Temp.</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Min. Temp</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Rainfall</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Pressure</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Humidity</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Wind Speed</label> </form> </div> <script> function initAutocomplete() { weather_city = new google.maps.places.Autocomplete( (document.getElementById('weather_city')), {types: ['geocode']}); weather_city.addListener('place_changed'); } </script> <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script> <script> var longitude; var latitude; function initalize(arr) { var lon = arr.city.coord.lon; var lat = arr.city.coord.lat; var mapProp = { center:new google.maps.LatLng(lat,lon), zoom:10, mapTypeId:google.maps.MapTypeId.ROADMAP } var map=new google.maps.Map(document.getElementById("googleMap"), mapProp); } </script> <div id="googleMap" style="width:600px;height:480px;"></div> <section> <div id="table"> <!-- <tr> <td class="hidden">example</td> <td class="hidden"></td> <td class="hidden"></td> </tr> --> </div> </section> <script> function getJson(request) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", request, true); xmlhttp.send(); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { myFunction(xmlhttp.responseText); } } } function fetchUrl() { var form = document.getElementById("form"); var city = form.weather_city.value; var value = form.weather_scale.value; var days = form.weather_numberOfDays.value; var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days; getJson(url); return false; } function myFunction(response) { var arr = JSON.parse(response); initalize(arr); var i; var out = "<table>"; for(i = 0; i < arr.list.length; i++) { out += "<tr><td>" + new Date(arr.list[i].dt * 1000) + "</td></tr>" + "<tr><td>" + getIcon(arr.list[i].weather[0].icon) + "</td><td>" + arr.list[i].weather[0].description + "</td><tr>" + "</tr><td>" + "Min. Temperature" + "</td><td>" + arr.list[i].temp.min + "</td><tr>" + "</tr><td>" + "Max. Temperature" + "</td><td>" + arr.list[i].temp.max + "</td><tr>" + "</tr><td>" + "Pressure" + "</td><td>" + arr.list[i].pressure + "</td><tr>" + "</tr><td>" + "Windspeed" + "</td><td>" + arr.list[i].speed + "</td><tr>" + "</tr><td>" + "Humidity" + "</td><td>" + arr.list[i].humidity + "</td><tr>" + "</tr><td>" + "Predicted Rainfall" + "</td><td>" + arr.list[i].rain + "</td><td>"; } out += "</table>"; document.getElementById("table").innerHTML = out; } function getIcon(s) { return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>"); } </script> <script> //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected! function showHide() { var checkbox = document.getElementById("chkbox"); var hiddenInput = document.getElementsByClassName("hidden"); for(var i = 0; i !=hiddenInput.length; i++) { if(checkbox.checked) { hiddenInput[i].style.display = "inline"; } else { hiddenInput[i].style.display = "none"; } } } </script> </body> </html>
The simplest means of achieving this, given the current approach, is to convert the HTML of the <td> opening tags from: "<tr><td>" to: "<tr><td class='example'>" And then use CSS to style the relevant elements, for example: .example { color: #f90; } Or, once you've assigned the string of innerHTML, you could simply add this line: // retrieves the collection of <td> elements from within the // element with the id of 'table', and uses Array.from() to // convert that collection into an Array. // Then iterates over the array of elements using // Array.prototype.forEach(): Array.from( document.querySelectorAll('#table td') ).forEach(function (td) { // within the anonymous function the 'td' argument is a reference // to the current array-element of the array over which we're // iterating. // here we use the Element.classList API to add the 'example' // class-name to the existing (if any) class-names of the <td> // elements: td.classList.add('example'); }); body { background: white; } h1 { color: black; font-size: 35px; text-align: center; font-family: 'Quicksand', sans-serif; } h2 { font-family: 'Quicksand', sans-serif; margin-left: 3.3em; } table, th , td { border: none; border-collapse: collapse; padding: 15px; margin-left: 5em; margin-top: -25em; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } #form { font-family: 'Quicksand', sans-serif; margin-left: 5em; } #googleMap { margin-left: 45em;; margin-right: auto; } #chkbox_display { margin-left: 5em; margin-top: 3em; font-family: 'Quicksand', sans-serif; } .hidden { display: none; } .example { color: #f90; } <html> <head> <link rel="stylesheet" type="text/css" href="main.css"> <link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'> <title>Weather App</title> </head> <body> <h1>Weather Forecast</h1> <div id="id01"></div> <h2>Please enter the following information:</h2> <form id="form" onsubmit ="return fetchUrl()"> Enter your City:<br> <input id="weather_city" placeholder="Entere here..."><br> How to display values: <br> <select id="weather_scale"> <option value="Metric">Metric Units (Celcius/mm)</option> <option value="Imperial">Imperial Units (Fahrenheit/inch)</option> </select><br> Number of days to show weather:<br> <select id="weather_numberOfDays"> <option value="1">Today only</option> <option value="2">2 days</option> <option value="3">3 days</option> <option value="4">4 days</option> <option value="5">5 days</option> </select> <br><br> <button onclick="initialize">Submit</button> </form> <div id="chkbox_display"> <form action="#"> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Max. Temp.</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Min. Temp</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Rainfall</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Pressure</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Humidity</label> <input type="checkbox" name="chkbox" id="chkbox"/> <label for="chkbox">Wind Speed</label> </form> </div> <script> function initAutocomplete() { weather_city = new google.maps.places.Autocomplete( (document.getElementById('weather_city')), {types: ['geocode']}); weather_city.addListener('place_changed'); } </script> <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script> <script> var longitude; var latitude; function initalize(arr) { var lon = arr.city.coord.lon; var lat = arr.city.coord.lat; var mapProp = { center:new google.maps.LatLng(lat,lon), zoom:10, mapTypeId:google.maps.MapTypeId.ROADMAP } var map=new google.maps.Map(document.getElementById("googleMap"), mapProp); } </script> <div id="googleMap" style="width:600px;height:480px;"></div> <section> <div id="table"> <!-- <tr> <td class="hidden">example</td> <td class="hidden"></td> <td class="hidden"></td> </tr> --> </div> </section> <script> function getJson(request) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", request, true); xmlhttp.send(); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { myFunction(xmlhttp.responseText); } } } function fetchUrl() { var form = document.getElementById("form"); var city = form.weather_city.value; var value = form.weather_scale.value; var days = form.weather_numberOfDays.value; var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days; getJson(url); return false; } function myFunction(response) { var arr = JSON.parse(response); initalize(arr); var i; var out = "<table>"; for(i = 0; i < arr.list.length; i++) { out += "<tr><td>" + new Date(arr.list[i].dt * 1000) + "</td></tr>" + "<tr><td>" + getIcon(arr.list[i].weather[0].icon) + "</td><td>" + arr.list[i].weather[0].description + "</td><tr>" + "</tr><td>" + "Min. Temperature" + "</td><td>" + arr.list[i].temp.min + "</td><tr>" + "</tr><td>" + "Max. Temperature" + "</td><td>" + arr.list[i].temp.max + "</td><tr>" + "</tr><td>" + "Pressure" + "</td><td>" + arr.list[i].pressure + "</td><tr>" + "</tr><td>" + "Windspeed" + "</td><td>" + arr.list[i].speed + "</td><tr>" + "</tr><td>" + "Humidity" + "</td><td>" + arr.list[i].humidity + "</td><tr>" + "</tr><td>" + "Predicted Rainfall" + "</td><td>" + arr.list[i].rain + "</td><td>"; } out += "</table>"; document.getElementById("table").innerHTML = out; Array.from( document.querySelectorAll('#table td') ).forEach(function (td) { td.classList.add('example'); }); } function getIcon(s) { return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>"); } </script> <script> //function to show and hide pressure, humidity, etc.... doesnt work yet. not connected! function showHide() { var checkbox = document.getElementById("chkbox"); var hiddenInput = document.getElementsByClassName("hidden"); for(var i = 0; i !=hiddenInput.length; i++) { if(checkbox.checked) { hiddenInput[i].style.display = "inline"; } else { hiddenInput[i].style.display = "none"; } } } </script> </body> </html> This does, of course, assume that you're correct that you need to append class-names to the elements; with no explanation of the problem you're trying to solve by adding the class-names it's hard to offer better advice.
I suggest you to use 'knockoutjs' for filling in the table by returned Json data. For your purpose it is really suitable. Its absolutely easy to learn. If you interested in this approach you may ask me questions in comments. And i will trying to help you to solve your particular problem. Reference: Knockout tutorial