What this program its supposed to do is first with a range input you put how many elements you want to guess then it will show a random element form a json list and you have to guess the valnce and then it will load annother one and you continue. OK when i run this code everything is normal until you click submit button two times. When i click the submit botton the first time its goes well but the second time the program runs the if in the line 41 but it also runs the code in the else and if you submit more times it will run the alerts more and more times.
I have tried doing it other ways like just putting all into a for but it still runing code i dont want to.
const $ = require('jquery');
let elementoActual;
let valorPositivoCorrecto;
let valorNegativoCorrecto;
let valorCuadroNegativo;
let valorCuadroPositivo;
// Button on click add the element
$(document).ready(function() {
$("#startButton").click(function() {
$(".hide").hide();
let questionHTML = '<div class="elementoQuimico"><img id="imgElemnt" src="" alt=""></div>' +
'<div class="valenciasElemento">' +
'<input type="text" class="valorPositivo" placeholder="Valencias positivas">' +
'<input type="text" class="valorNegativo" placeholder="Valencias negativas">' +
'</div>' +
'<button class="submitButtonElement">SUBMIT</button>';
$(".questions").append(questionHTML);
putAnElement();
}); //onclick ends
}) //ready ends
function putAnElement() {
let numb = $("#textInput").val();
let counter = 0;
$.getJSON("../../json/valencias.json", function(data) {
let numeroDeElemento = Math.floor(Math.random() * 3);
elementoActual = data[numeroDeElemento];
valorNegativoCorrecto = data[numeroDeElemento].valenciasNegativas;
valorPositivoCorrecto = data[numeroDeElemento].valenciasPositivas;
//$("#imgElemnt").attr( "src" , elementoActual.img);
$("#imgElemnt").attr("alt", elementoActual.name);
$("#imgElemnt").attr("width", "200px");
$("#imgElemnt").attr("height", "200px");
alert(numb);
$(".submitButtonElement").click(function() {
valorCuadroNegativo = $(".valorNegativo").val();
valorCuadroPositivo = $(".valorPositivo").val();
$(".valorNegativo").val("");
$(".valorPositivo").val("");
if (valorCuadroNegativo === valorNegativoCorrecto &&
valorCuadroPositivo === valorPositivoCorrecto) {
alert("correcto");
counter++;
alert(counter);
if (counter != numb){
putAnElement();
} else {
alert("ya");
}
} else {
alert("incorrecto");
counter++;
alert(counter);
if (counter != numb) {
putAnElement();
} else {
alert("ya");
}
}
});
}); //getJSON ends
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tabla periodica</title>
<link rel="stylesheet" href="../../css/periodic-table.css">
</head>
<body>
<div class="wrapper">
<div class="hide">
<h1>TABLA PERIODICA</h1>
<img src="../../img/tabla-valencias.png">
<div class="buttons">
<button id="startButton">EMPEZAR</button>
<form id="submit-tabla">
<label for="rangeInput"></label><input type="range" name="amountRange" id="rangeInput" min="10" max="30" value="20" oninput="this.form.amountInput.value=this.value" />
<label for="textInput"></label><input type="number" name="amountInput" id="textInput" min="10" max="30" value="20" oninput="this.form.amountRange.value=this.value" />
</form>
</div>
</div>
<div class="questions">
</div>
</div>
<footer>
2017 © Nestor and Diego
</footer>
<script src="chemistry.js"></script>
</body>
</html>
And here is the json
[
{
"name":"hidrogeno",
"valenciasNegativas":"-1",
"valenciasPositivas":"1",
"img":"img/Hidrogeno.svg"
},
{
"name":"litio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Litio.svg"
},
{
"name":"sodio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Sodio.svg"
}
]
Related
I am trying to create a loop. so far I can get it to say Hello Tom and just the number. I want to add on a function named addOrderListItems that receives the name and numOfTimes as parameters. Then call the addOrderListItems function from the displayHello function and if the number is even add an !
so if I type name Braden and numOfTimes 8
the output will display a list
1.Hello Braden
2.Hello Braden!
3.Hello Braden
4.Hello Braden!
5.Hello Braden
6.Hello Braden!
7.Hello Braden
8.Hello Braden!
9.Hello Braden
function displayHello() {
let name = document.getElementById("helloNameInput").value,
numOfTimes = document.getElementById("numOfTimesInput").value;
}
function addOrderListItems() {
let numOfTimes = 0;
while (numOfTimes > 0 ) {
document.getElementById("helloNameOutput").innerHTML = "Hello " + name + numOfTimes;
numOfTimes++;
}
}
function clearName() {
document.getElementById("helloNameInput").value = "";
document.getElementById("numOfTimesInput").value = "";
document.getElementById("helloNameOutput").innerText = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript: Looping Structures Assignment</title>
<link href="/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-3">
<h1>JavaScript: Looping Structures Assignment</h1>
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input
type="text"
class="form-control"
name="helloNameInput"
id="helloNameInput"
placeholder="Enter a name"
/>
</div>
<!--Number of Times input-->
<div class="mb-3">
<label for="numOfTimesInput" class="form-label">Number of Times:</label>
<input
type="text"
class="form-control"
name="numOfTimesInput"
id="numOfTimesInput"
placeholder="Enter number"
/>
</div>
<!--Name output-->
<ol id="helloNameOutput"></ol>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();" >
Display Hello!
</button>
<button class="btn btn-danger" id="clearButton" onclick=" clearName();">Clear</button>
</div>
<script src="/script.js"></script>
</body>
</html>
```
You'll probably need a few functions to help you accomplish your goal and keep your code organized. Below I've created an example in a code snippet to demonstrate how the functionality you described can be implemented. I've included lots of comments to explain and help you understand the steps involved.
You can search on MDN and read the JavaScript documentation if there are parts you've never seen or don't yet understand — for example, here are a few links to some of the DOM APIs used:
Document.createElement()
Element.remove()
Node.firstChild
Node.appendChild()
Keep learning, and good luck in your programming!
const nameInput = document.getElementById('helloNameInput');
const qtyInput = document.getElementById('numOfTimesInput');
const btn = document.getElementById('writeGreeting');
const output = document.getElementById('helloNameOutput');
function createGreetingText (name, withExclamationPoint) {
return `Hello ${name}${withExclamationPoint ? '!' : ''}`;
}
function createGreetingListItem (name, withExclamationPoint) {
const listItem = document.createElement('li');
listItem.textContent = createGreetingText(name, withExclamationPoint);
return listItem;
}
function clearOutput () {
// Delete every child element from the output element:
while (output.firstChild) {
output.firstChild.remove();
}
}
function writeGreeting () {
// Get the trimmed input value (or use "world" if it's empty):
const name = nameInput.value.trim() || 'world';
// Get the number of times (quantity) from the other input:
let qty = parseInt(qtyInput.value);
// If the number input value couldn't be parsed as a valid integer,
// use 1 as the default valid value and update the input:
if (!Number.isInteger(qty)) {
qty = 1;
qtyInput.value = 1;
}
clearOutput();
// Loop the number of times:
for (let i = 1; i <= qty; i += 1) {
// Create and append a list item element each time:
const isEven = i % 2 === 0;
const listItem = createGreetingListItem(name, isEven);
output.appendChild(listItem);
}
}
// Bind the "writeGreeting" function to the button's "click" event,
// so that it runs each time the button is clicked:
btn.addEventListener('click', writeGreeting);
#container {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1rem;
font-family: sans-serif;
}
button, input {
font-size: 1rem;
padding: 0.5rem;
}
<div id="container">
<input
type="text"
id="helloNameInput"
placeholder="name"
value="Braden"
/>
<input
type="number"
step="1"
min="1"
id="numOfTimesInput"
placeholder="# of times"
value="8"
/>
<button id="writeGreeting">Write greeting</button>
<ol id="helloNameOutput"></ol>
</div>
I'm looking for a practical way to hide a label of an input type range when its value is lower than a specific number.
And then showing it again when the value goes back to a specific minimum number.
any idea?
Thanks
$('input[type="range"]').on('mouseup', function() {
this.blur();
}).on('mousedown input', function() {
$('#1').text(this.value + "%");
$('#2').text(100 - this.value + "%");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="range" min="0" max="100" step="1" value="50" />
<div class="container2">
<label id="1">50%</label>
</div>
<div class="container3">
<label id="2">50%</label>
</div>
</div>
You can simply use if statement to validate your condition and than use hide() or show() on the element you want to display or not.
In the example below, label with id="2" is shown when value is greater or equal to 50 and hidden when value is lower.
$('input[type="range"]').on('mouseup', function() {
this.blur();
}).on('mousedown input', function() {
var label1value = this.value;
var label2value = 100 - this.value;
$('#1').text(this.value + "%");
$('#2').text(100 - this.value + "%");
// compare value greater or equal to 50
if (this.value >= 50) {
// show element when condition is true
$('#2').show();
} else {
// hide element when condition is false
$('#2').hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="range" min="0" max="100" step="1" value="50" />
<div class="container2">
<label id="1">50%</label>
</div>
<div class="container3">
<label id="2">50%</label>
</div>
</div>
Well, I'm not really sure of what you really want to achieve but here is a code sample and a demo.
The range label disappears when value is lower than 50.
Using Vanilla JS
// On document ready
document.addEventListener("DOMContentLoaded", function() {
// set a range limit to show/hide range label
var rangeLimit = 50;
// When range value changes, call this listener
function rangeValueListener(event) {
var rangeElement = event.target || event.srcElement;
setRangeLabelValue(rangeElement);
}
// Update range label for a range element
function setRangeLabelValue(rangeElement) {
var rangeLabelElement = document.querySelector(
'label[for="' + rangeElement.id + '"]'
);
// Update label text using range value
var rangeValue = rangeElement.value;
rangeLabelElement.innerText = rangeValue + "%";
// if range value is lower than limit, hide it else restore initial state
if (rangeValue < rangeLimit) {
rangeLabelElement.style.display = "none";
} else {
rangeLabelElement.style.display = "initial";
}
}
// Get range element
var rangeElement = document.querySelector("#myRange");
// Attach a listener to change range label when range value change
rangeElement.addEventListener("input", rangeValueListener);
rangeElement.addEventListener("change", rangeValueListener);
// Set initial range label
setRangeLabelValue(rangeElement);
});
Code snippet using jQuery (without explanation, code is simply adapted)
$(document).ready(function() {
var rangeLimit = 50;
var rangeDefaultValue = 65;
function rangeValueListener(event) {
setRangeLabelValue(event.target);
}
function setRangeLabelValue(rangeElement) {
var rangeElementId = rangeElement.id || rangeElement.attr("id");
var rangeLabelElement = $('label[for="' + rangeElementId + '"]');
var rangeValue = rangeElement.value || rangeDefaultValue;
rangeLabelElement.text(rangeValue + "%");
if (rangeValue < rangeLimit) {
rangeLabelElement.hide();
} else {
rangeLabelElement.show();
}
}
var rangeElement = $("#myRange");
rangeElement.on("input change", rangeValueListener);
setRangeLabelValue(rangeElement);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<input id="myRange" type="range" min="0" max="100" step="1" value="65" />
<label for="myRange"></label>
</body>
</html>
This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>
I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>
I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.
I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one
You should use:
$(this).next('input').focus();
try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...
Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.
Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>
This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});