Hi I am trying to make a form, where are the fields are required, including one of two radio buttons, but for some reason the .checked property will not work neither if I am selecting it like this document.querySelector('input[name="radio"]:checked')... What am I not seeing?
As you can see I was trying different approaches but something is missing
let contactForm = document.querySelector('.contact-form');
let firstName = document.getElementById('first-name');
let lastName = document.getElementById('last-name');
let textarea = document.getElementById('message');
// let radioBtn = document.querySelector('input[name="radio"]:checked');
// let firstRadioBtn = document.getElementById('male').checked;
// let secondRadioBtn = document.getElementById('female').checked;
// console.log(firstRadioBtn.value, secondRadioBtn.value);
let submitBtn = document.querySelector('.btn');
let successMsg = document.querySelector('.success-message');
// let radios = document.getElementsByName('radio');
// let formValid = false;
// console.log(radios)
// for (let i = 0; i < radios.length; i++) {
// if (radios[i].checked) {
// formValid = true
// }
// }
function checkInputs() {
let firstNameInput = firstName.value;
let lastNameInput = lastName.value;
let text = textarea.value;
if (firstNameInput === '' || lastNameInput === '' || text === '') {
firstName.className = 'invalid';
lastName.className = 'invalid';
textarea.className = 'invalid';
successMsg.style.backgroundColor = '#e63946';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Please fill in all the required fields`
}
if (firstNameInput !== '' && lastNameInput !== '' && text !== '') {
firstName.className = 'valid';
lastName.className = 'valid';
textarea.className = 'valid';
successMsg.style.backgroundColor = '#52b788';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Thank you for your message ${firstNameInput} ${lastNameInput}`
}
console.log(`${firstName.value} ${lastName.value} \n Gender: ${radios.value} \n Message: ${message.value}`)
}
<div class="radio-btn label">
<label for="radio">Male</label>
<input type="radio" name="radio" id="male" value="male">
<label for="radio">Female</label>
<input type="radio" name="radio" id="female" value="female">
</div>
This should work!
<div class="radio-btn label">
<label for="radio">Male</label>
<input type="radio" name="radio" id="male" value="male">
<label for="radio">Female</label>
<input type="radio" name="radio" id="female" value="female">
</div>
<div id="gender-error" style="color: red; display: none">Please select the gender</div>
<button type="submit" onclick="return submit();">Submit</button>
<script>
function submit() {
var radios = document.getElementsByName("radio");
var value = ""
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
document.getElementById("gender-error").style.display = !value ? "block" : "none";
alert(value ? "selected " + value : "no value selected");
}
</script>
Output:
Related
I have a form that i enter the number of element then the text then the type div or section
and i click create i should remove the older div or section and create the new one
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
The problem is that the div or section appear but than disappear quickly i'm checking if the field are empty and if the field element number > 0 than i create the element that should appear in the result div
how can i solve this problem
The problem with your code is that you aren't preventing the <form> from refreshing the page.
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
You use the above if statement to prevent the <form>'s default behaviour, but you set all those variables to true after creating your elements.
validElement = true;
validText = true;
validType = true;
So your script basically creates the elements and then the form refreshes the page.
Moving e.preventDefault(); outside of its if block would fix your immediate problem.
I would personally call e.preventDefault(); regardless of whether the users put in valid data, as a page refresh seems unneccesary in either case.
As for how to clear your results div, here is an elaborate post describing several ways of doing it.
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
// Clear the Results Container
while (result.firstChild) {
result.removeChild(result.lastChild);
}
// Repopulate the Results Container
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
e.preventDefault();
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
This is what I been doing so far. The problem is that the message appears always even without value input.
Another thing, would you do this differently? if yes show me your examples.
let jogador1 = document.querySelector('#jogador1');
let jogador2 =document.querySelector('#jogador2');
let output = document.querySelector('#output');
let value1 = jogador1.value;
let value2 = jogador2.value;
let letsCompareValues = (value1, value2) => {
if (value1 === value2 && value1 !== isNaN && value2 !==isNaN) {
msg += ' there is a match';
return output.textContent = msg;
}
}
button.addEventListener('click', letsCompareValues(value1, value2));
<div>
<label for="jogador1">Player 1</label>
<input type="text" id="jogador1">
</div>
<div>
<label for="jogador2">Player 2</label>
<input type="text" id="jogador2">
</div>
<button id="button">JOGAR</button>
The issue is you have set the value before button click only like:
let value1 = jogador1.value;
let value2 = jogador2.value;
So, even if the user changes these values.. the temp values stored in value1 & value2 will always be empty. You just need to access those values inside button click only like:
let letsCompareValues = () => {
let msg = '';
let value1 = jogador1.value;
let value2 = jogador2.value;
if (value1 === value2 && !isNaN(value1) && !isNaN(value2)) {
msg += ' there is a match';
output.textContent = msg;
return output.textContent;
} else {
output.textContent = msg;
}
}
DEMO:
let jogador1 = document.querySelector('#jogador1');
let jogador2 = document.querySelector('#jogador2');
let output = document.querySelector('#output');
let letsCompareValues = () => {
let msg = '';
let value1 = jogador1.value;
let value2 = jogador2.value;
if (value1 === value2 && !isNaN(value1) && !isNaN(value2)) {
msg += ' there is a match';
output.textContent = msg;
return output.textContent;
} else {
output.textContent = msg;
}
}
button.addEventListener('click', letsCompareValues);
<div>
<label for="jogador1">Player 1</label>
<input type="text" id="jogador1">
</div>
<div>
<label for="jogador2">Player 2</label>
<input type="text" id="jogador2">
</div>
<button id="button">JOGAR</button>
<div id="output">
</div>
You have to get the values and then compare them every time as follows:
let jogador1 = document.getElementById('jogador1');
let jogador2 =document.getElementById('jogador2');
let output = document.getElementById('output');
let btn = document.getElementById('button');
function letsCompareValues() {
let value1 = jogador1.value;
let value2 = jogador2.value;
if (value1 === value2 && value1 !== isNaN && value2 !==isNaN)
output.innerHTML = 'there is a match';
else
output.innerHTML = 'there´s no match';;
}
btn.addEventListener('click', letsCompareValues);
<div>
<label for="jogador1">Player 1</label>
<input type="text" id="jogador1">
</div>
<div>
<label for="jogador2">Player 2</label>
<input type="text" id="jogador2">
</div>
<button id="button">JOGAR</button>
<p id="output"></p>
I want all inputs (radios, checkboxes, etc..) to be disabled (I don't want to be able to check them/ type) until "Start Quiz" button is clicked.
(That's all I need, this code is a quiz and I don't want people to be able to start doing it before clicking that button that releases starting time. But I don't know how to do it, I'm new to all this.)
var tacniOdgovori = 0;
var netacniOdgovori = 0;
function pocniKviz(){
vreme1 = new Date();
var vremeOd = vreme1.getHours() + ":" + vreme1.getMinutes() + ":" + vreme1.getSeconds();
document.getElementById("vremeOd").innerHTML = vremeOd;
document.getElementById("btnZapocniKviz").disabled = true;
document.getElementById("btnZavrsiKviz").disabled = false;
}
function zavrsiKviz(){
var pitanje1 = document.getElementsByName('pitanje1');
for (var i = 0; i < pitanje1.length; i++)
{
if (pitanje1[i].checked)
{
if(pitanje1[i].value == "Da"){
tacniOdgovori = tacniOdgovori + 1;
}
}
}
var pitanje2 = document.getElementsByName('pitanje2');
for (var i = 0; i < pitanje2.length; i++)
{
if (pitanje2[i].checked)
{
if(pitanje2[i].value == "HTTP"){
tacniOdgovori++;
}
}
}
if(document.getElementById("pitanje3").value == "interakcija"){
tacniOdgovori++;
}
var pitanje4 = document.getElementsByName('pitanje4');
for (var i = 0; i < pitanje4.length; i++)
{
if (pitanje4[i].checked)
{
if(pitanje4[i].value == "Apache" && pitanje4[i].value == "IIS"){
tacniOdgovori++;
}
}
if (pitanje4[i].checked)
{
if(pitanje4[i].value == "Apache" || pitanje4[i].value == "IIS"){
tacniOdgovori=tacniOdgovori+0.5;
}
}
document.getElementById("btnResetujKviz").disabled = false;
}
vreme2 = new Date();
var vremeDo = vreme2.getHours() + ":" + vreme2.getMinutes() + ":" + vreme2.getSeconds();
document.getElementById("vremeDo").innerHTML = vremeDo;
document.getElementById("tacniOdgovori").innerHTML = tacniOdgovori;
document.getElementById("netacniOdgovori").innerHTML = 4 - tacniOdgovori;
document.getElementById("rezultat").innerHTML = (tacniOdgovori/4)*100 + "%";
document.getElementById("btnZavrsiKviz").disabled = true;
}
<html>
<head>
</head>
<body style="padding:1%;">
<h2 align="center">Kviz</h3>
<button onclick="pocniKviz()" id="btnZapocniKviz">Start Quiz</button>
<p>Vreme pocetka rada: <span id="vremeOd" style="color:red">span vreme od</span></p>
<hr>
<h3>1. Da li je moguce hostovati web sajt na vise web servera?</h3>
<input type="radio" value="Da" name="pitanje1">Da</input>
<input type="radio" value="Ne" name="pitanje1">Ne</input>
<input type="radio" value="Svaki" name="pitanje1">Svaki web sajt se hostuje na vise web servera</input>
<h3>2. Pomocu kojih protokola je moguce pristupiti sajtovima? (jedan ili vise odgovora)</h3>
<input type="checkbox" value="FTP" name="pitanje2">FTP</input>
<input type="checkbox" value= "HTTP" name="pitanje2">HTTP</input>
<input type="checkbox" value= "SMB" name="pitanje2">SMB</input>
<input type="checkbox" value= "SSH" name="pitanje2">SSH</input>
<input type="checkbox" value= "WSP" name="pitanje2">WSP</input>
<h3>3. Kada korisnik vrsi neku aktivnost na sajtu to se zove <input id="pitanje3"></h3>
<h3>4. Sta je od navedenog web server? (jedan ili više odgovora)</h3>
<input type="checkbox" value="Apache" name="pitanje4">Apache</input>
<input type="checkbox" value="Samba" name="pitanje4">Samba</input>
<input type="checkbox" value="IIS" name="pitanje4">IIS</input>
<hr>
<button onclick="zavrsiKviz()" id="btnZavrsiKviz" disabled>Zavrsi kviz</button>
<button onClick="window.location.reload()" id="btnResetujKviz" disabled>Resetuj kviz</button>
<p>Vreme kraja rada: <font color="red"><span id="vremeDo">span vreme do</span></font></p>
<p>Tacnih odgovora: <font color="green"><span id="tacniOdgovori">span tacnih odgovora</span></font></p>
<p>Netacnih odgovora: <font color="red"><span id="netacniOdgovori">span netacnih odgovora</span></font></p>
<p>Uspeh u procentima: <span id="rezultat">span rezultata</span></p>
</body>
</html>
First, add a disabled property to your input elements, like this
<input type="radio" value="Da" name="pitanje1" disabled="disabled">Da</input>
Then, inside your pocniKviz() function:
var inputs = document.querySelectorAll('input'); //get all inputs and store into an array
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = false; //enable the element
}
you can also disable your inputs through JS, on the first line of your script:
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = true; //disable the element
}
First, add a disabled property to your input elements and then
I implemented in some of the inputs
try to understand it and then do same thing with other inputs
Main Part Changed
put this code into your start Quiz button's click event
var input = document.getElementsByTagName("input"); // gets all the input tags as nodelist
var inputList = Array.prototype.slice.call(input); //convert it to array
inputList.forEach(function(element) { // loops through it and then sets disabled = false
element.disabled = false;
});
var tacniOdgovori = 0;
var netacniOdgovori = 0;
function pocniKviz(){
vreme1 = new Date();
var vremeOd = vreme1.getHours() + ":" + vreme1.getMinutes() + ":" + vreme1.getSeconds();
document.getElementById("vremeOd").innerHTML = vremeOd;
document.getElementById("btnZapocniKviz").disabled = true;
document.getElementById("btnZavrsiKviz").disabled = false;
var input = document.getElementsByTagName("input"); // gets all the input tags as nodelist
var inputList = Array.prototype.slice.call(input); //convert it to array
inputList.forEach(function(element) { // loops through it and then sets disabled = false
element.disabled = false;
});
}
function zavrsiKviz(){
var pitanje1 = document.getElementsByName('pitanje1');
for (var i = 0; i < pitanje1.length; i++)
{
if (pitanje1[i].checked)
{
if(pitanje1[i].value == "Da"){
tacniOdgovori = tacniOdgovori + 1;
}
}
}
var pitanje2 = document.getElementsByName('pitanje2');
for (var i = 0; i < pitanje2.length; i++)
{
if (pitanje2[i].checked)
{
if(pitanje2[i].value == "HTTP"){
tacniOdgovori++;
}
}
}
if(document.getElementById("pitanje3").value == "interakcija"){
tacniOdgovori++;
}
var pitanje4 = document.getElementsByName('pitanje4');
for (var i = 0; i < pitanje4.length; i++)
{
if (pitanje4[i].checked)
{
if(pitanje4[i].value == "Apache" && pitanje4[i].value == "IIS"){
tacniOdgovori++;
}
}
if (pitanje4[i].checked)
{
if(pitanje4[i].value == "Apache" || pitanje4[i].value == "IIS"){
tacniOdgovori=tacniOdgovori+0.5;
}
}
document.getElementById("btnResetujKviz").disabled = false;
}
vreme2 = new Date();
var vremeDo = vreme2.getHours() + ":" + vreme2.getMinutes() + ":" + vreme2.getSeconds();
document.getElementById("vremeDo").innerHTML = vremeDo;
document.getElementById("tacniOdgovori").innerHTML = tacniOdgovori;
document.getElementById("netacniOdgovori").innerHTML = 4 - tacniOdgovori;
document.getElementById("rezultat").innerHTML = (tacniOdgovori/4)*100 + "%";
document.getElementById("btnZavrsiKviz").disabled = true;
}
<html>
<head>
</head>
<body style="padding:1%;">
<h2 align="center">Kviz</h3>
<button onclick="pocniKviz()" id="btnZapocniKviz">Start Quizz</button>
<p>Vreme pocetka rada: <span id="vremeOd" style="color:red">span vreme od</span></p>
<hr>
<h3>1. Da li je moguce hostovati web sajt na vise web servera?</h3>
<input type="radio" value="Da" name="pitanje1" disabled>Da</input>
<input type="radio" value="Ne" name="pitanje1" disabled>Ne</input>
<input type="radio" value="Svaki" name="pitanje1" disabled>Svaki web sajt se hostuje na vise web servera</input>
<h3>2. Pomocu kojih protokola je moguce pristupiti sajtovima? (jedan ili vise odgovora)</h3>
<input type="checkbox" value="FTP" name="pitanje2" disabled>FTP</input>
<input type="checkbox" value= "HTTP" name="pitanje2" disabled>HTTP</input>
<input type="checkbox" value= "SMB" name="pitanje2" disabled>SMB</input>
<input type="checkbox" value= "SSH" name="pitanje2" disabled>SSH</input>
<input type="checkbox" value= "WSP" name="pitanje2" disabled>WSP</input>
<h3>3. Kada korisnik vrsi neku aktivnost na sajtu to se zove <input id="pitanje3"></h3>
<h3>4. Sta je od navedenog web server? (jedan ili više odgovora)</h3>
<input type="checkbox" value="Apache" name="pitanje4">Apache</input>
<input type="checkbox" value="Samba" name="pitanje4">Samba</input>
<input type="checkbox" value="IIS" name="pitanje4">IIS</input>
<hr>
<button onclick="zavrsiKviz()" id="btnZavrsiKviz" disabled>Zavrsi kviz</button>
<button onClick="window.location.reload()" id="btnResetujKviz" disabled>Resetuj kviz</button>
<p>Vreme kraja rada: <font color="red"><span id="vremeDo">span vreme do</span></font></p>
<p>Tacnih odgovora: <font color="green"><span id="tacniOdgovori">span tacnih odgovora</span></font></p>
<p>Netacnih odgovora: <font color="red"><span id="netacniOdgovori">span netacnih odgovora</span></font></p>
<p>Uspeh u procentima: <span id="rezultat">span rezultata</span></p>
</body>
</html>
As the question is asking, can you get the values from the session storage or local storage to radio buttons on html and the same thing for the checkboxes?
My code:
var customername = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var curcustomer1 = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var lastvist = {"date" : dateall} // only display the date and time
var myJSON = JSON.stringify(customername);
var myJSON1 = JSON.stringify(lastvist); // has the date when the user last has visited
var myJSON2 = JSON.stringify(curcustomer1);
var myJSON3full = JSON.stringify(custinfo);
sessionStorage.setItem("custinfo", myJSON3full);
var objectfull = sessionStorage.getItem("custinfo");
objfull = JSON.parse(objectfull);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
if(object != myJSON) {
sessionStorage.setItem("customername", myJSON);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
var curcustomer = customername;
var myJSONcopy = JSON.stringify(curcustomer);
var object2 = sessionStorage.setItem("curcustomer", myJSONcopy);
var msg5 = "Welcome ";
document.getElementById("customer").innerHTML = msg5 + " " + "New Customer";
document.getElementById("date1").innerHTML = "";
var radiobtn = document.getElementsByName("type");
if(radiobtn.value != 8) {
document.elem.type.value="8";
}
var radiobtn1 = document.getElementsByName("special");
if(radiobtn1.value != 0) {
document.elem.special.value="0";
}
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extras[i].checked = false;
}
}
}
if(object == myJSONcopy) {
radiobtn = document.getElementsByClassName("type").innerHTML = sessionStorage.getItem("type");
radiobtn1 = document.getElementsByClassName("special").innerHTML = sessionStorage.getItem("special");
checboxes = document.getElementsByClassName("extras").innerHTML = sessionStorage.getItem("extras");
}
<td>
<input type="radio" name="type" value="8" checked>Small $8.00
<br>
<input type="radio" name="type" value="10">Medium $10.00
<br>
<input type="radio" name="type" value="15">Large $15.00
<br>
<input type="radio" name="type" value="18">Extra Large $18.00
<br>
<br>
</td>
if you are trying to add the item to multiple buttons that share the same className then you will have to do something like this:
var list = document.getElementsByClassName('type');
var i;
for (i = 0; n < list.length; ++i) {
list[i].value= sessionStorage.getItem('events')
};
But if it's just one button then I will suggest you use getElementById
like this
document.getElementById('Id').value = sessionStorage("events");