Change next div display - input value - javascript

I'm trying to hide/show a div depending on a checkbox, but can't make it work. I've seen many examples, tutorials, but couldn't adapt them to my case. It seems there are a lot of ways to do that.
Here is part of my code:
<div id="layer-control">
<p>Selectionnez les couches pour les afficher sur la carte.</p>
<div id="reciprocite">
<nav id='filter-group-reci' class='filter-group-reci'></nav>
<div id='recipro-polygon' class='legend' style="display:none;">>
<div><span style='background-color: #e6d94c' 'opacity:0.45'></span>GPV (adhérent URNE)</div>
<div><span style='background-color: #010492' 'opacity:0.45'></span>GPRMV (adhérent URNE)</div>
<div><span style='background-color: #179201' 'opacity:0.45'></span>EH3VV (adhérent URNE)</div>
<div><span style='background-color: #920104' 'opacity:0.45'></span>GAP </div>
<div><span style='background-color: #404040' 'opacity:0.45' ></span>AAPPMA Non réciprocitaires</div>
</div>
</div>
<div id="rivieres">
<nav id='filter-group-rivieres' class='filter-group-rivieres'></nav>
<div id='rivieres-line' class='legend'>
<div><span style="background-color: #0400ff; height: 4px"></span>1ère Catégorie DPF</div>
<div><span style="background-color: #6ea5f2; height: 2px"></span>1ère Catégorie</div>
<div><span style="background-color: #c110b6; height: 4px"></span>2ème Catégorie DPF</div>
<div><span style="background-color: #e48ff5; height: 2px"></span>2ème Catégorie</div>
<span><em>*Domaine Public Fluvial</em></span>
</div>
</div>
var layers = document.getElementById('filter-group-reci');
var layers2 = document.getElementById('filter-group-rivieres');
var layers3 = document.getElementById('filter-group-parcours');
toggleLayer('Réciprocité', ['reciprocite-gpv', 'reciprocite-gap','reciprocite-gprmv','reciprocite-non-recipro','reciprocite-eh3vv']);
toggleLayer2('Catégories Piscicoles',['cours-deau-large-1ere-dpf', 'cours-deau-m-1ere-dpf','cours-deau-s-1ere-dpf','cours-deau-large-2eme-dpf', 'cours-deau-m-2eme-dpf','cours-deau-s-2eme-dpf','cours-deau-large-1ere', 'cours-deau-m-1ere','cours-deau-s-1ere','cours-deau-large-2eme', 'cours-deau-m-2eme','cours-deau-s-2eme'])
//Bouton réciprocité
function toggleLayer(name,ids) {
var input = document.createElement('input');
input.type = 'checkbox';
input.id = ids;
input.checked = false;
layers.appendChild(input);
var label = document.createElement('label');
label.setAttribute('for', ids);
label.textContent = name;
layers.appendChild(label);
input.onclick = function (e) {
e.stopPropagation();
for (layers in ids){
var visibility = map.getLayoutProperty(ids[layers], 'visibility');
if (visibility === 'visible') {
map.setLayoutProperty(ids[layers], 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(ids[layers], 'visibility', 'visible');
}
}
};
}
//Bouton Catégorie piscicoles
function toggleLayer2(name,ids) {
var input = document.createElement('input');
input.type = 'checkbox';
input.id = ids;
input.checked = true;
layers2.appendChild(input);
var label = document.createElement('label');
label.setAttribute('for', ids);
label.textContent = name;
layers2.appendChild(label);
input.onclick = function (e) {
e.stopPropagation();
for (layers in ids){
var visibility = map.getLayoutProperty(ids[layers], 'visibility');
if (visibility === 'visible') {
map.setLayoutProperty(ids[layers], 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(ids[layers], 'visibility', 'visible');
}
}
};
}
First, I've read that it may be possible using CSS, with "input:checked ~ "
i tried:
.legend {
display:none;
}
#reciprocite-gpv,reciprocite-gap,reciprocite-gprmv,reciprocite-non-recipro,reciprocite-eh3vv input:checked ~ .legend {
display: block;
}
Didn't work, maybe I caused a syntax error?
Then i tried using javascript (or is it JQuery?)
$(function(){
$("input[type=checkbox]").change(function(){
if ($(this).is(":checked")){
$(this).next("div").css("display","block");
} else {
$(this).next("div").css("display","none");
}
});
$("input[type=checkbox]").change();
});
Could anyone give me a hint how to accomplish this?

You can use onclickto create a toggle-function and check, whether the checkbox is checked or not. Depending on the result you change the text of your div.
Take a look at this plunker. Here I used plain JavaScript. As you use jQuery you could also use div.html("your text") to change the text.

Related

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Remove Active Element With JavaScript

I'm trying to add some validation on something I'm working on. Basically if no input is processed, it would return a red paragraph telling you to enter something and return false. The problem I'm having is how to remove it when a valid value is processed.
var input = document.getElementById('input'),
button = document.getElementById('add')
function removeItem() {
var item = this.parentNode
var parent = item.parentNode
parent.removeChild(item)
}
button.addEventListener('click', function (e) {
if (input.value === '') {
var p = document.querySelector('p')
p.style.display = 'block'
return false
} else if (!input.value === '') {
p.style.display = ''
return true
}
var userInput = document.createTextNode(input.value)
var li = document.createElement('li')
var ul = document.getElementById('todo')
var remove = document.createElement('button')
remove.innerHTML = 'Remove'
remove.addEventListener('click', removeItem);
ul.insertBefore(li, ul.childNodes[0])
li.appendChild(userInput)
li.appendChild(remove)
})
<input type="text" id="input"/>
<button id="add">Add</button>
<p>plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>
p {
display: none;
color: #f00;
}
Some issues:
You return in both if ... else cases, which (if it would work) makes the rest of the code unreachable.
The else if condition is unnecessary (since the if condition was already false), but is also wrong: ! has precedence over ===, so better use !==. Anyway, it is not needed at all.
Here is the corrected code:
var input = document.getElementById('input'),
button = document.getElementById('add');
function removeItem() {
var item = this.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
}
button.addEventListener('click', function(e) {
var p = document.querySelector('p');
if (input.value.trim() === '') {
p.style.display = 'block';
return false;
}
p.style.display = '';
var remove = document.createElement('button');
remove.textContent = 'Remove';
remove.addEventListener('click', removeItem);
var li = document.createElement('li');
li.appendChild(document.createTextNode(input.value));
li.appendChild(remove);
todo.insertBefore(li, todo.childNodes[0]);
});
p {
display: none;
color: #f00;
}
<input type="text" id="input"/>
<button id="add">Add</button>
<p>plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>
add an id to the error element. Then :
var el = document.getElementById('theidyouset')
el.parentNode.removeChild( el );
or you could hide it
el.className += " classhiddenwithcss";
Use CSS classes and simply add or remove the class from the class list as needed.
Also, because you are using return in both of your if/else cases, the code will stop processing and not continue on to do the rest of the work. Move the if/else to the end of the code so that return is the last thing you do.
And, use semi-colons at the end of your statements.
var input = document.getElementById('input'),
button = document.getElementById('add')
function removeItem() {
var item = this.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
}
button.addEventListener('click', function(e) {
var p = document.querySelector('p')
var userInput = document.createTextNode(input.value)
var li = document.createElement('li')
var ul = document.getElementById('todo')
var remove = document.createElement('button')
remove.innerHTML = 'Remove'
remove.addEventListener('click', removeItem);
ul.insertBefore(li, ul.childNodes[0])
li.appendChild(userInput)
li.appendChild(remove)
if (input.value === '') {
p.classList.remove("hidden");
return false;
} else {
p.classList.add("hidden");
return true;
}
})
p {
color: #f00;
}
.hidden {
display:none;
}
<input type="text" id="input"/>
<button id="add">Add</button>
<p class="hidden">plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>

How to save html page content in .txt file using JavaScript?

I have create a static html page for quiz.
Following is my code
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("question").text;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
</script>
</body>
all is working fine but i want to save the checked radio button value and final result in .txt file
i want to save all the answers by user and along with the correct and the wrong to.
Things to note :
- initialize the variable textToSave first with no value;
- document.getElementById("question").text; Should be document.getElementById("question").innerHTML;
- in the body of choose, add the value of radio to the variable textToSave
And the result
var textToSave='';
function saveTextAsFile()
{
textToSave += ". Final Result : "+document.getElementById("question").innerHTML;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
textToSave += "Choosen Value : "+selections[questionCounter];
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
</body>
I assume you want to save the data for yourself, not the end user.
If you are looking to generate a txt file and download it - You can refer answer from Sagar V.
You can't directly save your answers or whatever data into a file by using JavaScript from a web browser.
You neeed a small server, maybe in node.js , php or java
First format your answers in particular structure like json and sene it as POST request method parameter
In server parse your parameter and save to an file you need
function downloadFile(filename, content) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}

Setting the maximum number of button to be pressed

I have the following code that allows me to display the number of models I have in my database. Each model details are tagged with a href button for the user to select.
1) Once the user clicked on the href button, the button's text will be changed to "selected".
2) If the user clicked on the button showing "selected", the button's text will be changed to "select".
<div class="row text-center">
<?php
while($rowModelList=mysql_fetch_array($resultModelList))
{
?>
<div class="col-md-3 col-sm-6 hero-feature">
<div class="thumbnail">
<img src="Images/Models/<? echo $rowModelList['modelImage'];?>" alt="" style="height: 200px;">
<div class="caption">
<h4><?php echo $rowModelList['modelName']?></h4>
<p>
Select
</p>
</div>
</div>
</div>
<?php
}
?>
</div>
I have the following code that allows me to change the colour and text of the href button when clicked.
/* Changing the colour of the href button upon clicked */
function changecolor(element) {
alert(element.target.id);
if (element.innerHTML == "Select") {
element.innerHTML = "Selected";
element.style.backgroundColor = "#C0C0C0"; /*Grey*/
element.style.borderColor = "#C0C0C0";
alert(element);
} else {
element.innerHTML = "Select";
element.style.backgroundColor = "#FED136"; /*Yellow*/
element.style.borderColor = "#FED136";
alert(element);
}
return false;
}
However, I am trying to restrict the number of buttons to be selected by the user.
For example, a list of 20 models is shown to the user but they are only allowed to select 8 of the model. Once 8 of the button's text are shown to be "selected", they will need to deselect one of the selected button in order to make new selection.
Any idea how I can modify the code to achieve it?
Thanks in advance
simply count selected options in your function:
var selectedCount = 0; // global variable
function changecolor(element) {
alert(element.target.id);
if(selectedCount > 8)
{
alert("already selected 8 options");
return false;
}
if (element.innerHTML == "Select") {
element.innerHTML = "Selected";
selected++;
element.style.backgroundColor = "#C0C0C0"; /*Grey*/
element.style.borderColor = "#C0C0C0";
alert(element);
} else {
element.innerHTML = "Select";
element.style.backgroundColor = "#FED136"; /*Yellow*/
element.style.borderColor = "#FED136";
selected--;
alert(element);
}
return false;
}
But its a lot easier if you use class for each element. Less code, and more control. Add class "selected" if element is checked, and remove it if unchecked. You dont need to style it in your javascript code.
jQuery example with class usage:
jQuery(document).ready(function(){
jQuery('.option').click(function(){
if(jQuery(this).hasClass('selected'))
{
// mark as unchecked
jQuery(this).html('not selected');
jQuery(this).removeClass('selected');
}
else
{
// mark as checked
if(jQuery('.selected').length >= 2) // check limit
{
alert('to many selected');
return false
}
jQuery(this).html('selected');
jQuery(this).addClass('selected');
}
return false;
});
});
Just create a variable that tracks how many are selected
/* Changing the colour of the href button upon clicked */
var selectedCount = 0;
function changecolor(element) {
if (selectedCount >=8 ) {
return;
}
if (element.innerHTML == "Select") {
selectedCount++;
element.innerHTML = "Selected";
element.style.backgroundColor = "#C0C0C0"; /*Grey*/
element.style.borderColor = "#C0C0C0";
alert(element);
} else {
selectedCount--;
element.innerHTML = "Select";
element.style.backgroundColor = "#FED136"; /*Yellow*/
element.style.borderColor = "#FED136";
alert(element);
}
return false;
}
You should avoid a global variable and you can do so using a closure/module pattern.
/* Changing the colour of the href button upon clicked */
var changecolor = (function(){
var selectedCount = 0;
function(element) {
if (selectedCount >=8 ) {
return;
}
if (element.innerHTML == "Select") {
selectedCount++;
element.innerHTML = "Selected";
element.style.backgroundColor = "#C0C0C0"; /*Grey*/
element.style.borderColor = "#C0C0C0";
alert(element);
} else {
selectedCount--;
element.innerHTML = "Select";
element.style.backgroundColor = "#FED136"; /*Yellow*/
element.style.borderColor = "#FED136";
alert(element);
}
return false;
}
})();

Hide and show div with links

So I have this code that I will put in jsfiddle link bellow. Im making hide/show divs by clicking on links. Only problem is when I want to view a div (second, third or fourth div), lets say the third one, it doesnt show up on top but benith the first and second invisible divs. Anybody got any idea how to make this right and put any selected div on the top of the page?
<body>
<div class="col-md-2">
<ul class="nav nav-pills nav-stacked" id="menu">
<li>Felge</li>
<li>Gume</li>
<li>Branici</li>
<li>Farovi</li>
</ul>
</div>
<div class="col-md-3">
<div class="div" id="content1">
<p>BBS</p>
<p>ENKEI</p>
<p>KONIG</p>
</div>
<div class="div" id="content2">
<p>Michelin</p>
<p>Hankook</p>
<p>Sava</p>
</div>
<div class="div" id="content3">
<p>AMG</p>
<p>Brabus</p>
<p>Original</p>
</div>
<div class="div" id="content4">
<p>Angel Eyes</p>
<p>Devil Eyes</p>
<p>Original</p>
</div>
</div>
`<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
function show(id) {
if (id == 'link1') {
document.getElementById("content1").style.visibility = 'visible';
document.getElementById("content2").style.visibility = 'hidden';
document.getElementById("content3").style.visibility = 'hidden';
document.getElementById("content4").style.visibility = 'hidden';
}
else if (id == 'link2') {
document.getElementById("content1").style.visibility = 'hidden';
document.getElementById("content2").style.visibility = 'visible';
document.getElementById("content3").style.visibility = 'hidden';
document.getElementById("content4").style.visibility = 'hidden';
}
else if (id == 'link3') {
document.getElementById("content1").style.visibility = 'hidden';
document.getElementById("content2").style.visibility = 'hidden';
document.getElementById("content3").style.visibility = 'visible';
document.getElementById("content4").style.visibility = 'hidden';
}
else if (id == 'link4') {
document.getElementById("content1").style.visibility = 'hidden';
document.getElementById("content2").style.visibility = 'hidden';
document.getElementById("content3").style.visibility = 'hidden';
document.getElementById("content4").style.visibility = 'visible';
}
}
function init() {
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if (divs[i].className == "div") {
divs[i].style.visibility = 'hidden';
}
}
var a = document.getElementsByTagName("a");
a.onclick = show;
}
window.onload = init;
`
https://jsfiddle.net/4qq6xnfr/
visibility: hidden hides element but leaves the space occupied by it. You need to hide element with display: none:
document.getElementById("content1").style.display = 'block';
document.getElementById("content2").style.display = 'none';
document.getElementById("content3").style.display = 'none';
document.getElementById("content4").style.display = 'none';
Also, you can optimize you code a little. Maybe like this:
function show(id) {
var number = id.replace('link', '');
var blocks = document.querySelectorAll("[id^=content");
for (var i = 0; i < blocks.length; i++) {
blocks[i].style.display = 'none';
}
document.querySelector('#content' + number).style.display = 'block';
}
Demo: https://jsfiddle.net/4qq6xnfr/3/
Use:
element.style.display = 'none'; // Hide
element.style.display = 'block'; // Show
The most efficient way to achieve this is as follows:
Change all the links from javascript:show('link1'), javascript:show('link2'), etc. to just #content1, #content2, etc.
You can now remove all of the javascript code.
Create a new CSS stylesheet (or use the <style> tags), and in the stylesheet, write the following -
.div {
display:none;
}
.div:target {
display:block;
}
That's it! I hope this helped you.

Categories

Resources