How to change text of each DIV class indivdually? - sql

I am loading multiple DIV from Database
That my Javascript for click
<script type="text/javascript">
$(document).ready( function() {
var role = 0;
$(".role").click(function(){
if(role == 0)
{
role = 1;
$(".role").text("Decision Approver");
}
else if(role == 1)
{
role = 2;
$(".role").text("Decision Maker");
}
else if(role == 2)
{
role = 3;
$(".role").text("Influencer");
}
else if(role == 3)
{
role = 4;
$(".role").text("Gate Keeper");
}
else if(role == 4)
{
role = 5;
$(".role").text("User");
}
else if(role == 5)
{
role = 6;
$(".role").text("Stake-holder");
}
else if(role == 6)
{
role = 0;
$(".role").text("");
}
});
});
</script>
my CSS for the DIV "role"
{
position: absolute;
width: 50px;
min-height:20px;
height:auto;
border:1px solid #000;
word-wrap: break-word;
float:left;
font-size:12px;
z-index: 30;
margin-top:50px;
margin-left:3px;
}
This is the HTML
$qry = "SELECT * from contact";
$result = mysql_query($qry);
while ($row = mysql_fetch_array($result))
{
<div class="role" align="center" ></div>
}
Multiple DIV has been generated, when I click on one DIV role, all the DIV role change their text. How can I change each DIV individually and update them to database by contactID?

Assuming you want to use jQuery to do this client-side (and on this assumption I've no idea what the SQL is doing in either the tags or the question) I'd suggest using an array to contain the new text:
var textValues = ['Decision maker', 'Decision approver', 'influencer']; // and so forth
$('.role').text(function(i){
return textValues[i];
});
JS Fiddle demo.
The above will iterate over each of the .role elements, the i represents the index of the current element (amongst those other elements in the collection), and will set the text to that contained at the i position within the textValues array.
References:
text().

I think when you are updating the role, all conditions are met one after the other, so you need to include return false; that is similar to break;

Related

Cost Calculator giving wrong calculations

I'm trying to create a cost calculator with 1 dropdown and 2 sliders. Within each choice in the dropdown, it contains 2 different price for each sliders. Both the cost of these 2 sliders add up would give the total cost.
Here is the problem, the cost output is wrong. The output numbers from 2 sliders doesn't add up to the right result. Can anyone help me with this?
Codepen
<style>
.bubble {
background: red;
color: white;
padding: 4px 12px;
position: absolute;
border-radius: 4px;
left: 50%;
transform: translateX(-50%);
}
.bubble::after {
content: "";
position: absolute;
width: 2px;
height: 2px;
background: red;
top: -1px;
left: 50%;
}
.range-wrap {
position: relative;
margin: 0 auto 3rem;
}
.range {
width: 100%;
}
</style>
<h1>WhatsApp Messaging Cost Calculator</h1>
<!-- Dropdown fields for selecting the message type and network provider -->
<label for="message-type">Country:</label>
<select id="message-type" onchange="calculateCost()">
<option value="text" data="text">US</option>
<option value="image" data="image">UK</option>
<option value="audio" data="audio">Europe</option>
</select>
<br>
<!-- Number sliders for selecting the number of messages and size of the message (in KB) -->
<div class="range-wrap">
<label for="num-messages">User-initiated conversation rate:</label>
<input type="range" class="range" min="500" max="10000" value="0" step="10" id="num-messages" oninput="calculateCost(this.value)">
<output class="bubble"></output>
<p>Total Cost: $<span id="output2">0.00</span></p>
</div>
<br>
<div class="range-wrap">
<label for="message-size">Business-initiated conversation rate:</label>
<input type="range" class="range" min="500" max="10000" value="0" step="10" id="message-size" oninput="calculateCost2(this.value)">
<output class="bubble"></output>
<p>Total Cost: $<span id="output3">0.00</span></p>
</div>
<br>
<!-- Live output field for displaying the total cost of the WhatsApp messages -->
<p>Total Cost: $<span id="cost">0.00</span></p>
<script>
function calculateCost(value) {
// Get the selected values from the dropdown fields and number sliders
var messageType = (document.getElementById("message-type").value);
var numMessages = (document.getElementById("num-messages").value);
var messageSize = (document.getElementById("message-size").value);
// Set the base cost based on the message type
var baseCost = 0;
if (messageType == "text") {
baseCost = 0.0088;
baseCost2 = 0.0044;
} else if (messageType == "image") {
baseCost = 0.0388;
baseCost2 = 0.00194;
} else if (messageType == "audio") {
baseCost = 0.022;
baseCost2 = 0.011;
}
numMessages = parseInt(numMessages);
messageSize = parseInt(messageSize);
// Calculate the total cost based on the base cost, number of messages, and message size
var messages = numMessages * baseCost;
var messages2 = messageSize * baseCost2;
var totalCost = messages + messages2;
// Update the live output field with the total cost
document.getElementById("cost").innerHTML = totalCost.toFixed(2);
// Update the output2 element with a different calculation
document.getElementById("output2").innerHTML = value * baseCost;
}
function calculateCost2(value) {
// Get the selected values from the dropdown fields and number sliders
var messageType = (document.getElementById("message-type").value);
var numMessages = (document.getElementById("num-messages").value);
var messageSize = (document.getElementById("message-size").value);
// Set the base cost based on the message type
var baseCost = 0;
if (messageType == "text") {
baseCost = 0.0088;
baseCost2 = 0.0044;
} else if (messageType == "image") {
baseCost = 0.0388;
baseCost2 = 0.00194;
} else if (messageType == "audio") {
baseCost = 0.022;
baseCost2 = 0.011;
}
numMessages = parseInt(numMessages);
messageSize = parseInt(messageSize);
// Calculate the total cost based on the base cost, number of messages, and message size
var messages = numMessages * baseCost;
var messages2 = messageSize * baseCost2;
var totalCost = messages + messages2;
// Update the live output field with the total cost
document.getElementById("cost").innerHTML = totalCost.toFixed(2);
// Update the output2 element with a different calculation
document.getElementById("output3").innerHTML = value * baseCost;
}
function calculateCost3(value) {
// Get the selected values from the dropdown fields and number sliders
var messageType = (document.getElementById("message-type").value);
var numMessages = (document.getElementById("num-messages").value);
var messageSize = (document.getElementById("message-size").value);
// Set the base cost based on the message type
var baseCost = 0;
if (messageType == "text") {
baseCost = 0.0088;
baseCost2 = 0.0044;
} else if (messageType == "image") {
baseCost = 0.0388;
baseCost2 = 0.00194;
} else if (messageType == "audio") {
baseCost = 0.022;
baseCost2 = 0.011;
}
numMessages = parseInt(numMessages);
messageSize = parseInt(messageSize);
// Calculate the total cost based on the base cost, number of messages, and message size
var totalCost = calculateCost + calculateCost2;
// Update the live output field with the total cost
document.getElementById("cost").innerHTML = totalCost.toFixed(2);
}
</script>
<script>
const allRanges = document.querySelectorAll(".range-wrap");
allRanges.forEach(wrap => {
const range = wrap.querySelector(".range");
const bubble = wrap.querySelector(".bubble");
range.addEventListener("input", () => {
setBubble(range, bubble);
});
setBubble(range, bubble);
});
function setBubble(range, bubble) {
const val = range.value;
const min = range.min ? range.min : 0;
const max = range.max ? range.max : 100;
const newVal = Number(((val - min) * 100) / (max - min));
bubble.innerHTML = val;
// Sorta magic numbers based on size of the native UI thumb
bubble.style.left = `calc(${newVal}% + (${8 - newVal * 0.15}px))`;
}
</script>

How to break the line with vue-typer without breaking word

I'm working with vue-typer and it adjusts on screen according to the space. But, depending the size of the screen, the vue-typer breaks the word. I want to break just when we have backspace. The code is:
<vue-typer
class="text-h4 font-weight-bold"
text="Nós acreditamos que o futuro pode ser incrível. Quer criar
ele com a gente?" :repeat='0'
></vue-typer><br>
Here is the image of how is working now
I dont know if anyone is still dealing with this issue, I have written a quick fix to the issue. Its not perfect but does the job.
You will run the text through a Method that will auto add in the line breaks automatically.
<div
style="
font-size: 30pt;
margin: auto;
color: white;
max-width: 600px;
"
ref="theRef"
>
<vue-typer
v-if="startTypers"
:text="[
formatText(
'TextHere',
'theRef',
22
),
]"
:repeat="0"
:shuffle="false"
initial-action="typing"
:pre-type-delay="70"
:type-delay="70"
:pre-erase-delay="2000"
:erase-delay="100"
erase-style="backspace"
:erase-on-complete="false"
caret-animation="blink"
></vue-typer>
</div>
mounted() {
setTimeout(() => {
this.startTypers = true;
}, 150);
}
The reason for the startTypers is because they will run the formatText method before the div has been rendered. Meaning you won't be able to get the clientWidth of the parent div.
formatText(text, ref, textSize = 22) {
let maxChars = Math.floor(this.$refs[ref].clientWidth / textSize);
let words = text.split(" ");
let breaked = "";
let currentCount = 0;
words.forEach((word) => {
currentCount += word.length;
currentCount += 1;
if (currentCount >= maxChars) {
currentCount = word.length;
breaked = `${breaked}\n${word} `;
} else {
breaked = `${breaked}${word} `;
}
});
return breaked;
},
The Parameters for formatText are the Text that you want to have the line breaks added in, The name of the ref, and the size of the span(Chars) that is rendered (22 was the default for the font and font-size I used in my use case, yours will vary)
Hopefully this helps
In order to break the text into chunks, consider the following
data() {
text : 'Hello World! I`m clarification masterjam!',
},
computed : {
textComputed() {
let n = "\n"
let breaked = this.text.match(/.{1,25}/g);
breaked[0];
var pos = breaked[0].lastIndexOf(' ');
breaked[0] = breaked[0].substring(0,pos)+n+breaked[0].substring(pos+1);
return breaked.join('')
},
}

Cannot get aurelia-interactjs plugin to work using Aurelia CLI

I'm trying out the aurelia-interactjs plugin to see if it meets my needs. I installed it into a new aurelia cli project by following all of the installation steps. I then added code for the Dragging section of the interactjs demo. The browser console displays the following error stating that interact is not a function:
Unhandled rejection TypeError: interact is not a function. (In 'interact(this.element)', 'interact' is undefined)
attached#http://localhost:9005/node_modules/aurelia-interactjs/dist/amd/interact-draggable.js:18:21
Here's my code:
app.html
<template>
<div id="drag-1" interact-draggable.bind="interactjsOptions">
<p> You can drag one element </p>
</div>
<div id="drag-2" interact-draggable.bind="interactjsOptions">
<p> with each pointer </p>
</div>
</template>
app.js
export class App {
constructor() {
this.interactjsOptions = {
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: {
top: 0,
left: 0,
bottom: 1,
right: 1
}
},
// enable autoScroll
autoScroll: true,
// call this function on every dragmove event
onmove: dragMoveListener,
// call this function on every dragend event
onend: function(event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of ' +
(Math.sqrt(event.dx * event.dx +
event.dy * event.dy) | 0) + 'px');
}
};
}
}
function dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
I am sorry, wrote the above in the bus on my commute to work on my phone didn't read all the code :-)
If you want to have the basic draggable sample (first one from http://interactjs.io/), which allows you to just drag elements around:
app.css
.draggable {
width: 25%;
height: 100%;
min-height: 6.5em;
margin: 10%;
background-color: #29e;
color: white;
border-radius: 0.75em;
padding: 4%;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
}
app.html
<template>
<require from="app.css"></require>
<div
interact-draggable.bind="interactOptions"
interact-dragend.delegate="dragEnd($event)"
interact-dragmove.delegate="dragMoveListener($event)"
class="draggable">
<p> You can drag one element </p>
</div>
<div
interact-draggable.bind="interactOptions"
interact-dragend.delegate="dragEnd($event)"
interact-dragmove.delegate="dragMoveListener($event)"
class="draggable">
<p> with each pointer </p>
</div>
</template>
app.ts (if you remove the public keyword in the function it will be valid js I think)
export class App {
public dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.detail.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.detail.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
public dragEnd(event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of '
+ (Math.sqrt(event.detail.dx * event.detail.dx +
event.detail.dy * event.detail.dy)|0) + 'px');
}
public interactOptions = {
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
// enable autoScroll
autoScroll: true,
};
}

How to trigger OnChange Event of Radio Button when its UnChecked

I have a HTML table with rows and columns of course. There are radio buttons in each row and each row is one group of radio buttons means I can select only ONE radio button in the row from all the columns. I am trying to set a CSS on selection of a radio button cell in my table, this is fine but When I move to another radio button in the same row, being a radio button group the previous radio button is de-selected but the CSS remains there, because on selecting another radio in the group doesn't trigger the OnChange event for the radio which got de-selected automatically.
Is there any way to trigger onChange event on de-selecting the radio?
How about this: http://jsfiddle.net/2Z8Nt/14/
JS
$(function () {
// Create table and radios
for (var tri = 0; tri < 3; tri++) {
var $tr = $('<tr>').appendTo('table');
var $td = $('<td>').appendTo($tr);
for (var rai = 0; rai < 3; rai++) {
var $sp = $('<span class="radio-holder">');
var $rd = $('<input type="radio" name="rad-' + tri + '" class="rad" value="val-' + rai + '"/>').appendTo($sp);
$sp.append('Radio ' + tri + '' + rai);
$td.append($sp);
$tr.append($td);
}
}
// Record to keep track of radio selection
var selrad = {};
// Handler
$('input.rad').on('deselect', function () {
$(this).parents('.radio-holder').addClass('just-deselected')
}).each(function () {
$(this).on('click', function () {
var nm = $(this).attr('name');
$('input[name="' + nm + '"').parents('.radio-holder').removeClass('just-deselected');
if (selrad[nm]) {
selrad[nm].trigger('deselect');
}
selrad[nm] = $(this);
})
});
})
CSS
.radio-holder {
border: 1px solid silver;
margin: 3px;
padding: 3px;
}
.radio-holder.just-deselected {
border: 1px solid red;
}

jQuery - Animation content inside a div when it becomes the current container on a horizontal slider

The Setup I have a full screen horizontal slider with 5+ divs that moves to the left when you click on an anchor link. I have some basic knowledge of jquery, and did attempted to use (scrollLeft). But the div is the wrapper div is hiding over flow and doesn't really go anywhere.
The goal is to animate the content inside the container div when it becomes the current container, and undo animation when it does to a different div.
The Issue: I got the animation to play, but have no control over when it starts.
The HTML
<div class="contentItem" id="content2">
<div id="top-box"></div>
<div id="bottom-box"></div>
</div>
<div class="contentItem" id="content3"></div>
<div class="contentItem" id="content4"></div>
<div class="contentItem" id="content5"></div>
The javascript
var theWidth;
var theHeight;
var currentContent = 0;
$(window).resize(function () {
sizeContent();
});
$(window).ready(function () {
sizeContent();
});
function sizeContent() {
theWidth = $(window).width();
theHeight = $(window).height();
sizeContentItems();
setLeftOnContentItems();
sizeContentWrapper(theWidth, theHeight);
moveContent(currentContent, theWidth);
changeSelected(currentContent);
}
function sizeContentItems() {
$(".contentItem").css('width', theWidth);
$(".contentItem").css('height', theHeight);
}
function setLeftOnContentItems() {
var contentCount = 0;
$(".contentItem").each(function (i) {
contentCount += i;
$(this).css('left', i * 990); //slider contern hight
});
}
function sizeContentWrapper(width, height) {
$("#contentWrapper").css('width', width);
$("#contentWrapper").css('height', height);
}
function moveContent(i, width) {
$("#contentWrapper").scrollLeft(i * width);
}
function changeSelected(i) {
$(".selected").removeClass("selected");
$("li:eq(" + i + ") a").addClass("selected");
}
function scrollContentNext() {
scrollContent(currentContent + 1);
}
function scrollContent(i) {
i = checkMax(i);
scrollLogo(i);
scrollTriangle(i);
changeSelected(i)
currentContent = i;
$("#contentWrapper").animate({ scrollLeft: i * 990 }, 400); // how far to go
}
function scrollLogo(i) {
var left = (i * +200);
$("#logo").animate({ left: left }, 1000);
}
function scrollTriangle(i) {
var left = (i * -300);
$("#triangle").animate({ left: left }, 700);
}
// **my edit**
function scrollbox(i) {
var i = currentContent;
if ( currentContent = 2) {
$("#bottom-box").stop().animate({'margin-top': '200px'}, 1500);
}
}
function checkMax(i) {
var maxItems = $("li").length;
if (i >= maxItems) {
return 0;
}
return i;
}