PHP - Validation radio buttons alert - javascript

i have three radio buttons input within a form. i want alert box appears when user click submit without choose or answer all questions ..
this is my form ..
<tr>
<th> Your attendance<font size="4" > </font></th>
<td> <input type="radio" name ="v1" value = "4" onclick="updateTotal();"/></td>
<td> <input type="radio" name ="v1" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v1" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v1" value = "1" onclick="updateTotal();" /></td>
</tr>
<tr>
<th > Your grades <font size="4" > </font></th>
<td> <input type="radio" name ="v2" value = "4" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "1" onclick="updateTotal();" /></td>
</tr>
<tr>
<th >Your self-control <font size="4" > </font></th>
<td> <input type="radio" name ="v3" value = "4" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "1" onclick="updateTotal();" /></td>
</tr>
i have tried this javascript code .. but it doesn't work no alert appears
<script type="text/javascript">
function validateform()
{
if(document.getElementsByName('v1').value="")
{
alert('Your grades is not selected');
return false;
}
}
</script>

Take this function, you can't use document.getElementsByName('v1').value on a radio group.
Check out this fiddle: http://jsfiddle.net/JXajh/2/
function isOneChecked(name)
{
var buttons = document.getElementsByName(name);
for (var i = 0; i < buttons.length; i++)
{
if (buttons[i].checked)
{
return true;
}
}
return false;
}

That is because the getElementsByName() will return an array of DOM elements, you can't get value or detect if an element is checked directly from this array. You must iterate through all elements check that at least one is checked. So something like this:
function validateForm() {
var radiosToValidate = ['v1', 'v2', 'v3'];
var invalidRadios = [];
for (i = 0; i < radiosToValidate.length; i++) {
var currentRadioArray = documentGetElementsByName(radiosToValidate[i]);
var currentRadioIsValid = false;
for (j = 0; j < currentRadioArray.length; j++) {
if (currentRadioArray[j].checked) {
currentRadioIsValid = true;
break;
}
}
if (currentRadioIsValid === false) {
invalidRadios[] = radiosToValidate[i];
}
}
if (invalidRadios.length > 0) {
alert('At least one radio button has not been selected');
return false;
}
return true;
}

Your comparison has a single =, not a ==. You are assigning and testing "", which is falsy so your if statement will never execute.
The operator to compare two values is ==.
Use this:
if (document.getElementsByName('v1').value== "") {
// ...
}

Related

How do I check 1 checkbox or radial button as N/A and make all the items in the same table also get checked N/A automatically?

I have a simple table with 4 columns.
A row label and 1 column for PASS, FAIL AND N/A.
I have it so each row only allows 1 selection which seems to be working fine.
My header row only has N/A. I want it so if I check N/A in my header row all other rows below in the same table will also be marked N/A automatically.
I'm a novice to HTML and scripts FYI :(
Any help you can provide would be greatly appreciated!
This is what I tried.
<table>
<tr>
<TD><label>HEADING:</label> </td>
<TD><label></label></td>
<TD> </td>
<TD> </td>
<TD><label></label></td>
<TD> </td>
<TD><label>N/A</label></td>
<TD><input type="checkbox" name="HEADING1"id="is_HEADING1"/></td>
</tr>
<tr>
<TD><label>Q1:</label> </td>
<TD><label>PASS</label></td>
<TD><input type="radio" name="Q1" id="is_PASS" /></td>
<TD> </td>
<TD><label>FAIL</label></td>
<TD><input type="radio" name="Q1" id="is_FAIL" /></td>
<TD><label>N/A</label></td>
<TD><input type="radio" name="Q1" id="is_N/A" /></td>
</tr>
<tr>
<TD><label>Q2:</label> </td>
<TD><label>PASS</label></td>
<TD><input type="radio" name="Q2" id="is_PASS" /></td>
<TD> </td>
<TD><label>FAIL</label></td>
<TD><input type="radio" name="Q2" id="is_FAIL" /></td>
<TD><label>N/A</label></td>
<TD><input type="radio" name="Q2" id="is_N/A" /></td>
</tr>
</table>
<script>
function valueChanged() {
if (document.getElementByid("is_PASS").checked == true) {
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 0;
} else {
document.getElementById("is_PASS").value = 0;
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 1;
}
console.log(document.getElementById("is_PASS").value);
console.log(document.getElementById("is_FAIL").value)
console.log(document.getElementById("is_N/A").value)
}
<script>
function valueChanged() {
if (document.getElementByNameId("is_PASS").checked == true) {
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 0;
} else {
document.getElementById("is_PASS").value = 0;
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 1;
}
console.log(document.getElementById("is_PASS").value);
console.log(document.getElementById("is_FAIL").value)
console.log(document.getElementById("is_N/A").value)
}
</script>
I believe I need an if then else scenario that will state
if (document.getElementByid("is_HEADING1").checked == true) {
NAME "Q1" ID"N/A".VALUE = 0
NAME "Q2" ID"N/A".VALUE = 0
: } else {
:}
:<script>
I just don't know the correct syntax to reference an element Name and ID

When non of the options are selected for the checkboxes, how to make the value none?

I've my code below and I'm using an array here. I'm trying to print "None" value when none of the options are selected, but instead when I submit the form I have a few checkboxes selected; it still says "None". Without the else if condition when I choose to not select one of the option, then I get nothing for the result.
I'm not supposed to create a "None" option for the input function.
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
} else if (!extras[count].checked) {
array = ["None"];
}
}
alert("(Including extras: " + array + ")");
}
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>
The problem is that you're replacing array with ["None"] every time there's an empty checkbox, not if all of the checkboxes are empty.
The simplest fix is to check after the loop if array is empty, e.g.:
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
Here it is in a working snippet:
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
alert("(Including extras: " + array + ")");
}
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>

Javascript update multiple form totals from checked boxes

I have a form with various items with checkboxes and those items may be repeated multiple times. I'd like to have another table or form that shows all those items and has a running total for the number of items that are checked and it updates as they are checked.
Let's say I've got the initial form like this:
<form name="myform">
<input type="checkbox" name="model1" value="2">2 x model1
<input type="checkbox" name="model2" value="2">2 x model2
<input type="checkbox" name="model3" value="2">2 x model3
<input type="checkbox" name="model1" value="1">1 x model1
<input type="checkbox" name="model1" value="4">4 x model1
<input type="checkbox" name="model3" value="5">5 x model3
<p>
Totals: <br>
<input type="text" name="totalmodel1" value="0" size="2"><br>
<input type="text" name="totalmodel2" value="0" size="2"><br>
<input type="text" name="totalmodel3" value="0" size="2"><br>
</form>
How can I get the totals to update as the items are checked off. I've used javascript to update lots of other stuff like this and I've found examples that will add up my choices if they are all to be added together, but I haven't been able to successfully make it work with adding multiple items separately.
Any and all help is appreciated.
I made a JS Fiddle as an example of where to start... Here
Basically what I did was:
Relate the input text to checkboxes:
var modelNum = ($(this).attr("name")).slice(($(this).attr("name").length) - 1, $(this).attr("name").length);
var child = "totalmodel" + modelNum;
Make input text only appear if related checkbox is checked:
if (this.checked) {
$("input").each(function() {
if ($(this).attr("name") == child) {
$(this).show();
}
});
} else {
$("input").each(function() {
if ($(this).attr("name") == child) {
$(this).hide();
}
});
}
And show you how to get the value of text (assuming user will enter integer):
$("input").each(function(){ //This is how you get the value of each...
if($(this).is(":text")){
var value = $(this).attr("value");
}
});
So I had previously found an example at http://www.madirish.net/11 that did what I wanted but it was only for one item to total up. I needed to total multiple items separately. I had been trying to modify his code to my needs and it wasn't working, but then I realized his code wouldn't work when I pasted it into jsfiddle. So I tried it on my own server and it worked. I gave up on jsfiddle (I'm sure it's my fault somehow that it didn't work) and began testing on my own server. Here's an example output of what I did to get it to work (please ignore the ugly layout...I didn't need it to be pretty while testing).
<script type="text/javascript">
function checkTotal1() {
document.listForm.total1.value = '';
var sum = 0;
if (document.getElementsByName("choice1").length == 1) {
if (document.listForm.choice1.checked) {
sum = sum + parseInt(document.listForm.choice1.value);
}
} else {
for (i=0;i<document.listForm.choice1.length;i++) {
if (document.listForm.choice1[i].checked) {
sum = sum + parseInt(document.listForm.choice1[i].value);
}
}
}
document.listForm.total1.value = sum;
}
function checkTotal2() {
document.listForm.total2.value = '';
var sum = 0;
if (document.getElementsByName("choice2").length == 1) {
if (document.listForm.choice2.checked) {
sum = sum + parseInt(document.listForm.choice2.value);
}
} else {
for (i=0;i<document.listForm.choice2.length;i++) {
if (document.listForm.choice2[i].checked) {
sum = sum + parseInt(document.listForm.choice2[i].value);
}
}
}
document.listForm.total2.value = sum;
}
function checkTotal3() {
document.listForm.total3.value = '';
var sum = 0;
if (document.getElementsByName("choice3").length == 1) {
if (document.listForm.choice3.checked) {
sum = sum + parseInt(document.listForm.choice3.value);
}
} else {
for (i=0;i<document.listForm.choice3.length;i++) {
if (document.listForm.choice3[i].checked) {
sum = sum + parseInt(document.listForm.choice3[i].value);
}
}
}
document.listForm.total3.value = sum;
}
function checkTotal4() {
document.listForm.total4.value = '';
var sum = 0;
if (document.getElementsByName("choice4").length == 1) {
if (document.listForm.choice4.checked) {
sum = sum + parseInt(document.listForm.choice4.value);
}
} else {
for (i=0;i<document.listForm.choice4.length;i++) {
if (document.listForm.choice4[i].checked) {
sum = sum + parseInt(document.listForm.choice4[i].value);
}
}
}
document.listForm.total4.value = sum;
}
function checkTotal5() {
document.listForm.total5.value = '';
var sum = 0;
if (document.getElementsByName("choice5").length == 1) {
if (document.listForm.choice5.checked) {
sum = sum + parseInt(document.listForm.choice5.value);
}
} else {
for (i=0;i<document.listForm.choice5.length;i++) {
if (document.listForm.choice5[i].checked) {
sum = sum + parseInt(document.listForm.choice5[i].value);
}
}
}
document.listForm.total5.value = sum;
}
</script>
<form name="listForm">
<table>
<tr>
<td align="left" valign="top">
<input type="checkbox" name="choice1" value="1" onchange="checkTotal1()">1 x mod1<br>
<input type="checkbox" name="choice1" value="1" onchange="checkTotal1()">1 x mod1<br>
<input type="checkbox" name="choice2" value="2" onchange="checkTotal2()">2 x mod2<br>
<input type="checkbox" name="choice2" value="2" onchange="checkTotal2()">2 x mod2<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice4" value="1" onchange="checkTotal4()">1 x mod4<br>
<input type="checkbox" name="choice5" value="1" onchange="checkTotal5()">1 x mod5<br>
<input type="checkbox" name="choice5" value="1" onchange="checkTotal5()">1 x mod5<br>
</td>
<td align="left" valign="top">
<table>
<tr>
<th>Product Model</th>
<th>Qty Received</th>
<th>Qty Checked</th>
</tr>
<tr>
<td>mod1</td>
<td align="right">2</td>
<td><input type="text" size="3" name="total1" value="0"></td>
</tr>
<tr>
<td>mod2</td>
<td align="right">4</td>
<td><input type="text" size="3" name="total2" value="0"></td>
</tr>
<tr>
<td>mod3</td>
<td align="right">3</td>
<td><input type="text" size="3" name="total3" value="0"></td>
</tr>
<tr>
<td>mod4</td>
<td align="right">1</td>
<td><input type="text" size="3" name="total4" value="0"></td>
</tr>
<tr>
<td>mod5</td>
<td align="right">2</td>
<td><input type="text" size="3" name="total5" value="0"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>

For loop breaking IndexOf

Well I've ripped my hair off because I assumed I was finished this script but suddenly adding ONE more for loop broke every single indexOf, I tried to create checks so the console wouldn't freak out, but sadly no success. using a static value for "z" or LevelCheck allows for all the indexOfs to work properly but as soon as a for loop is involved, it seems none of the indexOfs wishes to work
<script type="text/javascript">
var tempval = new Array();
function Renew(){ //Reset tempval back to val
for(d=0;d<val.length;d++){
tempval[d] = val[d];
}
}
function UpdateLoop(){
Renew();
var Levels = document.getElementById("Lvl");
if(Levels){
for(z=0; z<=Levels.value; z++){
Update(z);
}
}
}
function Update(LevelCheck){
for (i=0; i<=key.length; i++){
if(key[i] != null){
if ( key[i].indexOf("rate") > -1 ) { //Search through
for (r=0; r<=key.length; r++){
if(key[i].indexOf(key[r]) > -1){ //Finds out which form it should replace
var raw=tempval[i];
for (y=0; y<=key.length; y++){
if(key[i] != "movespeed" && key[i] != "Movrate"){ //add a check to see if string is not there
var item = document.getElementById(key[y]);
if (item) { //Make it use formula value and then put that result into a value and loop back into function until level reached. If level changed to a lower number, reset to original value and repeat
//raw=raw.replace(key[y],document.getElementById(key[y]).value); //replace this with val[y]
raw=raw.replace(key[y],tempval[y]);
}
}
else
break;
}
if(raw != null){
if(raw.indexOf("Mov") > -1){
for(x=0; x<=key.length; x++){
if(key[x].indexOf("movespeed") > -1){
//raw=raw.replace("Mov",document.getElementById(key[x]).value);
raw=raw.replace("Mov",tempval[x]);
break;
}
}
}
if(raw.indexOf("Lvl") > -1){
raw=raw.replace("Lvl",document.getElementById('Lvl').value);
}
if(raw.indexOf("Exp") > -1){
raw=raw.replace("Exp","0");
}
}
if( document.getElementById('Lvl').value == LevelCheck){
alert("Input:"+tempval[i]);
if(key[i] == "Movrate"){
document.getElementById("movespeed").value = eval(raw);
}
else{
var check = document.getElementById(key[r]);
if (check){
document.getElementById(key[r]).value = eval(raw);
}
}
}
else{
tempval[r] = eval(raw);
}
break; //So it doesn't keep searching
}
}
}
}
}
}
</script>
Html portion(This is generated via php so I just used what the browser generated)
<table>
<tbody>
<tr>
<td>Creature Name:</td>
<td>
<input type="Text" name="CName" value="Thing" size="10%">
</td>
</tr>
<tr>
<td>Level:</td>
<td>
<input type="Text" id="Lvl" name="level" onchange="" value="1" size="10%">
</td>
</tr>
<tr>
<td>movespeed:</td>
<td>
<input type="Text" name="movespeed" id="movespeed" value="1" size="10%">
</td>
</tr>
<tr>
<td>str:</td>
<td>
<input type="Text" name="str" id="str" value="4" size="10%">
</td>
</tr>
<tr>
<td>dex:</td>
<td>
<input type="Text" name="dex" id="dex" value="3" size="10%">
</td>
</tr>
<tr>
<td>int:</td>
<td>
<input type="Text" name="int" id="int" value="1" size="10%">
</td>
</tr>
<tr>
<td>will:</td>
<td>
<input type="Text" name="will" id="will" value="2" size="10%">
</td>
</tr>
<script type="text/javascript">
var key=new Array();
var val=new Array();
key.push("movespeed");
val.push("1");
key.push("str");
val.push("4");
key.push("dex");
val.push("3");
key.push("int");
val.push("1");
key.push("will");
val.push("2");
key.push("Movrate");
val.push("Mov+1");
key.push("strrate");
val.push("1+str");
key.push("dexrate");
val.push("1+dex+(str/4)");
key.push("intrate");
val.push("1+int");
key.push("willrate");
val.push("1+will");
</script>
<tr>
<td>
<input type="button" name="button" value="Use Formula" onclick="UpdateLoop();">
</td>
<td>
<input type="submit" value="Save">
</td>
Console:
Uncaught TypeError: Object 2 has no method 'indexOf' Monsters.php:62
Update Monsters.php:62
UpdateLoop Monsters.php:39
onclick Monsters.php:28
you need to change your Update function to the following:
function UpdateLoop(){
var Levels = document.getElementById("Lvl");
if(Levels){
for(z=0; z<=Levels.value; z++){
Renew();
Update(z);
}
}
}
After processing Level 0, the tempval array had the values from Level 0, which wiped out the original values from the val array.
Making this change fixed the problem in my tests: http://jsfiddle.net/jimmym715/xTUND/
oh, and what MaxArt said in the comments above is right on the money... there are far better ways to accomplish what you're going for here
Turns out that flat numbers are NOT strings so in order to safely go through every value .toString() had to be present, thanks everyone for trying though.
so it would look like:
key[i].toString().indexOf(key[r])

Calculate percentage between dynamic number of inputfields

I need to display the percentage each input value contains out of the full dataset.
So if the user inputs 3, 2 and 1. The "percent" inputfield should show "50, 30 and 20"
The thing is, i dont know how many inputs the form will get. It could be from 1 to any number.
The source html code is created by a partial view i created. The output is:
<table>
<tr>
<th>Name</th><th>Distributiob key</th><th>Percent</th>
</tr>
<tr>
<td>
House 1
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 2
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 3
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
</td>
</tr>
First field in the table is the title or name. Second is where the user punches in distribution number. Third is the readonly field with the calculated percentage.
The calculation should be done in javascript, but i cant quite crack the nut on how to get started, getting the inputs and setting the outputs.
A function like this should help (this will round down the percentages- replace the Math.floor if you want to handle differently):
function calcPcts() {
var distributions = $("[id$=DistributionKey]");
// Get the base first
var base = 0;
distributions.each(function () {
base += window.parseInt($(this).val(), 10);
});
// Now calculate the percentages of the individual ones
distributions.each(function () {
var input = $(this),
val = window.parseInt($(this).val(), 10),
pct = (val === 0) ? val : Math.floor((val / base) * 100);
$("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
});
}
If you add a class to the input fields you can use jQuery to get the number of items with that class. Then you can get the values and perform your calculations.
Here is an example:
var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
var total = GetTotal();
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
if (total != 0) {
var percent = inputValue / total;
$('#LightPhysicalEntities_' + i + '__Percent').val(percent);
}
}
});
function GetTotal() {
var total = 0;
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
total += parseInt(inputValue);
}
return total;
}
Here is an example of the script working: http://jsfiddle.net/ZWuQr/

Categories