My table is not hiding when using Javascript - javascript

I want to hide or show my spinner depending on what is selected in the radio button. The spinner is displayed in a table. If the user chose yes (radio button), it will display the table which the spinner is in, if the user chose no (radio button), it will hide the table the spinner is in.
I researched on Google the best way to use style in JavaScript and the one I most commonly found was using (variable).style.(css property).
I have tried this but it hasn't worked. What I want to know is that am I coding this wrong (it is not showing anything in error console and it seems right with the examples I have followed) or do I need to do it another way when it comes to display and hiding tables?
Below is my HTML code:
<table id="tblWeight">
<tr>
<th>6: Provide a Total Weight for your Session</th>
<td><input type="radio" name="weightChoice" value="yes" onClick="getWeight()"/> Yes</td>
<td><input type="radio" name="weightChoice" value="No" onClick="getWeight()"/> No</td>
</tr>
</table>
<div id="radioAlert"></div>
<br/>
<table>
<tr>
<th>Weight (%):</th>
<td class="spinner"><input type="text" class="spinnerWeight" name="txtWeight" id="txtWeight"></td>
<td><button class="scrollBtn" id="btnWeightUp" type="button"><img src="Images/black_uppointing_triangle.png" alt="Increase" /></button>
<button class="scrollBtn" id="btnWeightDown" type="button"><img src="Images/black_downpointing_triangle.png" alt="Decrease" /></button></td>
</tr>
</table>
<div id="weightAlert"></div>
<br/>
<table><tr><th>7: Module:</th>
<td><?php echo $moduleHTML; ?></td>
</tr>
</table>
Below is JavaScript code:
function getWeight() {
var weightChoice = document.getElementsByName("weightChoice");
var textWeight = document.getElementById("txtWeight");
var tableWeight = document.getElementById("tblWeight");
if(weightChoice[0].checked == true){
tableWeight.style.visibility=="visible";
textWeight.value == 0;
} else {
tableWeight.style.visibility=="hidden";
textWeight.value == 0;
}
}

Your assignment statements are written with doubled "=" characters, which makes them not be assignment statements.
if(weightChoice[0].checked == true){
tableWeight.style.visibility = "visible";
textWeight.value = 0;
}else{
tableWeight.style.visibility = "hidden";
textWeight.value = 0;
}
The "==" is a comparison operator, so your statements were not syntactically erroneous and thus no errors were reported.

You're using == to assign, when == is an equality comparison operator. It should be =:
function getWeight() {
var weightChoice = document.getElementsByName("weightChoice");
var textWeight = document.getElementById("txtWeight");
var tableWeight = document.getElementById("tblWeight");
if(weightChoice[0].checked) {
tableWeight.style.visibility = "visible";
textWeight.value = 0;
} else {
tableWeight.style.visibility = "hidden";
textWeight.value = 0;
}
}
Also, == true, which I removed, is never necessary. I repeat - never. Anywhere you use == true, just take it out.

Related

How to create a html/javascript table that automatically selects radiobuttons?

I have only very basic html/javascript understanding.
I am trying to make what is probably only a slight modification to an existing code. Below is, first the original code, and then how I'd like to change it.
Original code:
A table gives the user a choice between left and right for several rows. The table enforces at most a single switch point from left to right going down the table, meaning that if the user chooses right at some row, the table automatically selects right for all rows below, and if the user chooses left at a given row, the table automatically selects left for all rows above. No switch point at all is allowed (meaning left is selected for all rows, or right is selected for all rows). A selection is required for each row (the app checks for this by default already).
{{ block content }}
<table class="table table-striped">
<colgroup>
<col width="45%">
<col width="10%">
<col width="45%">
</colgroup>
<tr>
<td align="right"><b>Option A</b></td>
<td></td>
<td align="left"><b>Option B</b></td>
</tr>
{{ for amount in player.right_side_amounts }}
<tr>
<td align="right">
<b>{{ player.left_side_amount }}</b> now
<td align="middle">
<input type="radio"
value="left"
name="{{ amount|json }}"
required>
<input type="radio"
name="{{ amount|json }}"
value="right" data-amount="{{ amount|json }}"
required>
</td>
<td align="left">
<b>{{ amount }} </b> next month
</tr>
{{ endfor }}
</table>
{{ formfield_errors 'switching_point' }}
<input type="hidden" name="switching_point" id="id_switching_point"
value="9999">
{{ next_button }}
{{ endblock }}
{{ block scripts }}
<script>
$(document).ready(function () {
$('input[type=radio]').change(
function () {
var clickedRadio = this;
var afterClickedRadio = false;
var radios = document.querySelectorAll('input[type=radio]');
for (i = 0; i < radios.length; ++i) {
var radio = radios[i];
if (radio === clickedRadio) {
afterClickedRadio = true;
continue;
}
if (!afterClickedRadio && clickedRadio.value === 'left' && radio.value === 'left') {
radio.checked = true;
}
if (afterClickedRadio && clickedRadio.value === 'right' && radio.value === 'right') {
radio.checked = true;
}
}
}
);
$('.otree-btn-next').click(function () {
var radios = document.querySelectorAll('input[type=radio]');
for (i = 0; i < radios.length; ++i) {
var radio = radios[i];
if (radio.value === 'right' && radio.checked) {
$('#id_switching_point').val(radio.dataset.amount);
break;
} else {
$('#id_switching_point').val(9999);
}
}
});
});
</script>
{{ endblock }}
This is how the original table looks:
original table
Modification:
Just as in the original, I'd like to have the table with a left/right choice, and enforce at most a single switch point. But, I'd like user to have the possibility to express indifference between the left and right choice at the switch point.
In other words, at the row the user chooses to switch from option A to option B, he could choose either "I prefer B" or "I am exactly indifferent between A and B".
I envision a table with three radio buttons per row, where the center button means “I am indifferent”. At whichever row the user chooses to switch ($17 in this image: what I envision) the user could select either the center button (which would express exact indifference) or the right button (which would express preference for option B). Regardless of whether the user chooses center or right button, all rows above would get checked for A, and all rows below would get checked for B. The center button can be selected at most once, since all rows below would be automatically selected right, and all rows above would be automatically selected left.
I think a second variable would need to be created relative to the original code, to record not just the switching point, but also whether the switching point occurred with indifference or strict preference.
Thank you so much for any help.
How's this? If I understood you correctly, then the rules are:
Selecting A checks all A inputs
Selecting B checks all B inputs
Selecting X will make all inputs below the X selection to be the opposite of the first checked input and everything above the X selection defaults to the first checked input selection. (If A, then B after the X. If B, then A after the X)
Prevents selecting more than one X. If more than X, the last checked X will prevail, the previous X changes according to rule 3.
In addition to those rules, I disabled the first and last middle inputs because you didn't say what happens if the first or last middle inputs are checked. Also, I added logic that prevents the user from checking any middle input before anything else is selected since you didn't say what happens in that situation either.
There are some edge cases I didn't code for, but this is more than enough to cover your rules.
https://jsfiddle.net/j1vas2x8/
<table>
<tr>
<th>A</th>
<th>X</th>
<th>B</th>
</tr>
<tr>
<td><input type="radio" name="r1[]" value="A"></td>
<!-- if the first middle selection is not disabled, then which column is the opposite of it? -->
<td><input type="radio" name="r1[]" value="X" disabled="disabled"></td>
<td><input type="radio" name="r1[]" value="B"></td>
</tr>
<tr>
<td><input type="radio" name="r2[]" value="A"></td>
<td><input type="radio" name="r2[]" value="X"></td>
<td><input type="radio" name="r2[]" value="B"></td>
</tr>
<tr>
<td><input type="radio" name="r3[]" value="A"></td>
<td><input type="radio" name="r3[]" value="X"></td>
<td><input type="radio" name="r3[]" value="B"></td>
</tr>
<tr>
<td><input type="radio" name="r4[]" value="A"></td>
<td><input type="radio" name="r4[]" value="X"></td>
<td><input type="radio" name="r4[]" value="B"></td>
</tr>
<tr>
<td><input type="radio" name="r5[]" value="A"></td>
<!-- if the last middle selection is not disabled, then what should should happen if it's selected last? -->
<td><input type="radio" name="r5[]" value="X" disabled="disabled"></td>
<td><input type="radio" name="r5[]" value="B"></td>
</tr>
</table>
var header_row = document.querySelectorAll('table tr th');
var column = {
'left': header_row[0].innerText,
'middle': header_row[1].innerText,
'right': header_row[2].innerText
};
var radios = document.querySelectorAll('input[type="radio"]');
var rows = document.querySelectorAll('table tr');
Array.from(radios).forEach(function(radio) {
radio.addEventListener('click', function(event) {
var is_more_than_one_middle_column_selected = document.querySelectorAll('input[type="radio"][value="' + column.middle + '"]:checked').length > 1;
if (is_more_than_one_middle_column_selected === true) {
// loops through all radio inputs with the middle column checked
Array.from(document.querySelectorAll('input[type="radio"][value="' + column.middle + '"]:checked')).forEach(function(input) {
if (input !== event.target) {input.checked = false;}
});
}
var current_row_index = Array.from(rows).findIndex(function(row) {
var current_input = Array.from(row.querySelectorAll('td input[type="radio"]')).find(function(input) {
return input === event.target;
});
return !!current_input;
});
var middle_selected_input_row_index = Array.from(rows).findIndex(function(row) {
return row.querySelector('input[type="radio"][value="' + column.middle + '"]')?.checked === true;
});
var is_middle_input_selected = middle_selected_input_row_index > -1;
let first_input_column = rows[1].querySelector('input[type="radio"]:checked')?.value || '';
// if the first input has not been checked but a middle input somewhere else has
if (!first_input_column && is_middle_input_selected === true) {
// uncheck the current input, and stop the script here; if script keeps going it will run into null errors
return event.target.checked = false;
}
for (var row_index = 1; row_index < rows.length; row_index++) {
// if the middle input is not checked yet
if (is_middle_input_selected === false) {
// whatever selection the current value, change all inputs to that
rows[row_index].querySelector('input[type="radio"][value="' + event.target.value + '"]').checked = true;
}
else if (is_middle_input_selected === true && row_index < middle_selected_input_row_index) {
// check the previous input to whatever the first checked input value was
rows[row_index].querySelector('input[type="radio"][value="' + first_input_column + '"]').checked = true;
}
else if (is_middle_input_selected === true && row_index > middle_selected_input_row_index) {
// check the previous input to whatever the first checked input value was
rows[row_index].querySelector('input[type="radio"][value="' + (first_input_column === column.left ? column.right : column.left) + '"]').checked = true;
}
// if the current input checked was the input that triggered this logic, and a there was more than one middle input that was checked
else if (row_index === current_row_index && is_more_than_one_middle_column_selected === true) {
// get the first checked input value
let first_input_column = rows[1].querySelector('input[type="radio"]:checked').value;
// check the previous input to whatever the first checked input value was
rows[row_index - 1].querySelector('input[type="radio"][value="' + first_input_column + '"]').checked = true;
}
}
});
});

Adding different EventListeners to multiple buttons on a page

Some background: I've been working on a Dark Souls II statistical calculator. I have a table with buttons that will allow you to either add or subtract a value to any of the primary stats. This will then update the stats on the page, which will eventually tell you how many souls (experience points) you need to get to that soul level.
Anyway, I want to use pure Javascript to addEventListeners to each of the buttons to achieve this goal. The problem is, I have been adding them with several different calls and I was just curious if there was a more efficient way about doing this. The following code samples will show you my verbose solution, which I'm fairly certain can be trimmed down for brevity. If you can answer my question in pure Javascript it would be regarded higher than with jQuery, but if you come up with a jQuery solution I would still be very appreciative. I think an elegant solution to this problem is quite possible, but I am at a loss.
Here is a code sample with three buttons.
HTML snippet (this is obviously within the body tag):
<tr id="rowVigor">
<td>Vigor</td>
<td id="baseVIG">0</td>
<td class="increased" id="increasedVIG">0</td>
<td id="currentVIG">0</td>
<td><input type="button" value="-" class="buttonSubtract" id="minusVIG"/></td>
<td><input type="button" value="+" class="buttonAdd" id="addVIG"/></td>
</tr>
<tr id="rowEndurance">
<td>Endurance</td>
<td id="baseEND">0</td>
<td class="increased" id="increasedEND">0</td>
<td id="currentEND">0</td>
<td><input type="button" value="-" class="buttonSubtract" id="minusEND"/></td>
<td><input type="button" value="+" class="buttonAdd" id="addEND"/></td>
</tr>
<tr id="rowVitality">
<td>Vitality</td>
<td id="baseVIT">0</td>
<td class="increased" id="increasedVIT">0</td>
<td id="currentVIT">0</td>
<td><input type="button" value="-" class="buttonSubtract" id="minusVIT"/></td>
<td><input type="button" value="+" class="buttonAdd" id="addVIT"/></td>
</tr>
Javascript snippet:
window.onload = function()
{
//Global event listeners - Buttons
//VIGOR
document.getElementById("addVIG").addEventListener("click", function(){ addOne("increasedVIG"); }, false);
document.getElementById("minusVIG").addEventListener("click", function(){ minusOne("increasedVIG"); }, false);
//ENDURANCE
document.getElementById("addEND").addEventListener("click", function() { addOne("increasedEND"); }, false);
document.getElementById("minusEND").addEventListener("click", function() { minusOne("increasedEND"); }, false);
//VITALITY
document.getElementById("addVIT").addEventListener("click", function() { addOne("increasedVIT"); }, false);
document.getElementById("minusVIT").addEventListener("click", function() { minusOne("increasedVIT"); }, false);
}
//The functions calls and objects within these two functions are for updating statistical values.
function addOne(id)
{
console.log(id);
id = document.getElementById(id);
id.innerText = parseInt(id.innerText) + 1;
player.SoulLevel++;
updateAll();
}
function minusOne(id)
{
console.log(id);
id = document.getElementById(id);
if (parseInt(id.innerText) != 0)
{
id.innerText = parseInt(id.innerText) - 1;
player.SoulLevel--;
updateAll();
}
}
Now, the above code works, but the problem is that there are nine statistics (I only showed three) and it's getting very wordy. Is this the proper way to do something like this? Should I even be concerned?
Here's an idea I had that did not end up working...(Same HTML as above)
Javascript snippet:
//suffix has global scope
var suffix = ["VIG", "END", "VIT"];
window.onload = function()
{
for (var i = 0; i < suffix.length; i++)
{
document.getElementById("add" + suffix[i]).addEventListener("click", function(){ addOne("increased" + suffix[i]); }, false);
document.getElementById("minus" + suffix[i]).addEventListener("click", function(){ minusOne("increased" + suffix[i]); }, false);
}
}
When you click the plus or minus buttons, the console.log(id) returns increasedundefined, so I'm guessing you can't create event listeners this way. Any ideas?
Here is one option that you might find useful:
Note the use of the new data-* attribute:
<div id="statsHome">
<tr id="rowVigor">
<td>Vigor</td>
<td id="baseVIG">0</td>
<td class="increased" id="increasedVIG">0</td>
<td id="currentVIG">0</td>
<td><input type="button" value="-" class="buttonSubtract" data-type="increasedVIG"/></td>
<td><input type="button" value="+" class="buttonAdd" data-type="increasedVIG"/></td>
</tr>
</div>
In this case, I'm going to loop and add to the buttons rather than using delegation. It was kind of a toss up, though, really.
function addHandler(button, mode) {
if (mode === "add") {
button.addEventListener("click", function() {
var stat = this.getAttribute("data-type");
addOne(stat);
}, false);
} else {
button.addEventListener("click", function() {
var stat = this.getAttribute("data-type");
minusOne(stat);
}, false);
}
}
var statsHome = docuemt.getElementById("statsHome");
var buttons = statsHome.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
if (button.className === "buttonSubtract") {
addHandler(button, "subtract");
}
if (button.className === "buttonAdd") {
addHandler(button, "add");
}
}
Nothing is wrong with your code, other than not calling a named event handler function and a scope issue on your index variable within your current event handler

Form validation linking fields as required

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.
Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/
So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>
This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

Javascript Drop Down

I'm working on a form that has multiple drop downs which get checked whether the user has selected something or not. Most fields are mandatory so upon clicking submit, red text replaces the black, showing which have to be filled in. It isn't validating for some reason or doing what it is i'm trying to accomplish. Other fields that have a id such as 'literature' work fine but this doesn't. Could it be because it's numeric?
Javascript:
var lit = document.getElementById("012");
var hasLeadLiterature = false;
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
if (!hasLeadLiterature){
changeCSS("lbl_literature", "errored");
ErrorText=ErrorText+"11";
}
------
if (submitcount != 0){
alert("This form has already been submitted. Thank you!");
return;
}
/** Submit form check */
if (ErrorText == ""){
submitcount++; form.submit();
} else{
return;
}
------
HTML:
<TR>
<TD width="30%" valign="middle" ALIGN="left"><LABEL id="lbl_literature" for="lbl_literature" class="normal">How would you prefer to receive<br /> literature?: <SPAN class="required">*</SPAN></LABEL></TD><TD width="70%" valign="top" ALIGN="LEFT">
<TABLE>
<TR>
<td class="text_input"> <!-- 012 -->
<select id="012" name="012" title="Literature Preference">
<option value="None">--None--</option>
<option value="Print">Print</option>
<option value="Digital">Digital</option>
</select>
</td>
</TR>
</TABLE>
</TD>
</TR>
Any help would be much appreciated!!
Thanks in advance!
I believe there is a problem with your for loop, it is not looping anything, have you checked it does loop?
I suggest you read up about how to use a for loop, correct code will be more like:
for (var i=0; i<lit.length; i++)
Because this loop is not valid hasLeadLiterature never changes which by the nature of your code bypasses everything.
It looks like your validation is checking the opposite condition. Take a look:
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
If you get rid of the unnecessary loop structure, you're doing this:
if (lit[0].selected === true) {
hasLeadLiterature = true;
}
In this case, lit[0] is the first, empty option element in the select element. So your condition is saying that if the empty option is selected, the form validates. Shouldn't you reverse that condition? Something like this:
if (lit[0].selected === false) {
hasLeadLiterature = true;
}

Using javascript to check if a radio button is selected and return a specific answer based on the selection

I am looking, in the cleanest way possible to be able to take a simple yes or no question and test for which answer has been chosen.
For instance in this case if a "yes" I want it to return a value of "Continue" into a specified area (a 3 column table which has a question in the first, the radio buttons in the second, and I want it to update and display the answer in the third).
My code for the JS stands thus far:
<script type="text/javascript">
var answer = 'place-holder';
var user_input;
function checkForm()
{
var substanceab = document.getElementById('Sub');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab.length[i].checked)
{
user_input = substanceab.length[i].value;
}
}
if (user_input ="yes")
{
return answer = "Continue";
}
else if (user_input ="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm[user_input];
};
</script>
and the Body text (minus the actual question):
<table class="table table-bordered">
<tr>
<td width="58%"><center><strong>Required:</strong></center></td>
<td width="19%"></td>
<td width="23%"><center><u><strong>___________</strong></u></center></td>
</tr>
<tr>
<td> <span class="sub depend"> <strong><i>_________</i> </strong></span></td>
<td> <span class="sub depend ans">
<form name="Substance">
<label class="radio inline">
<input type="radio" value="yes" name="substance" onclick="writeAns()">
yes </label>
<label class="radio inline">
<input type="radio" value="no" name="substance" onclick="writeAns()">
no </label> </form></span></td>
<div id="answerwrite"></div>
<script type="text/javascript">
document.write("<td>" + writeAns() + "</td>")
</script>
</tr></table>
Ok, fixed the 'funk' but like I said, more used to java than javascript, completely tougher syntax. I agree, I only used the ID thing to try and get this to work with a different method, but it never did. Now with some of the suggestions it is just giving me undefined everywhere. And while I agree this will eventually turn to jquery, I have NO clue how to work with it, hence figuring out this in javascript first.
A few things:
document.getElementByID()
will always return the first element, as ID's are supposed to be unique.
Instead, use:
document.getElementsByName('substance');
Next, in your loop, you are improperly referencing the array's members using the .length property. Try this instead:
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
Finally, in javascript, the '=' opertator is always an assignment statement. To do comparisons, always use '==':
if (user_input == "yes")
{
return answer = "Continue";
}
else if (user_input =="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
Also, try to avoid global variables whenever possible.
Here is the working code, refactored a bit:
<input type="radio" value="no" id= "Sub" name="substance" onclick="writeAns()">
function checkForm()
{
var user_input;
var substanceab = document.getElementsByName('substance');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
if (user_input == "yes")
{
return "Continue";
}
else if (user_input =="no")
{
return "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm();
};
Very easy if you are using JQuery.
Ensure your elements have the same "name" attribute and use:
var RadioGroupResult = $('input[name="MyRadioGroupNameHere"]:checked').val();
Nice and simple.

Categories

Resources