I am trying to make a Contact form with Radio Buttons and Checkboxes for Packages I intend to offer. The first Radio is for the full Package. The Second Radio Button reveals the Checkboxes that breaks the full package into single options.
What I am trying to achieve is when all checkboxes get checked, the first radio gets checked and all checkboxes get unchecked and are hidden. I managed to get the function to work with one little
var radio1 = document.getElementbyID('radio1');
var radio2 = document.getElementbyID('radio2');
var checkgroup = document.getElementbyID('checkgroup');
var check1 = document.getElementbyID('check1');
var check2 = document.getElementbyID('check2');
var check3 = document.getElementbyID('check3');
var check4 = document.getElementbyID('check4');
$(document).change(function () {
if (radio2.checked) {
checkgroup.style.display = "block";
} else {
checkgroup.style.display = "none";
}
});
$(document).change(function () {
if ((check1&&check2&&check3&&check4).checked) {
check1.checked = false;
check2.checked = false;
check3.checked = false;
check4.checked = false;
checkgroup.style.display = "none";
radio1.checked = true;
}
});
Whenever I check the the checkbox that is last in the if() condition (only the last, not the others) it executes the function which misses the point.
My Goal:
If all get Checked, Execute the Function (Uncheck all, Hide the Checkboxes, Switch back to Radio1). If any 3 get checked nothing should happen.
I feel like i'm missing something, I just don't know what.
Change if ((check1&&check2&&check3&&check4).checked)
to if (check1.checked && check2.checked && check3.checked && check4.checked)
I'm confused that it even worked somewhat since you essentially used && between Javascript objects and not (boolean) variables
Try this: https://jsfiddle.net/h95y86gt/22/
Also, I hope getElementbyID is a typo for document.getElementById()
Related
I would like to run different functions depending if a field is checked or not during page load.
So I use window.onload. The first if condition works great but I would like to add more if conditions as defined below. But it doesn't seem to be the proper way.
I thought I could work with if and if else. Does someone know how to make multiple if conditions work for window.onload function?
<script>
window.onload=function(){
if (document.getElementById("field1").checked) {
document.getElementById("field2").style.color = "red";
}
else if (document.getElementById("field3").checked) {
document.getElementById("field4").style.color = "red";
}
<script>
Added: I would like to add that all functions must be executed if all the if statements are fitting (so if else functions are maybe incorrect in this context). If only field1 is fitting the conditions, only the matching field2 should turn colour of text into red.
It’s not about the colour (that’s just an example for a JS function) - in real I want 3 things: enter value X, turn red and get disabled for future inputs (I already coded that - so not necessary).
UPDATE: Thanks to your comments. I used the code of Emiel Zuurbier: It's working for field 1 until 4 but not for field 10 until 14, did I wrote it wrong?
<script>
const fieldMap = [
['field1', 'field2', 'field3', 'field4'],
['field10', 'field11', 'field12', 'field14']
];
window.onload = function() {
for (const [fieldA, fieldB, fieldC, fieldD] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).value = "X";
document.getElementById(fieldB).style.color = "red";
document.getElementById(fieldB).disabled = true;
document.getElementById(fieldC).value = "X";
document.getElementById(fieldC).style.color = "red";
document.getElementById(fieldC).disabled = true;
document.getElementById(fieldD).value = "X";
document.getElementById(fieldD).style.color = "red";
document.getElementById(fieldD).disabled = true;
}
}
}
</script>
You can eleminate repeating tasks by taking the dynamic parts of your code, in this case your ID selectors, and put them in an array (or object) which you can loop over.
const fieldMap = [
['field1', 'field2'],
['field3', 'field4']
];
window.onload = function() {
for (const [fieldA, fieldB] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).style.color = 'red';
}
}
}
The principle of writing your code like this is called DRY (Don't Repeat Yourself)
winow.onload executes your function() when the page is fully loaded, but it happens just once. If the code you provided is correct then I think you might be missing } at the end. However, there's still one thing that bothers me. If you check if a specified checkbox is checked it checks the checked property only when the page is fully loaded, not when the user clicks on the #field checkbox. If you want the check whether the user checked the checkbox then you can use eventlistener 'check'.
In my PDF form I've got some radio buttons checked by default and I need to make them unchecked before printing the form.
I've tried this but it didn't seem working:
function deleteDefault()
{
for (let x of this.getElementsByClassName("radio")){
x.checked = False;}
}
function deleteDefault()
{
var x = this.getElementsByClassName("radio");
var i;
for (i = 0; i < x.length; i++){
x[i].checked = False;}
}
I even tried to uncheck one after another like so:
function deleteDefault()
{
this.getField("FieldName").checked = False;
}
.. but that didn't work nether.
Can someone please tell me where I'm making a mistake?
Thank you all, I'm just getting started with JavaScript
I figured it out this way:
this.getField("FieldName").value = "Disapproved";
That works for a radio button.
For list box or simple text box this works just fine:
this.getField("FieldName").value = "";
So what I'm trying to do is basically check if the response from the server contains alternatives. If it does then it should print the alternatives out , hide the text area where I would answer the question if the question did not contain alternatives and show the radio buttons. Problem is, it prints out the response, but never hides/shows the text area or the radio buttons.
I tried putting the code for the visibility in a button to see if it works on click, and it does, but it does not work when I put the same code in the if statement.
Also, another problem is that instead of printing out the actual alternatives, it just prints out Object object, but when I try to print out the question, it prints it out correctly.
HideAllRadios and ShowArea functions are basically the same as what's in the if statement, but reversed.
Here is the code:
QuestionReq.onreadystatechange = function(){
if(QuestionReq.readyState === 4 && QuestionReq.status === 200) {
response = JSON.parse(QuestionReq.responseText);
console.log(response);
questionLink.innerText = response.question;
url = response.nextURL;
// questAltLink.innerText = response.alternatives;
if(response.alternatives !=null){
questAltLink.innerText = response.alternatives;
AnswerArea.style.visibility = "hidden";
RadioArea.style.visibility = "visible";
}
HideAllRadios();
ShowArea();
}
Here is how they are declared:
var questions = function () {
var AnswerArea = document.getElementById("AnswerArea");
var RadioArea = document.getElementById("radioplace");
I am using Dojo "dgrid/OnDemandGrid".In that i am using its inbuilt functionality of check-box for each row.
The problem is whenever i am selecting all the check-boxes one by one then its header check-box i.e. select all check-box is not getting checked and same with whenever am deselecting all the check-boxes one by one then the select all check-box didn't get deselected remains in mixed state . There three states True,False and Mixed.
When i was searching a solution for this i found that its a bug in Dojo Dgrid itself.
This is the URL where you can check.DOjo Dgrid Sellect All functionality
Please help me to resolve this issue, Thanks in advance.
The property used to updated the header checkbox (allSelected) is not updated when you select the rows individually. You might be right it might be a bug. Have you reported it?
The workaround solution I could think of is to update the state of the header checkbox yourself. Below is the code to do the same.
grid.on('dgrid-select', function () {
var selectedRows = [];
for (var e in grid.selection) {
grid.selection[e] && selectedRows.push(e)
}
//get the selector column and checkbox from that column
var column = grid.columns["select"];
var headerCheckbox = column._selectorHeaderCheckbox;
if (selectedRows.length === grid.get('total')) {
//update the checkbox when the selection count equal to total count.
headerCheckbox.indeterminate = false;
headerCheckbox.checked = true;
headerCheckbox.setAttribute('aria-checked', 'true');
grid.allSelected = true;
}
});
grid.on('dgrid-deselect', function () {
var selectedRows = [];
for (var e in grid.selection) {
grid.selection[e] && selectedRows.push(e)
}
//get the selector column and checkbox from that column
var column = grid.columns["select"];
var headerCheckbox = column._selectorHeaderCheckbox;
if (selectedRows.length === 0) {
headerCheckbox.indeterminate = false;
headerCheckbox.checked = false;
headerCheckbox.setAttribute('aria-checked', 'false');
grid.allSelected = false;
}
});
Hope this was helpful.
Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone