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");
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'.
i have a problem in the following code snippet.
for (var i=0;i<data.parlist.length;i++){
var inp = document.createElement("input")
var label = document.createElement("label")
var labelValue = document.createElement("label")
var subDiv = document.createElement("div")
var br = document.createElement("br")
try{
var dBtn = document.getElementById(data.parlist[i].id);
var dLabel = document.getElementById(data.parlist[i].id + " label")
var dDiv = document.getElementById(data.parlist[i].id +" div");
var inprad = document.getElementById(data.parlist[i].id+" inp_rad");
var dLabelRad = document.getElementById(data.parlist[i].id + " label_rad")
var dSubDiv = document.getElementById(data.parlist[i].id +" div_rad");
dSubDiv.replaceChild(inprad);
dSubDiv.removeChild(dLabelRad);
dDiv.removeChild(dSubDiv);
dDiv.removeChild(dBtn);
dDiv.removeChild(dLabel);
myDiv.removeChild(dDiv);
}catch{
console.log("no")
}
This for loop is inside a function that when clicking on a button of a station shows the parameters.in this way:
What you see in the images works, but the problem that I have come to try to clarify is that when I press the button for example as station 1 appears in the image and then I press the button for example of station 2 the try that is supposed to you must remove the previous parameters with removeChild does not work, the parameters of station 1 remain in the div and the parameters of station 2 are added below these instead of being removed
Within the try there is a problem but I do not know what it is, I say this because when I check the page and open the console I get the message that I left in the catch a "no"
Thanks for reading my problem and any suggestions are welcome as I am desperate to find a solution.
You need to pass 2 inputs to the replaceChild function.
parentNode.replaceChild(newChild, oldChild);
For more info refer Mozilla docs here.
Here is some additional advice
When you log for debugging, use some meaningful messages. In your case you could do
try {
...
} catch (err) {
console.log(err);
}
From the questions nothing is clear about what is there in data.parlist and whether that is implemented properly.
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()
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
I am having some problems removing parts of a var.
function hotBarClick() {
var likeCount = 0;
$.each(companies, function (key, value) {
if (value.liked) {
likeCount++;
}
if (value.liked && value.alreadyliked ==false) {
var content = value.getHtmlLogo();
matchesHtml.add(content);
this.alreadyliked = true;
}
if (value.liked == false && value.alreadyliked == true) {
var discontent = value.getHtmlLogo();
matchesHtml.remove(discontent);
this.alreadyliked = false;
}
});
I am making a app based on html and javascript. You can like/dislike companies in the neighbourhood. If you liked 5 companies or touch the "hotbar" you will see a slider(owl-carousel) with the logos of the companies you liked.
My problem is that if you liked a company first and then dislike it, i cant remove the images from the slider, that were previously shown.
var matcheshtml is the var containing this infomation. You can see that in my code i add stuff by matcheshtml.add() but i cant seem to use the .remove() method here?
How do i remove the good part?
BTW: i think discontent contains the correct value