Java Script error handling - javascript

I have a function where I check my two (or one) input fileds if they are empty i want to let's say print alert in window but if they have vaules i want to run else but in my case alert is not popping up and if i want to submit those two fileds with data it is ok pushing it and doing alll stuff in else but whole browser is reloading. I was trying to add prevent.Default() but not working. Or return false
UPDATE: I made some changes and know when input is empty alert is popping up, but when i colse it it is still realoding whole page, same thing if else is executed all browser is reloading
let pushBtn = document.getElementById('push-btn');
pushBtn.addEventListener('click', pushData);
function pushData() {
let deviceVal = document.getElementById('device').value;
let powerVal = document.getElementById('power').value;
if (deviceVal != '' || powerVal != '') {
let list = document.getElementById('list-group')
let button = document.createElement('button');
let ul = document.createElement('ul');
let liFirst = document.createElement('li');
let liSecond = document.createElement('li');
let liThird = document.createElement('li');
button.classList.add("list-group-item");
ul.classList.add("desc");
liFirst.classList.add("t-desc");
liSecond.classList.add("t-desc2");
liThird.classList.add("t-desc3");
liFirst.textContent = deviceVal;
liSecond.textContent = powerVal;
liThird.innerHTML = `<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>`
modal.style.display = 'none';
ul.append(liFirst);
ul.append(liSecond);
ul.append(liThird);
button.append(ul);
list.prepend(button);
} else {
alert('aaa');
return false
}
}

<input type="text" name="device" required />
Job done, no JavaScript needed.
* But you should use a submit event on the form, not a click event on the button.
Specifically for your question, you want the alert to trigger if either input is blank, but you're testing if either one isn't blank. Use == instead of !=.

ok got it!
function pushData(e) {
let deviceVal = document.getElementById('device').value;
let powerVal = document.getElementById('power').value;
e.preventDefault()
if (deviceVal != '' || powerVal != '') {
let list = document.getElementById('list-group')
let button = document.createElement('button');
let ul = document.createElement('ul');
let liFirst = document.createElement('li');
let liSecond = document.createElement('li');
let liThird = document.createElement('li');
button.classList.add("list-group-item");
ul.classList.add("desc");
liFirst.classList.add("t-desc");
liSecond.classList.add("t-desc2");
liThird.classList.add("t-desc3");
liFirst.textContent = deviceVal;
liSecond.textContent = powerVal;
liThird.innerHTML = `<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>`
modal.style.display = 'none';
ul.append(liFirst);
ul.append(liSecond);
ul.append(liThird);
button.append(ul);
list.prepend(button);
} else {
alert('aaa');
}
}

You can log to console before the "if" statement and inspect deviceVal/powerVal values, or use built-in debbuger in browser.
function pushData() {
console.log(deviceVal)
console.log(powerVal)
if (deviceVal != '' || powerVal != '') {
alert('aaa');
} else {..}
}

Related

Javascript adding li element value to the empty list if it is not existing

I have a problem in Javascript.I am adding new list items to the 'ul' elements and this list is empty at first and I do not want to add same values twice. When I write the if statement I get the exception because my list is empty so the result return null.
How can I fix this this problem?
Thank you in advance...
Html Codes
<input type="text" id="the-filter" placeholder="Search For..." />
<div class="list-container">
<ul id="myList"></ul>
<button id="button">Click</button>
Javascript Codes
let newlist = document.querySelector("#myList");
const li = document.getElementsByClassName('list-group-item');
const button = document.getElementById("button");
const button.addEventListener('click' , listName);
const input = document.getElementById("the-filter");
function listName()
const inputVal = input.value;
for (i = 0; i < li.length; i++) {
if ((li[i].innerHTML.toLocaleLowerCase().includes(inputVal) && inputVal!="") ||
(li[i].innerHTML.toUpperCase().includes(inputVal) && inputVal!="")) {
let newItem = document.createElement("li");
li[i].classList.add("list-group-item");
let textnode = document.createTextNode(li[i].innerHTML.toLocaleLowerCase());
newItem.appendChild(textnode);
if((newlist.children[0].innerHTML.toLocaleLowerCase().includes(inputVal))){
newlist.insertBefore(newItem, newlist.childNodes[0]);
}
}
}
}
If I understood the task correct, you need to add items to the list by button click.
If same item exists (case insensitive), then nothing happens.
const list = document.querySelector("#myList");
const button = document.getElementById("button");
button.addEventListener("click", listName);
const input = document.getElementById("the-filter");
function listName() {
const inputVal = input.value;
const [...lis] = document.getElementsByClassName("list-group-item");
const same = lis.find((el) => el.textContent.toLowerCase() === inputVal.toLowerCase());
if (same) {
return;
}
let newItem = document.createElement("li");
newItem.classList.add("list-group-item");
newItem.textContent = inputVal;
list.appendChild(newItem)
}
<input type="text" id="the-filter" placeholder="Search For..." />
<div class="list-container">
<ul id="myList"></ul>
<button id="button">Click</button>
</div>
You're on the right track with event listeners and element creation, but your original code didn't quite seem to match your stated goal.
Here's a solution you might find useful, with some explanatory comments:
// Identifies some DOM elements
const
input = document.getElementById("my-input"),
newList = document.getElementById("my-list"),
items = document.getElementsByClassName('list-group-item'),
button = document.getElementById("my-button");
// Focuses input, and calls addItem on button-click
input.focus();
button.addEventListener('click', addItem);
// Defines the listener function
function addItem(){
// Trims whitespace and sets string to lowerCase
const inputTrimmedLower = input.value.trim().toLocaleLowerCase();
// Clears and refocuses input
input.value = "";
input.focus();
// Ignores empty input
if (!inputTrimmedLower) { return; }
// Ignores value if a list item matches it
for (const li of items) {
const liTrimmedLower = li.textContent.trim().toLocaleLowerCase();
if (liTrimmedLower === inputTrimmedLower) {
console.log(`${inputTrimmedLower} is already listed`);
return;
}
}
// If we got this far, we want to add the new item
let newItem = document.createElement("li");
newItem.classList.add("list-group-item");
newItem.append(inputTrimmedLower); // Keeps lowerCase, as your original code
newList.prepend(newItem); // More modern method than `insertBefore()`
}
<input id="my-input" />
<ul id="my-list"></ul>
<button id="my-button">Click</button>

console out checked radio buttons

Im trying to console out a radio button with JS in order to see the value of the checked button. the Js seems to be without syntax error, but it returns undefined:
this is the HTML:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
if (meeting1.checked) {
meeting = meeting1.value;
console.log(meeting = "1");
} else if (meeting2.checked) {
meeting = meeting2.value;
console.log(meeting = "2")
} else if (meeting3.checked) {
meeting = meeting3.value;
console.log(meeting = "3")
} else if (meeting4.checked) {
meeting = meeting4.value;
console.log(meeting = "4")
}
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function() {
console.log(` Name: ${firstName.value}, Last Name: ${lastName.value}, Email: ${email.value}, Comment: ${comments.value} Type of meeting: ${meeting}`);
});
<fieldset>
<legend>Would you like to meet for?</legend>
<label><input type="radio" id="meetingtype1" name=meetingtype value="coffee" > A coffee</label>
<label><input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</label>
<label><input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</label>
<label><input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</label>
<button id="submitform" type="submit">Submit</button>
thank you very much!
Since you want to check the value/log it onto your console when you are going to click onto your button, make sure to use your if-else-statement inside of the EventListener and not outside of the function. If you write the if-else-statement in your way, it will be executed when the page loads the first time.
To print out your current value of the selected meeting change your JavaScript Code to this. I modified your provided code.
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function () {
if (meeting1.checked){
meeting = meeting1.value;
} else if (meeting2.checked){
meeting = meeting2.value;
} else if (meeting3.checked){
meeting = meeting3.value;
} else if (meeting4.checked){
meeting = meeting4.value;
}
console.log(`Type of meeting: ${meeting}`);
});

queryselector is returning incorrect value for input field

Code:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function displayquestion(a, ignore){
var b = a-1;
var currentInput = '';
var questions = document.getElementsByClassName("questionholder");
var showRequired = document.getElementById("requiredMessage");
if (document.querySelector('input.input' + b) !== null) {
var currentInput = document.querySelector('input.input' + b).value;
}
// Check if question should ignore inputs
if (ignore == 1) { // yes, ignore the inputs so move on to next question
console.log("path 1");
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
} else { //no, don't ignore the inputs
if (currentInput == '') { // the input is blank so show error
console.log("path 2");
showRequired.style.display = "block";
} else { // the input is not blank so move on to next question
console.log("currentInput = " + currentInput);
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
}
}
}
</script>
</head>
<body>
<div id="requiredMessage" style="display:none"><p>This field is required.</p></div>
<form id="TheForm" style="display:block;">
<div data-toggle="buttons" class="questionholder multiplechoice" id="question10" style="display:block">
<h5>Do you have a surname?</h5>
<input class="input10" type="radio" id="yes" name="sn" value="yes"><label for="relPPTsnyes"><p class="radioChoice">Yes / Oui</p></label>
<input class="input10" type="radio" id="no" name="sn" value="no"><label for="relPPTsnno"><p class="radioChoice">No / Non</p></label><br>
<a class="text2button radio" onclick="displayquestion(11)">Next</a>
</div>
</form>
</body>
</html>
I have issues with my javascript function, which works as intended with input text fields, but does not with radio buttons.
In short, I have a div that contains a pair of radio buttons and a next button. When the user click next, the function displayquestion(a) fires.
The function checks currentInput to see if the input is blank. If it is blank, it shows an error message. If it is not blank, it hides the div.
With radio buttons however, currentInput is always returning "yes" whether nothing is selected, no is selected or yes is selected. Since it isn't blank, it hides the div.
The intended result should be that the error message displays until the user makes a selection. only when the user clicks next, it should hide the div.
So my question is, what is causing my issue and how can it be fixed?
jsfiddle
use :checked
var currentInput = document.querySelectorAll('input.input' + b + ':checked").value;
Radios and Checkboxes always return their value.
The first thing you must do is check if one of them is selected, then get the value of the selected one.
const inputs = document.querySelectorAll('input[type=checkbox]') // or type=radio
for (const input of inputs)
{
if (input.checked)
{
console.log(input.value)
}
}
Also, querySelector() can return the selected one directly, without the need to loop the node list.
const input = document.querySelector('input[type=checkbox]:checked') // or type=radio
if (input)
{
console.log(input.value)
}
you not checking whether the radio is checked or not.As a result document.querySelector returns the first radio with value = "yes" use :checked is querySelector
if (document.querySelector('input.input' + b + ':checked') !== null) {
currentInput = document.querySelector('input.input' + b + ':checked').value;
console.log(currentInput)
}
My solution:
if (document.querySelector('input.input' + b).type == "radio") { //this is a radio input
if (document.querySelector('input[type=radio]:checked')) { //a radio option is selected
showNext();
} else { // no radio option is selected so show error
showRequired.style.display = "block";
}
} else { // not a radio input
}

Unable to set the onclick property of a button

I have a button calling a js function. Everything in the function runs but at the end I try to set the onclick value for the button and nothing happens. The catch block doesn't even generate an error
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
I have also tried setting the onclick value these ways
nextButton.onclick = function () { generateCategories(); };
nextButton.onclick = generateCategories;
the tvalue variable is set like this:
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value;
Other test outputs have shown that this retrieves the value no problem
The relevant HTML:
<form id='fieldsets' action="../scripts/reportParse.php">
<fieldset>
<legend> Select Report Type </legend>
<select id="type" name="type">
<option value="trend"> Waitlists over Time </option>
<option value="stats"> Region Statistics </option>
</select>
</fieldset>
<button id="next" onclick="generateRegions()"> Next </button>
I've been trying solutions based on the following page:
Change onclick action with a Javascript function
and w3schools.com
Thanks for any help. I've been hung up on this for a little bit now
Edit: I've tried useing event listeners based on a comment below and am now getting the error "i is not defined'. which seems odd since i is not referred too inside the try block.
The whole function in case i've missed something stupid:
function generateRegions(){
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value; // The value of the selected option
var names = ["Downtown", "Glenmore", "Mission", "Rutland"];
var regions = document.createElement("FIELDSET");
regions.setAttribute("id","Region");
var temp = document.createElement("LEGEND");
temp.innerHTML = "Select Region:";
regions.appendChild(temp); //creating the fieldset div and assigning its legend
for(var i = 0; i < 4; i++){
var templ = document.createElement("LABEL");
var str1 = "chk";
var str2 = i.toString();
var id = str1.concat(str2); //creating a dynamic ID so each checkbox can be referred to individually
templ.setAttribute("for",id);
temp = document.createElement("INPUT"); //creating the checkbox and assigning its values
temp.setAttribute("type","checkbox");
temp.setAttribute("name","region");
temp.setAttribute("value",names[i]);
temp.setAttribute("id",id);
regions.appendChild(templ);
templ.innerText = names[i]+':'; //creating and placing the label, then placing its checkbox
regions.appendChild(temp);
}
document.getElementById("fieldsets").appendChild(regions); //adding the fieldset to the overall form
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
//document.getElementById("demo").innerHTML = tvalue; //checking that the type variable is properly found
}
Try adding an event listener to your code so the JavaScript is separated from the HTML markup. Like so:
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.addEventListener("click",generateLocations()) ;
}
else if (tvalue == "stats"){
nextButton.addEventListener("click",generaCategories()) ;
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
You can test if the event listener is working by adding a console log on the functions you are executing.
Source: https://www.w3schools.com/js/js_htmldom_eventlistener.asp

How to disable a text-box when clicking on other radio-buttons using a single function in javaScript?

I want to disable the text-box (its id is text1), when clicking on other radio buttons using a single function. According to my code the text-box is showing when the user is clicking on the radio button (its id is rd_other). But when the user clicking on the other radio buttons, after clicking the above radio button (its id is rd_other) the text-box is not disabling.
Here is HTML my code.
<input type="radio" name="rd_other" id="rd_other" value="rd_other" data-toggle="radio" onchange="enableText()">Other (please specify)
<input type="text" name="text1" id="text1"class="form-control input-sm jfl" readonly="readonly" style="display: none;"/>
<input type="radio" name="rdn1" id="rdn1" value="rdn1" data-toggle="radio">I haven't received the disc
<input type="radio" name="rdn2" id="rdn2" value="rdn2" data-toggle="radio">I lost or damaged the protective cover
Here is my javaScript code.
function enableText() {
var text1 = document.getElementById('text1');
text1.readOnly = false;
text1.style.display = 'block';
}
Firstly, to make sure there are no confusions, onchange will only fire when a radio button is selected.
Secondly, you would have to hook up an onchange function to the two other radio buttons. The function below should work.
function disableText() {
var text1 = document.getElementById('text1');
text1.readOnly = true;
text1.style.display = 'none';
}
like this
function disable() {
//one radio button
var radio = document.getElementById("your_radio_button_id");
var checkbox = document.getElementById("your_checkbox_id");
if (radio.checked == true) {
checkbox.disabled = true;
}
}
or like this
function disable() {
var radios = document.getElementsByName("your_radio_button_group_name");
var checkbox = document.getElementById("your_checkbox_id");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
checkbox.disabled = true;
}
}
}
You can fix this like this:
window.enableText = function(e) {
var text1 = document.getElementById('text1');
if(e.id == "rd_other2") {
text1.readOnly = false;
text1.style.display = 'block';
}
else{
text1.readOnly = true;
text1.style.display = 'none';
}
}
please check the full example here :)

Categories