How to disable div(s) until previous div has been filled in - javascript

I'm currently making a drag and drop quiz, as a start I have four questions in which answers can be picked up and dropped into the corresponding question. I want to disable the drop box for questions 2,3,4 until question 1 is answered. Then re-active q2 leaving 3,4 disabled and so on.... I'm quite new to JavaScript and have tried multiple ways to do this, including looking at other situations similar to mine on here but have yet succeeded! I have put a screenshot of the quiz so far which will hopefully make it clearer.
Hopefully someone can help, thanks!
All my code is below:
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="draganddrop.js"></script>
</head>
<body>
<div id="container">
<h1>SAN Failure</h1>
<p>Your SAN's RAID controller has failed and corrupted a significant amount of data. You need to contact your DR provider failover to your recovery environment whilst you restore your internal servers from backup images.</p>
</div>
<div id="mainContainer">
<div id="dragScriptContainer">
<div id="questionDiv">
<p><strong>Task one: Damage Control</strong></p>
<div class="dragDropSmallBox textbox" id="q1">1. Find the relevant IP address for the affected hardware</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox" id="q2">2. Notify your disaster recovery provider</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox" id="q3">3. Inform the team of directors of the situation</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox disabled="true"" id="q4">4. Update the emergency phone message</div><div class="destinationBox"></div>
</div>
<div class="feedback">
<div id="feedback"></div>
<div id="counter">0</div>
<div id="result"></div>
</div>
<div class="container">
<h1 style="text-align:center">Disaster Recovery Runbook</h1>
<!-- Page 1 -->
<h5 style="color: red; ">Page 1</h5>
<h2>Executive Summary</h2>
<p>[ACME Ltd. company information]<br>ACME Ltd. currently has 9 virtual servers and 4 physical servers all hosted at an onsite data centre.<br>The key IT staff required for recovery are [IT Manager], [Backup Manager] and [Disaster Recovery Provider]. The servers must be recovered within 8 hours of invocation.
</p>
<!-- Page 2 -->
<h5 style="color: red; ">Page 2</h5>
<h2>Contents</h2>
<p><strong>
Invoking Disaster Recovery<br>
Key Contacts<br>
Call Tree<br>
Emergency Phone Message<br>
Network Diagram<br>
Recovery Locations<br>
Software License and Registration Keys<br>
Event Log<br>
Recovery Templates
</strong></p>
<!-- Page 3 -->
<h5 style="color: red; ">Page 3</h5>
<h2>Invoking Disaster Recovery</h2>
<p>If a crisis or disaster has occurred, the business continuity manager must decide the course of action. If, for whatever reason, the business continuity manager is unable to perform these duties, refer to the cascading decision-making hierarchy below.<br>Only the most senior member is authorized to invoke the DR plan, subject to availability.<br>1. Business Continuity Manager<br>2. IT Director<br>3. IT Manager<br>4. IT Administrator<br>In the event none of the stated staff members are available...good luck.</p>
<div id="answerDiv">
<!-- Page 4 -->
<h5 style="color: red; ">Page 4</h5>
<h2>Key Contacts</h2>
<main class="flex-center">
<table>
<tr>
<td><p><strong>Contact</strong></p></td>
<td><p><strong>Telephone Number</strong></p></td>
<td><p><strong>Email Address</strong></p></td>
</tr>
<tr>
<td><p>Managing Director</p></td>
<td><div class="dragDropSmallBox" id="a3">0123456789</div></td>
<td><div class="dragDropSmallBox" id="a10">M.D#acme.com</div></td>
</tr>
<tr>
<td><p>Financial Director</p></td>
<td><div class="dragDropSmallBox" id="a10">1234567890</div></td>
<td><div class="dragDropSmallBox" id="a10">F.D#acme.com</div></td>
</tr>
<tr>
<td><p>Business Continuity Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">2345678901</div></td>
<td><div class="dragDropSmallBox" id="a10">B.C.D#acme.com</div></td>
</tr>
<tr>
<td><p>Sales Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">3456789012</div></td>
<td><div class="dragDropSmallBox" id="a10">S.M#acme.com</div></td>
</tr>
<tr>
<td><p>Production Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">4567890123</div></td>
<td><div class="dragDropSmallBox" id="a10">P.M#acme.com</div></td>
</tr>
<tr>
<td><p>HR Director</p></td>
<td><div class="dragDropSmallBox" id="a10">5678901234</div></td>
<td><div class="dragDropSmallBox" id="a10">H.R.D#acme.com</div></td>
</tr>
<tr>
<td><p>Backup Manger</p></td>
<td><div class="dragDropSmallBox" id="a10">6789012345</div></td>
<td><div class="dragDropSmallBox" id="a10">B.M#acme.com</div></td>
</tr>
<tr>
<td><p>Power Supplier</p></td>
<td><div class="dragDropSmallBox" id="a10">7890123456</div></td>
<td><div class="dragDropSmallBox" id="a10">P.S#acme.com</div></td>
</tr>
<tr>
<td><p>Internet Supplier</p></td>
<td><div class="dragDropSmallBox" id="a10">8901234567</div></td>
<td><div class="dragDropSmallBox" id="a10">I.S#acme.com</div></td>
</tr>
<tr>
<td><p>Disaster Recovery Supplier</p></td>
<td><div class="dragDropSmallBox" id="a2">9012345678</div></td>
<td><div class="dragDropSmallBox" id="a10">D.R.S#acme.com</div></td>
</tr>
</table>
</main>
<!-- Page 5 -->
<h5 style="color: red; ">Page 5</h5>
<h2>Call Tree</h2>
<img class="callTree" src="img/call_tree.jpg">
<!-- Page 6 -->
<h5 style="color: red; ">Page 6</h5>
<h2>Emergency Phone Message</h2>
<p>We have distributed emergency call cards to staff, containing the number for an emergency phone line in a disaster. You should update this message to alert your staff members to the presence of a disastrous event, and every time there is a change in circumstances - either towards or away from resolution.<br> To update the message call the number below:</p>
<div class="dragDropSmallBox" id="a4">UPDATE EMERGENCY PHONE LINE</div><br><br>
<!-- Page 7 -->
<h5 style="color: red; ">Page 7</h5>
<h2>Network Diagram with Service Information</h2>
<main class="flex-center">
<table>
<tr>
<td><p><strong>Service</strong></p></td>
<td><p><strong>IP Address</strong></p></td>
</tr>
<tr>
<td><p>Email</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.1</div></td>
</tr>
<tr>
<td><p>Web Server</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.2</div></td>
</tr>
</tr>
<tr>
<td><p>MPLS</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.3</div></td>
</tr>
<tr>
<td><p>VoIP</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.4</div></td>
</tr>
<tr>
<td><p>SAN Server</p></td>
<td><div class="dragDropSmallBox" id="a1">192.0.0.5</div></td>
</tr>
<tr>
<td><p>CRM Server</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.6</div></td>
</tr>
</table>
</main>
</div>
<div id="dragContent"></div>
</div>
</div>
</div>
<div id="buttons">
<input type="button" onclick="dragDropResetForm();return false" value="Reset">
<input type="button" onclick="clearFields();" id="clear" value="Clear">
<input type="button" onclick="showResults();" id="result" value="Result">
</div>
</body>
</html>
JAVASCRIPT:
var shuffleQuestions = true;
var shuffleAnswers = false;
var lockedAfterDrag = true;
function quizIsFinished()
{
alert('Finished!');
}
var dragContentDiv = false;
var dragContent = false;
var dragSource = false;
var dragDropTimer = -1;
var destinationObjArray = new Array();
var destination = false;
var dragSourceParent = false;
var dragSourceNextSibling = false;
var answerDiv;
var questionDiv;
var sourceObjectArray = new Array();
var arrayOfEmptyBoxes = new Array();
var arrayOfAnswers = new Array();
function getTopPos(inputObj)
{
if(!inputObj || !inputObj.offsetTop)return 0;
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue;
}
function getLeftPos(inputObj)
{
if(!inputObj || !inputObj.offsetLeft)return 0;
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
function cancelEvent()
{
return false;
}
function initDragDrop(e)
{
if(document.all)e = event;
if(lockedAfterDrag && this.parentNode.parentNode.id=='questionDiv')return;
dragContentDiv.style.left = e.clientX + Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + 'px';
dragContentDiv.style.top = e.clientY + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + 'px';
dragSource = this;
dragSourceParent = this.parentNode;
dragSourceNextSibling = false;
if(this.nextSibling)dragSourceNextSibling = this.nextSibling;
if(!dragSourceNextSibling.tagName)dragSourceNextSibling = dragSourceNextSibling.nextSibling;
dragDropTimer=0;
timeoutBeforeDrag();
return false;
}
function timeoutBeforeDrag(){
if(dragDropTimer>=0 && dragDropTimer<10){
dragDropTimer = dragDropTimer +1;
setTimeout('timeoutBeforeDrag()',10);
return;
}
if(dragDropTimer>=10){
dragContentDiv.style.display='block';
dragContentDiv.innerHTML = '';
dragContentDiv.appendChild(dragSource);
}
}
function dragDropMove(e)
{
if(dragDropTimer<10){
return;
}
if(document.all)e = event;
var scrollTop = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
dragContentDiv.style.left = e.clientX + scrollLeft + 'px';
dragContentDiv.style.top = e.clientY + scrollTop + 'px';
var dragWidth = dragSource.offsetWidth;
var dragHeight = dragSource.offsetHeight;
var objFound = false;
var mouseX = e.clientX + scrollLeft;
var mouseY = e.clientY + scrollTop;
destination = false;
for(var no=0;no<destinationObjArray.length;no++){
var left = destinationObjArray[no]['left'];
var top = destinationObjArray[no]['top'];
var width = destinationObjArray[no]['width'];
var height = destinationObjArray[no]['height'];
destinationObjArray[no]['obj'].className = 'destinationBox';
var subs = destinationObjArray[no]['obj'].getElementsByTagName('DIV');
if(!objFound && subs.length==0){
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destinationObjArray[no]['obj'].className='dragContentOver';
destination = destinationObjArray[no]['obj'];
objFound = true;
}
}
}
sourceObjectArray['obj'].className='';
if(!objFound){
var left = sourceObjectArray['left'];
var top = sourceObjectArray['top'];
var width = sourceObjectArray['width'];
var height = sourceObjectArray['height'];
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destination = sourceObjectArray['obj'];
sourceObjectArray['obj'].className='dragContentOver';
}
}
return false;
}
function dragDropEnd()
{
if(dragDropTimer<10){
dragDropTimer = -1;
return;
}
dragContentDiv.style.display='none';
sourceObjectArray['obj'].style.backgroundColor = '#FFF';
if(destination){
destination.appendChild(dragSource);
destination.className='destinationBox';
if(!destination.id || destination.id!='answerDiv'){
var previousEl = dragSource.parentNode.previousSibling;
if(!previousEl.tagName)previousEl = previousEl.previousSibling;
var numericId = previousEl.id.replace(/[^0-9]/g,'');
var numericIdSource = dragSource.id.replace(/[^0-9]/g,'');
if(numericId==numericIdSource){
dragSource.className='correctAnswer';
checkAllAnswers();
}
else
dragSource.className='wrongAnswer';
}
if(destination.id && destination.id=='answerDiv'){
dragSource.className='dragDropSmallBox';
}
} else{
if(dragSourceNextSibling)
dragSourceNextSibling.parentNode.insertBefore(dragSource,dragSourceNextSibling);
else
dragSourceParent.appendChild(dragSource);
}
if(numericId==numericIdSource) {
document.getElementById('feedback').innerHTML = "";
document.getElementById('feedback').innerHTML += 'Correct Answer!';
}
else {
document.getElementById('feedback').innerHTML = "";
document.getElementById('feedback').innerHTML += 'Incorrect Answer! Have you tried this...';
incrementScore();
}
dragDropTimer = -1;
dragSourceNextSibling = false;
dragSourceParent = false;
destination = false;
}
function checkAllAnswers()
{
for(var no=0;no<arrayOfEmptyBoxes.length;no++){
var sub = arrayOfEmptyBoxes[no].getElementsByTagName('DIV');
if(sub.length==0)return;
if(sub[0].className!='correctAnswer'){
return;
}
}
quizIsFinished();
}
function resetPositions()
{
if(dragDropTimer>=10)return;
for(var no=0;no<destinationObjArray.length;no++){
if(destinationObjArray[no]['obj']){
destinationObjArray[no]['left'] = getLeftPos(destinationObjArray[no]['obj'])
destinationObjArray[no]['top'] = getTopPos(destinationObjArray[no]['obj'])
}
}
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
}
function initDragDropScript()
{
dragContentDiv = document.getElementById('dragContent');
answerDiv = document.getElementById('answerDiv');
answerDiv.onselectstart = cancelEvent;
var divs = answerDiv.getElementsByTagName('DIV');
var answers = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='dragDropSmallBox'){
divs[no].onmousedown = initDragDrop;
answers[answers.length] = divs[no];
arrayOfAnswers[arrayOfAnswers.length] = divs[no];
}
}
if(shuffleAnswers){
for(var no=0;no<(answers.length*10);no++){
var randomIndex = Math.floor(Math.random() * answers.length);
answerDiv.appendChild(answers[randomIndex]);
}
}
sourceObjectArray['obj'] = answerDiv;
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
sourceObjectArray['width'] = answerDiv.offsetWidth;
sourceObjectArray['height'] = answerDiv.offsetHeight;
questionDiv = document.getElementById('questionDiv');
questionDiv.onselectstart = cancelEvent;
var divs = questionDiv.getElementsByTagName('DIV');
var questions = new Array();
var questionsOpenBoxes = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='destinationBox'){
var index = destinationObjArray.length;
destinationObjArray[index] = new Array();
destinationObjArray[index]['obj'] = divs[no];
destinationObjArray[index]['left'] = getLeftPos(divs[no])
destinationObjArray[index]['top'] = getTopPos(divs[no])
destinationObjArray[index]['width'] = divs[no].offsetWidth;
destinationObjArray[index]['height'] = divs[no].offsetHeight;
questionsOpenBoxes[questionsOpenBoxes.length] = divs[no];
arrayOfEmptyBoxes[arrayOfEmptyBoxes.length] = divs[no];
}
if(divs[no].className=='dragDropSmallBox'){
questions[questions.length] = divs[no];
}
}
if(shuffleQuestions){
for(var no=0;no<(questions.length*10);no++){
var randomIndex = Math.floor(Math.random() * questions.length);
questionDiv.appendChild(questions[randomIndex]);
questionDiv.appendChild(questionsOpenBoxes[randomIndex]);
destinationObjArray[destinationObjArray.length] = destinationObjArray[randomIndex];
destinationObjArray.splice(randomIndex,1);
questionsOpenBoxes[questionsOpenBoxes.length] = questionsOpenBoxes[randomIndex];
questionsOpenBoxes.splice(randomIndex,1);
questions[questions.length] = questions[randomIndex];
questions.splice(randomIndex,1);
}
}
questionDiv.style.visibility = 'visible';
answerDiv.style.visibility = 'visible';
document.documentElement.onmouseup = dragDropEnd;
document.documentElement.onmousemove = dragDropMove;
setTimeout('resetPositions()',150);
window.onresize = resetPositions;
}
function incrementScore(){
counter = document.getElementById('counter');
counter.innerHTML++;
}
function showResults() {
result = document.getElementById('result');
if(counter.innerHTML < 2){
result.innerHTML += 'Well done!';
} else {
result.innerHTML += 'Not so great!';
}
}
/* Reset the form */
function dragDropResetForm()
{
for(var no = 0; no < arrayOfAnswers.length; no++){
arrayOfAnswers[no].className='dragDropSmallBox'
answerDiv.appendChild(arrayOfAnswers[no]);
}
document.getElementById('score').innerHTML = "";
}
function clearFields() {
document.getElementById("questionDiv").innerHTML = "";
}
window.onload = initDragDropScript;

I suggest you use jQueryUI draggable and droppable interactions to achieve what you want. They contain many methods and events which you can use, for example you can easily disable a droppable object by using $( ".selector" ).droppable( "disable" );. You can also save yourself the trouble of creating methods for dragging the elements.

I have create a very basic example that should help you out, however it can be improved :)
jsFiddle : https://jsfiddle.net/CanvasCode/hoeh0hds/1/
html
<input id="input1" />
<br />
<input id="input2" />
<br />
<input id="input3" />
<br />
<input id="input4" />
<br />
Javascript
document.getElementById('input2').disabled = true;
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
inputs[index].addEventListener('input', function () {
// Input 1
if (this == document.getElementById('input1')) {
if (this.value.length) {
document.getElementById('input2').disabled = false;
} else {
document.getElementById('input2').disabled = true;
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
}
}
// Input 2
if (this == document.getElementById('input2')) {
if (this.value.length) {
document.getElementById('input3').disabled = false;
} else {
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
}
}
// Input 3
if (this == document.getElementById('input3')) {
if (this.value.length) {
document.getElementById('input4').disabled = false;
} else {
document.getElementById('input4').disabled = true;
}
}
});
}

Try removing the onmouseup and onmousedown eventlisteners till the div is ready for activity. The syntax below should work for that
document.getElementById("myDIV").removeEventListener("mouseup", dragDropEnd)
document.getElementById("myDIV").removeEventListener("mousedown", dragDropMove)

Related

How I get values updating/refreshing related input areas in Javascript?

I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?
My code is in JSFiddle UPDATED !!
My Javascript are:
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('ht')[0].value;
var input_name_last = document.getElementsByName('ft')[0].value;
var input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
<script type="text/javascript">
function myFunctionFt() {
var home = document.getElementById("home_score").value;
var away = document.getElementById("away_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ft").value = results;
}
</script>
<script type="text/javascript">
function myFunctionHt() {
var home = document.getElementById("home_ht_score").value;
var away = document.getElementById("away_ht_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ht").value = results;
}
</script>
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.
Here is the final working code:
//FT and HT Result//
let name_first = document.getElementById('ht');
let name_last = document.getElementById('ft');
let input_name_first = name_first.value;
let input_name_last = name_last.value;
//HT Home//
let home = document.getElementById("home_ht_score");
let away = document.getElementById("away_ht_score");
home_ht_score.addEventListener("input", myFunctionHt);
away_ht_score.addEventListener("input", myFunctionHt);
let input_away = away.value;
let input_home = home.value;
//FT Home//
let home_ft = document.getElementById("home_score");
let away_ft = document.getElementById("away_score");
home_score.addEventListener("input", myFunctionFt);
away_score.addEventListener("input", myFunctionFt);
let input_ft_away = away_ft.value;
let input_ft_home = home_ft.value;
function myFunctionHt() {
input_away = away.value;
input_home = home.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_home && !input_away) return;
var results = "";
if (input_home > input_away) {
results = "1";
} else if (input_home < input_away) {
results = "2";
} else if (input_home = input_away) {
results = "X";
}
document.getElementById("ht").value = results;
join_names();
}
function myFunctionFt() {
input_ft_away = away_ft.value;
input_ft_home = home_ft.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_ft_home && !input_ft_away) return;
var results = "";
if (input_ft_home > input_ft_away) {
results = "1";
} else if (input_ft_home < input_ft_away) {
results = "2";
} else if (input_ft_home = input_ft_away) {
results = "X";
}
document.getElementById("ft").value = results;
join_names();
}
function join_names() {
if (!input_name_first && !input_name_last) return;
let input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(name_first.value, name_last.value, true);
input_name_full.value = var_name_full;
}
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
<table border="0" cellpadding="1">
<tbody>
<tr>
<td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
<td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
<td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
<td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
<td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
<td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
<td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
<td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>
</tr>
<tr>
<td> </td>
<td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

How to properly distribute js code for php foreach?

Have php foreach in file
<?php
foreach($_SESSION['cart'] as $item):
$sqlcartprod = mysqli_query(db(),"SELECT * FROM products WHERE id='".$item['product']."' ");
$rowcartprod = mysqli_fetch_array($sqlcartprod);
?>
<tr>
<td class="shoping__cart__item">
<img src="<?=$rowcartprod['ikonka']?>" width="101" alt="">
<h5><?=$rowcartprod['name_'.$lang]?></h5>
</td>
<td class="shoping__cart__price" >
<span id="priceprod"><?=$rowcartprod['price']?></span> azn
</td>
<td class="shoping__cart__quantity">
<div class="quantity">
<div class="pro-qty">
<input type="text" style="cursor: default" readonly value="<?=$item['qty']?>">
</div>
</div>
</td>
<td class="shoping__cart__total" id="totalprice">
<?=$item['price']*$item['qty']?> azn
</td>
</tr>
<?php endforeach; ?>
for this piece of code:
<div class="quantity">
<div class="pro-qty">
<input type="text" style="cursor: default" readonly value="<?=$item['qty']?>">
</div>
</div>
have JS code:
var proQty = $('.pro-qty');
proQty.prepend('<span class="dec qtybtn">-</span>');
proQty.append('<span class="inc qtybtn">+</span>');
proQty.on('click', '.qtybtn', function () {
var $button = $(this);
var oldValue = $button.parent().find('input').val();
if ($button.hasClass('inc')) {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find('input').val(newVal);
var Price = document.getElementById('priceprod').innerText;
var Tprice = document.getElementById('totalprice');
if (Price[i] > 0) {
Tprice.textContent = (Price[i] * newVal) + ' azn';
}
});
The issue is that when I click on qtybtn + or qtybtn -, the js code works only for the first product in the shopping list, even if there are 2,3 or more products in the list. I tried to separate inside the js code with loops, but then the js code somehow stops working at all. How to distribute correctly so that the js code works for each product separately?

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

php codeigniter - managing values in multi select box

I am working on a multibox as a part of my codeigniter based project, here I am trying to move the values across the boxes using custom js code shared below
The values shown in first box are fetched from db when page loads and used to move the required values to second box using javascript. My goal it that the values already moved to second box should not be visible in the first box after saving the data and at the same time source data for the first box should not be altered.
Right now I am able to select the values to second box and save successfully but when I load the page again after saving I am seeing the moved values in the fist box and this is visually creating duplication of values and would confuse the user. On the other hand if I try to move back the values to the first box which is creating a conflict while saving the data.
Is there any way I could change my code so that moved values will not be available in the first box again
HTML version of multibox
<fieldset class="emp_contact">
<legend>Area Allocation</legend>
<div class="form-group input-group">
<table width="100%" border="0" cellpadding="10" cellspacing="10" style="border:1px solid #ccc">
<tr>
<td width="40%">
<p>Available Areas</p>
</td>
<td width="12%"> </td>
<td width="40%">
<p>Selected Areas</p>
</td>
</tr>
<tr>
<td valign="top" id="myarea_list">
<?php echo $aval_area_list ?>
</td>
<select name="aval_id_temp" id="aval_id_temp" multiple style="display:none"></select>
<td>
<table width="100%" border="0">
<tr>
<td align="center">
<input type="Button" value=">>" onClick="SelectMoveRows_all(document.form.avail_area, document.form.selec_area)">
<br>
<br />
<input type="Button" value=">" onClick="SelectMoveRows(document.form.avail_area, document.form.selec_area)">
<br>
<br>
<input type="Button" value="<<" onClick="SelectMoveRows_all(document.form.selec_area, document.form.avail_area)">
<br>
<br>
<input type="Button" value="<" onClick="SelectMoveRows(document.form.selec_area, document.form.avail_area)">
</td>
</tr>
<tr>
<td align="center"> </td>
</tr>
</table>
</td>
<td valign="top">
<?php echo $sel_area_list ?>
<select name="sel_id_temp" id="sel_id_temp" multiple style="display:none"></select>
</td>
</tr>
</table>
</div>
</fieldset>
Javascript functions used
function SelectMoveRows_all(SS1, SS2) {
var SelID = '';
var SelText = '';
// Move rows from SS1 to SS2 from bottom to top
for (i = SS1.options.length - 1; i >= 0; i--) {
//if (SS1.options[i].selected == true)
{
SelID = SS1.options[i].value;
SelText = SS1.options[i].text;
var newRow = new Option(SelText, SelID);
SS2.options[SS2.length] = newRow;
SS1.options[i] = null;
for (j = SS2.options.length - 1; j >= 0; j--) {
SS2.options[j].selected = true;
}
}
}
SelectSort(SS2);
}
function SelectMoveRows(SS1, SS2) {
var SelID = '';
var SelText = '';
// Move rows from SS1 to SS2 from bottom to top
for (i = SS1.options.length - 1; i >= 0; i--) {
if (SS1.options[i].selected == true) {
SelID = SS1.options[i].value;
SelText = SS1.options[i].text;
var newRow = new Option(SelText, SelID);
SS2.options[SS2.length] = newRow;
SS1.options[i] = null;
for (j = SS2.options.length - 1; j >= 0; j--) {
SS2.options[j].selected = true;
}
}
}
SelectSort(SS2);
}
function SelectSort(SelList) {
var ID = '';
var Text = '';
for (x = 0; x < SelList.length - 1; x++) {
for (y = x + 1; y < SelList.length; y++) {
if (SelList[x].text > SelList[y].text) {
// Swap rows
ID = SelList[x].value;
Text = SelList[x].text;
SelList[x].value = SelList[y].value;
SelList[x].text = SelList[y].text;
SelList[y].value = ID;
SelList[y].text = Text;
}
}
}
}

Darts game - checking problems in AngularJS

There is the content of my AngularJS (JavaScript ) file:
// define new Angular module
var myApp = angular.module('myApp',[]);
myApp.controller('MyAppController',function($scope){
$scope.player = '';
$scope.players = [];
$scope.totalPoints = [];
$scope.flag = 1;
$scope.myNumberRegex = /[0-9]/;
$scope.last = {};
$scope.score = {};
$scope.winner = 0;
$scope.nextPlayer = '';
$scope.nextRound = false;
var actualPlayer = 0;
var pointsValue,round = 0;
var internalRoundCounter = 1;
var shootsString = '';
$scope.$watch('roundCount',function(value){
console.log('new value',value);
});
$scope.add = function(){
$scope.players.push({name: $scope.player, totalPoints: 0, fields:[]});
$scope.player = '';
};
$scope.checkForm = function() {
var valid = true;
if ($scope.players.length == 0) {
alert('There is no player added!');
valid = false;
}
if ($scope.roundCount < 3 || $scope.roundCount > 10) {
alert('Incorrect round count!');
valid = false;
}
if ($scope.players.length == 1) {
console.log('Tömb hossza: ', $scope.players.length);
alert('One player is not enough!');
valid = false;
}
if (valid) {
$scope.flag = 2;
var startingPlayer = $scope.players[actualPlayer].name;
$scope.nextPlayer = startingPlayer;
}
};
function showResults(){
$scope.flag = 3;
}
// watching changed value
$scope.$watch('last.id',function(newValue){
console.log('last.id changed',newValue);
pointsValue = 0;
//-----------------------------------------------------------
// checking target to calculate earned points
//-----------------------------------------------------------
if (newValue == "Bull") {
pointsValue += 50;
console.log(pointsValue);
}
else if (newValue == "Outer") {
pointsValue += 25;
console.log(pointsValue);
}
else if (['s','d','t'].indexOf(newValue[0]) != -1) {
var multiplier = 1;
if (newValue[0] == 'd')
multiplier = 2;
else if (newValue[0] == 't')
multiplier = 3;
var tmp = newValue.split("").splice(1,2).join("");
pointsValue += (tmp * multiplier);
}
//-----------------------------------------------------------
// while playing darts
if (round < $scope.roundCount) {
if (internalRoundCounter < 4){
shootsString += newValue+' ';
$scope.players[actualPlayer].totalPoints += pointsValue;
internalRoundCounter++;
}
else{
$scope.players[actualPlayer].fields.push({fieldId : round+1, fieldName : shootsString});
shootsString = '';
internalRoundCounter = 1;
actualPlayer++;
if (actualPlayer == $scope.players.length) {
actualPlayer = 0;
round++;
}
$scope.nextPlayer = $scope.players[actualPlayer].name;
}
}
// when game finished
else{
showResults();
$scope.winner = $scope.players[0].name;
// find winner in array
for (var i=1; i<$scope.players.length; i++){
if ($scope.players[i].totalPoints > $scope.players[i-1].totalPoints){
$scope.winner = $scope.players[i].name;
}
}
console.log($scope.players);
}
});
});
myApp.directive('dartClickListener', function() {
return {
restrict: 'A',
scope: false,
link: function(scope,element,attrs) {
console.log(angular.element(element));
angular.element(element).find('g').children().bind('click',function(){
console.log(angular.element(this).attr('id'));
scope.last.id = angular.element(this).attr('id');
scope.$apply();
});
}
}
});
<!DOCTYPE html>
<html ng-app="myApp" ng-init="roundCount=3">
<head lang="en">
<meta charset="UTF-8">
<title>.:: Darts ::.</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="myscript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MyAppController">
<div id="start" ng-show="flag == 1">
<div>
<h1 class="stdCell gameTitle">Darts</h1>
</div>
<div>
<table>
<tr>
<td><label class="stdCell" for="playerName">Add player</label></td>
<td><input type="text" id="playerName" ng-model="player"></td>
<td><input type="button" value="Add" ng-click="add()" ng-disabled="!(!!player)"></td>
</tr>
<tr>
<td><label class="stdCell" for="rounds">Rounds (3-10) </label></td>
<td colspan="2"><input type="text" id="rounds" ng-model="roundCount" ng-pattern="myNumberRegex" ng-required="true"></td>
</tr>
</table>
</div>
<div>
<button ng-disabled="!(!!roundCount)" ng-click="checkForm()">Start game</button>
</div>
</div>
<div ng-show="flag == 2">
<div id="gameState">
<div>
<table>
<tr><td class="stdCell borderedCell tableHeader">Player</td><td class="stdCell borderedCell tableHeader">Points</td></tr>
<tr ng-repeat="player in players"><td class="stdCell borderedCell">{{player.name}}</td><td class="stdCell borderedCell">{{player.totalPoints}}</td></tr>
</table>
</div>
<div>
<h2 class="stdCell" ng-model="nextPlayer">{{nextPlayer}} is next</h2>
</div>
</div>
<div id="darts">
<svg id="dartboard" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="630px" height="630px" viewBox="0 0 787 774" enable-background="new 0 0 787 774" xml:space="preserve">
<g id="areas" dart-click-listener="last.id">
<!-- svg file content -->
<div>
<h3 ng-model="winner" ng-repeat="player in players | filter:winner" class="stdCell">The winner: {{winner}} # points: {{player.totalPoints}}</h3>
</div>
<div>
<table>
<tr>
<td class="stdCell borderedCell tableHeader" rowspan="2">Player</td>
<td class="stdCell borderedCell tableHeader" colspan="{{players[0].fields.length}}">Round</td>
<td class="stdCell borderedCell tableHeader totalPointCell" rowspan="2">Total points</td>
</tr>
<tr>
<td class="stdCell borderedCell resultCell" ng-repeat="field in players[0].fields">{{field.fieldId}}</td>
</tr>
<tr ng-repeat="player in players">
<td class="stdCell borderedCell">{{player.name}}</td>
<td class="stdCell borderedCell resultCell" ng-repeat="field in player.fields">{{field.fieldName}}</td>
<td class="stdCell borderedCell resultCell">{{player.totalPoints}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Everything is about a darts game in AngularJS, but I have two problems with it:
1.) After every 3 shoots the player is changed. The shooting is checking in $scope.$watch('last.id' ...) section. My problem is that before changing a player, I must click once more on darts table, because the code is running only after clicking on either field of the table. How can I eliminate it?
2.) The second problem is, that I have to count also shoots, which not hit the table. How can I do it?
The dartboard is an SVG file, inserted into HTML code, the source is from: link.
Thank you very much for answers! :)

Categories

Resources