[javascript]radio button jumps to first option - javascript

I have a standard html from with a couple of radio buttons (3 of them actually).
With:
function abo_show()
{
var x = document.gms_option.gms_element1;
console.log(x.value);
if (x.value = "1") {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="table-row";
document.getElementById("gms_abo3").style.display="table-row";
}
else {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="none";
document.getElementById("gms_abo3").style.display="none";
}
}
I try to show a couple of extra buttons, based on the first 3. The new ones are in a div "abo", that is hidden by default (in css: "display:none").
But when I click on a radio button to select, it executes and jumps to option 1.
No idea why. Could someone explain and help?

x.value = "1" because of this.
you use a single = doing an assignment not a comparison. This causes the if to always succeed. just use == or even ===instead.

You have an easy = in an if statement. Its not compared, it is set.
Your code sets x.value to "1" instead of comparing it.
Use:
if(x.value=="1") {

Related

Javascript disabled button if checkboxes are not choosen - problem

I wrote a code, that make the button not disabled when you check at least one checkbox with class "sum".
I want to change the code, so I have to classes for and you can check only one checkbox (or two of them) to make the button not disabled.
This is what I have and it works with only one class:
var checkBoxes = $('.sum');
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum').change();
});
This is what I tried to do, but OR op does not work:
var checkBoxes = $('.sum' || **'.checkAll'**);
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum' || **'.checkAll'**).change();
});
The code works with && operator, but I do not need this.
Using the OR operation on strings this way does not make sense. If you do this with two non-empty strings, you always get the first operand:
console.log('a' || 'b')
In order to select multiple elements, you just separate them by comma:
var checkBoxes = $('.sum, .checkAll');
The code works with && operator, but I do not need this.
Not really. 'a' && 'b' always returns 'b'.
You could check for the amount of checked inputs then add/remove the disabled property in the change event handler.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if (checkBoxes.filter(':checked').length > 0) {
$('#dashboardbuttonpay').prop('disabled', null);
} else {
$('#dashboardbuttonpay').prop('disabled');
}
});
This way you capture if one or more checkboxes are checked before remove the disabled attribute of the button. Which lets you enable the button with either one or both checkboxes selected.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if(checkBoxes.filter(':checked').length > 1)
$('#dashboardbuttonpay').prop('disabled',true);
else
$('#dashboardbuttonpay').prop('disabled',false);
});

Javascript - want to press button repeatedly and have same function trigger

I'm making a quiz in Javascript and I want to be able to use the same button over and over for answers without reloading the page. Here's my code:
document.getElementById("nextBtn").addEventListener("click", function() {
let answers = document.getElementById('answers').value;
let inputAns = [0, 1, 2];
for (var i = 0; i < inputAns.length; i++) {
if (answers == inputAns[i]) {
document.getElementById("correctAnswers").innerHTML = "✅";
inputAns++;
} else {
document.getElementById("incorrectAnswers").innerHTML = "❌";
inputAns++;
}
}
});
and
<button type="submit" id="nextBtn" class="nextBtn">NEXT!</button>
</div>
<div class="correctAnswers" id="correctAnswers"></div>
<div class="incorrectAnswers" id="incorrectAnswers"></div>
So when the button (nextBtn) is pressed, it reads the input bar (answers) and checks to see if that matches the input of the array (inputAns). If it matches, a green check is displayed. If it doesn't, a red x is displayed. Then the loop adds to the array to make the answer change for the next question. This works one time. But when the button is pressed again, nothing happens. How can I make the function repeat so that more questions can be checked and checks or x's can appear? Thanks!
ETA: More HTML
The first thing you'll want to do is turn your .innerHTML to append rather than replace (with +=).
You'll also want to make use of a true equals in the conditional, or else an empty answer will be treated as the same thing as 0, and thus be valid for the first answer. If you do this, you'll also want to make use of parseInt(answers) rather than just answers.
After this, you'll want to shift your input array outside of your function, and set up a current answer variable as well. This should reference the first index of the array.
From here, you'll want to completely remove your loop, and simply run inputAns.shift() inside of your 'success' criteria; this will remove the first element in the array. Because of this, you're able to run the comparison against currentAnswer = inputAns[0]. If the first element is removed, the answer will be compared against the second element, and so on until all answers have been given.
Finally, you'll probably want to add a message or 'stop' condition when all answers have been entered. This can be done by checking if (!inputAns.length).
This can be seen in the following, where the correct answers are 0, 1, 12` in order:
let inputAns = [0, 1, 2];
let currentAnswer = inputAns[0];
document.getElementById("nextBtn").addEventListener("click", function() {
let answers = document.getElementById('answers').value;
if (parseInt(answers) === currentAnswer) {
document.getElementById("correctAnswers").innerHTML += "✅";
inputAns.shift();
if (!inputAns.length) {
console.log("All answers provided!");
}
} else {
document.getElementById("incorrectAnswers").innerHTML += "❌";
}
currentAnswer = inputAns[0];
});
<input id="answers" />
<button id="nextBtn">Next</button>
<div id="correctAnswers"></div>
<div id="incorrectAnswers"></div>

Javascript catch unselected radio button along with textboxes and alert

I'm practically new here and i'm a beginner in programming.
I am creating an html/js based template for my team for easy consolidation of data and copy to clipboard so we can easily paste it in our main tool.
The problem is that doesn't seem to work properly (at least here at the office, at home it does work).
It doesn't prompt when the radio selection is empty, so I am resorting to using my current function that catches any textboxes/textarea that is empty. (sample code below)
if (document.getElementById('INbrief').value == "") {
errCatch +="-Issue/Request \n";
valid = false;
}
if (document.getElementById('INdesc').value == "") {
errCatch +="-Issue/Request Description \n";
valid = false;
}
if (!valid) {
document.body.removeChild(dummyTxtArea);
alert(errCatch);
return valid;
} else {
document.body.removeChild(dummyTxtArea);
alert ("Data has been copied to Clipboard.");
}
The above if else is inside a Function that is called when the Evenlistener is triggered via "click" of the submit button. I tried inserting a 'for' statement above the if else inside the function but it wont work and the alert will only show that the textbox/area are empty. Thanks in advance for your help
Your code was throwing errors at lines 4 and 5 when you were trying to get the value of an unchecked radio box and set the variable to that value:
var selectedLOB = document.querySelector('input[name="INlob"]:checked').value; //LOB selected
var selectedSev = document.querySelector('input[name="INsev"]:checked').value; //Severity selected
In order to fix this you must first check if the radio is selected, and then if it is get the value that is selected. You can do that by replaceing your lines 4 and 5 with the following:
var selectedLOB = document.querySelector('input[name="INlob"]:checked') ? document.querySelector('input[name="INlob"]:checked').value :false;
var selectedSev = document.querySelector('input[name="INsev"]:checked') ? document.querySelector('input[name="INsev"]:checked').value :false;
This code will first check to see if the radio is checked, if it is it will set the variable to the value, if it is not it will set the variable to false.
(The a ? b : c is know as the conditional or ternary operator and is just a short if() else()statement). This change will stop the errors from being thrown.
You will also need to update your checks further down for the radios to:
if (selectedLOB == false) {
errCatch +="-Choose LOB \n";
valid = false;
}
if (selectedSev == false) {
errCatch +="-Choose Severity \n";
valid = false;
}
As a side note you don't have to set uncheck radios to false, you could set them to a string like 'unchecked' or ''empty' if it helps make your code more readable. Just be sure to make sure that your checks match what you set it to.

Show field if true, hide field if false?

Want to have a notification box displayed if amount in fieldA is higher than amount in fieldB.
Currently have some code working but the notification box toggles on and off not depending on the actual amount.
What am I missing?
jquery:
$(document).ready(function() {
$('#fieldA').change(function(){
if($(this).val()>$('#fieldb').val()){
//display it on the form
$('.labelNotification').toggle();
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
HTML:
< p style="display: none;" class="error labelNotification">
This is tailor-made for the toggle(boolean) method. Also, you have to be careful about appending to the notification label ... what if the user changes his answer twice? It's better to have multiple notification objects, each of which can contain stuff for a single type of notification.
$(function() {
$('#fieldA').change(function() {
var isLarger = +$(this).val() > +$('#fieldB').val(); // Note: convert to number with '+'
var $labelNotification = $('.labelNotification');
$labelNotification.toggle(isLarger);
if (isLarger) {
//display it on the form
$labelNotification.html('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
If you're comparing numerical values (which it seems like you are), you should use parseInt or parseFloat to convert the (string) value returned by val() to an integer. According to the documentation for val, the function always returns a string value.
I found the problem ,
First thing is you need to have semicolon properly as below
$('#fieldA').change(function () {
if ($(this).val() > $('#fieldB').val()) {
alert("its greater");
//display it on the form
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
$('.labelNotification').show();
}
else {$('.labelNotification').hide();
$('.labelNotification').html('');}
});
Second thing , when you toggle it it won't show for the second time
if 40 > 30
and again if you entery 50 and 50 > 30 it won't show
this is second problem
final problem is empty the label all the time
$('.labelNotification').html('')'
Toggle is not the best approach for your situation.
You want to compare and then decide.
Since you are looking at numbers I would strongly suggest using a number type to do the comparison, either using parseInt() or parseFloat().
The text in the notification label only needs to be set once, since you don't have any comment for it showing something when B > A. I would suggest setting this in your HTML.
<span class="labelNotification" style="display:none">Your Warning Text</span>
<!-- if your CSS class has `display:none` remove the style attribute -->
as for the jQuery.
$(function() {
$("#fieldA").change(function() {
var a = parseInt($(this).val());
var b = parseInt($("#fieldb").val());
// handle if a or b is not a number --> isNaN(a) || isNaN(b)
if( a > b ) {
$('.labelNotification').show()
} else {
$('.labelNotification').hide()
}
});
});

What is wrong with this simple javascript function to swap the CSS class of an HTML body?

I've been staring at this for too long. I've put alerts throughout and the flow is correct. The styles exist. The body starts with the "styleBlack" class. The condition of the if statement is met and the body's class becomes "styleLight". A second call meets the condition of the else statement but the innerHTML of mDiv does not change, nor does the class of the body.
function ColorSwap() {
var mDiv = document.getElementById("m_divSwap");
if (mDiv.innerHTML = "Go Light") {
mDiv.innerHTML = "Go Dark";
document.body.className = "styleLight";
} else {
mDiv.innerHTML = "Go Light";
document.body.className = "styleBlack";
}
}
You're assigning instead of comparing
Change
if (mDiv.innerHTML = "Go Light")
to
if (mDiv.innerHTML === "Go Light")
At a first glance, it seems that in your if instead of comparing a string value (with ==)you are assigning (with =).
In my opinion you could use JQuery that is a cross browser standard javascript framework, you could download from here (http://docs.jquery.com/Downloading_jQuery).
Also you could put an id attribute to your body like
And the jquery code could be like this:
function ColorSwap() {
if ($("#m_divSwap").text() == "Go Light")
{
$("#m_divSwap").text("Go Dark");
$("#mybody").removeClass('styleBlack');
$("#mybody").addClass('styleLight');
}
else
{
$("#m_divSwap").text("Go Light");
$("#mybody").removeClass('styleLight');
$("#mybody").addClass('styleBlack ');
}
}
Hope it helps.
Best Regards.
Jose.

Categories