Javascript validate all radio buttons if checked - validation

Im so dumb in javascript, I would like to ask your help about radio button validation. I have 3 set of questions, each has 3 radio buttons. I want to validate if all the 3 questions have been answered or checked.
Thanks in advance
Here is the code I have tested, it only validates 1 radiobutton
<script type="text/javascript">
function validateForm() {
var radios = document.querySelectorAll("#option1, #option2, #option3, #option4, #option5, #option6");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}
</script>

I have solved the problem with this code
if ($('div.quizbox:not(:has(:radio:checked))').length) {
alert("You missed answering one or more of the questions.");
}

try this it works for me
<script type="text/javascript">
function validateForm(){
var inputs = document.querySelectorAll("#option1,#option2,#option3,#option4,#option5,#option6")
var formValid = false;
for(var i=0;i<inputs.length;i++){
if(inputs[i].checked){
formValid = true;
}
}
if(!formValid ){
alert("Must check some option!");
}
}
</script>
html code
<body>
<form name="frm">
Question 1<br>
<input type="radio" name="group1" value="Ans1" id="option1">Ans1<br>
<input type="radio" name="group1" value="Ans2" id="option2">Ans2<br>
Question 2<br>
<input type="radio" name="group2" value="Ans1" id="option3">Ans1<br>
<input type="radio" name="group2" value="Ans2" id="option4">Ans2<br>
Question 3<br>
<input type="radio" name="group3" value="Ans1" id="option5">Ans1<br>
<input type="radio" name="group3" value="Ans2" id="option6">Ans2<br>
<input type="submit" value="Test" onclick="validateForm();" />
</form>
</body>

Related

Count the number of inputs in a page

Is there a way I can count the number of inputs in a single page?
Say if the page has 5 inputs, a save button will appear- and if there is no inputs on the page, the save button will not appear. How do i do this?
i have this but i dont think this is right
<script>
var x = 0;
var ins = 0;
$(':input').each(function(){
x++;
});
ins = x;
and pass the ins variable to php like
<?php echo '<script>ins</script>';?>
but it doesnt echo anything? is the code right tho
Two line code is enough for you.If you have not any input fields the submit button will be automatically hide.
var inputs = document.querySelectorAll('input');
console.log(inputs);
alert(inputs.length);
if(inputs.length==0)
{
document.querySelector('#button').style.display = 'none';
}
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<button id="button">submit</button>
JS fiddle:
https://jsfiddle.net/njv5e8yc/1/
I am not sure if you actually need to have JavaScript be echoed in php since you can determine count in the first line, but you can not pass javascript to php without ajax. Here is a basic example:
/index.php
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<script>
$(document).ready(function() {
// Get the count of the inputs found
var x = $('input').length;
// Pass the count to php
$.ajax({
url: '/count.php',
data: {
"count": x
},
type: 'post',
// This is what happens with the ajax returns from count.php
success: function(response) {
alert(response);
}
});
});
</script>
/count.php
<?php
if(!empty($_POST['count'])) {
$count = $_POST['count'];
die('The count is: '.$count);
}
You would get an alert dialogue box that says:
The count is: 4

Blank page after submitting external HIT in MTurk

If I submit my external HIT with the https://workersandbox.mturk.com/mturk/externalSubmit URL, it gets succesfully submitted to MTurk (in my requester Sandbox, i can see the result), but for the worker an empty / blank page appears, instead of the confirmation, that her/his HIT got submitted succesfully...
I guess, something with the action-parameter in my form could be wrong...
The HTML-Code of this blank page looks like:
<html><head>
<title><bean:message key="external_submit.title" /></title>
<script type="text/javascript">
function reloadOuterPage() {
var boxes = top.document.getElementsByName('autoAcceptEnabled');
if( boxes.length == 0 || !boxes[0].checked ) {
top.location = top.document.getElementById('hitExternalNextLink').href;
} else {
top.location = top.document.getElementById('hitExternalNextAcceptLink').href;
}
};
</script>
</head>
<body onload="reloadOuterPage();"><bean:message key="external_submit.body">
</bean:message></body></html>
The form I'm submitting:
<form target="_parent" name="hitForm" style="visibility:hidden" id="hitForm" method="POST"
action="https://workersandbox.mturk.com/mturk/externalSubmit">
<input type="hidden" id="assignmentId" name="assignmentId">
<input type="hidden" id="hitId" name="hitId"/>
<input type="hidden" id="workerId" name="workerId"/>
<input type="hidden" id="caption" name="caption" value="TEST">
<input type="submit" name="Submit" id="submitButton" value="submit" disabled="true">
</form>
<button ng-show="!hasAccepted()" disabled>You must first accept the HIT in order to Submit it!</button>
<button ng-click="submitHit(inputText)" ng-show="hasAccepted()">Submit</button>
where the submitHit Method looks like this (the ids get assigned properly - i checked that):
$scope.submitHit = function (cap) {
$scope.form = document.getElementById("hitForm");
$scope.assignmentId = "";
$scope.hitId = "";
$scope.workerId = "";
$scope.assignmentId = $scope.turkGetParam("assignmentId");
$scope.hitId = $scope.turkGetParam("hitId");
$scope.workerId = $scope.turkGetParam("workerId");
document.getElementById("assignmentId").value = $scope.assignmentId;
document.getElementById("hitId").value = $scope.hitId;
document.getElementById("workerId").value = $scope.workerId;
$scope.form.submit();
}
thank you very much for your help!
As always, one works nearly 2 days on this "bug" and after overcoming to ask on stackoverflow, one finds the solution: I had to delete the target="_parent" in my form and now everything works fine!

onclick calling object working ONLY in Firefox

as I stated in the title, I can get the onclick calling object only in Firefox: not in Chrome, not in IE, not in Safari.
I am pretty new to ajax and javascript in general, so I built my code around the answers you guys gave here.
I have a html page with a number of 'products': for each one of them, I have a form with hidden fields which contain the information about the product. Every form has two (submit) buttons: one is to 'add' the product to the shopping cart, the other is to take it 'off' of it.
I want to identify the button that gets clicked in order to identify the product it refers to and then add it to or cancel it from the cart list.
Here is the html code for the page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
TEST
</title>
<meta charset="utf-8">
<script src="form_submit.js" type="text/javascript">
</script>
</head>
<body>
<form id="ajax_1" name="ajax_form" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="1" /><br />
<button id="ajax_1" type="submit" name="on">On</button>
<button id="ajax_1" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_2" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="2" /><br />
<button id="ajax_2" type="submit" name="on">On</button>
<button id="ajax_2" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_3" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="3" /><br />
<button id="ajax_3" type="submit" name="on">On</button>
<button id="ajax_3" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<div id="responseArea"> </div>
</body>
</html>
This is the script code:
window.onload = checkButton;
var xhr = false;
var on;
var stnz;
var opz;
var url;
function checkButton() {
var el = document.getElementsByTagName('button');
for(var i=0; i<el.length; i++){
el[i].onclick = function (e) {
// Capturing the event
e = e || window.event;
var targ = e.target || e.srcElement;
on = (targ.name == 'on') ? true: false;
var form = document.getElementById(targ.id);
url = form.action;
stnz = form.stnz.value;
opz = form.opz.value;
makeRequest();
return false;
};
}
}
function makeRequest(){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr){
var data = "stnz=" + stnz + "&opz=" + opz + "&act=";
if(on){
data = data + "1";
} else {
data = data + "0";
}
xhr.onreadystatechange = showContents;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(data);
}
}
function showContents(){
if(xhr.readyState == 4 && xhr.status == 200) {
var return_data = xhr.responseText;
console.log(return_data);
} else {
var return_data = "Sorry, but I couldn't create an XMLHttpRequest";
console.log(return_data);
}
/*document.getElementById("responseArea").innerHTML = return_data;*/
}
The test.php file is just:
<?php
if (isset($_POST['stnz'],$_POST['opz'],$_POST['act'])){
$stnz= $_POST['stnz'];
$opz = $_POST['opz'];
$act = $_POST['act'];
echo "Stnz: " . $stnz . ", Opz: " . $opz . ", Azt: " . $act;
}
?>
Please, help me fixit this thing for Chrome, IE and Safari....
Also, is there a better way to get the same functionality? (maybe not using forms?)
Thanks a lot!
each browser has its own event handling method , use a library like jquery to be able to handle all the browsers .
$(el[i]).click(function(e){});
using jquery isn't the only solution you can optimize your code for every browser by adding the browser specific codes but that is a recipe for disaster.same goes for your ajax request(cross browser problems).
jquery designed with all the browsers in mind , so you write just one code and jquery handles the browser specific stuff .
example for your ajax with jquery :
https://api.jquery.com/jQuery.ajax/
$.ajax({
url : url,
type:'POST',
data:{"stnz" : stnz , "opz" : opz , "act" : (on ? 1 : 0)}
success : function (data){
},
error:function(){}
});

CKEditor iframe-based plugin and how to return radio value

I have created an iframe-based plugin for CKEDitor using CKEDITOR.dialog.addIframe and want the user to select a radio value, which will be returned to the editor. I am using the code below to try and return the value.
<form name="form1">
<label><input type="radio" name="field_name" value="[value one]" id="field_name_0" onclick="return get_radio_value()" />value one</label><br />
<label><input type="radio" name="field_name" value="[value two]" id="field_name_1" onclick="return get_radio_value()" />value two</label><br />
<label><input type="radio" name="field_name" value="[value three]" id="field_name_2" onclick="return get_radio_value()" />value three</label><br />
</form>
<script language="javascript">
function get_radio_value()
{
for (var i=0; i < document.form1.field_name.length; i++)
{
if (document.form1.field_name[i].checked)
{
var rad_val = document.form1.field_name[i].value;
//alert(rad_val); //this works using onclick
}
}
}
var CKEDITOR = window.parent.CKEDITOR;
var okListener = function(ev) {
this._.editor.insertHtml('<div class="custom_form">'+rad_val+'</div>');
CKEDITOR.dialog.getCurrent().removeListener("ok", okListener);
};
CKEDITOR.dialog.getCurrent().on("ok", okListener);
</script>
I also tried the simple:
var form_value = document.form1.field_name.value;
this._.editor.insertHtml('<div class="custom_form">'+form_value+'</div>');
but this returned "undefined"
Any help or ideas would be appreciated?
Note: Form field values are dynamically created via PHP and fed from a MySQL database.

jQuery ajaxSubmit ignored by IE8

I am combing the jQuery validation plug-in with the jQuery Form Plugin to submit the form via AJAX.
This works perfectly in Firefox & Chrome, but (as usual) Internet Explorer is being a pain. For reasons that are alluding me, IE is ignoring the ajaxSubmit, as a result it submits the form in the normal fashion.
I've followed the validation plug-in's documentation when constructing my code:
JS:
<script src="/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="/js/jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var validator = $("#form_notify").validate({
messages: {
email: {
required: 'Please insert your email address. Without your email address we will not be able to contact you!',
email:'Please enter a <b>valid</b> email address. Without a valid email address we will not be able to contact you!'
}
},
errorLabelContainer: "#error",
success: "valid",
submitHandler: function(form) {$(form).ajaxSubmit();}
});
$('#email').blur(function() {
if (validator.numberOfInvalids() > 0) {
$("#label").addClass("label_error");
return false;
}
else {$("#label").removeClass("label_error");}
});
$('#form_notify').submit(function() {
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});
});
</script>
Form HTML:
<form id="form_notify" class="cmxform" name="form_notify" action="optin.pl" method="get">
<fieldset>
<div class="input">
<label id="label" for="email">Email Address:</label>
<input type="text" id="email" name="email" value="" title="email address" class="{required:true, email:true}"/>
<div class="clearfix"></div>
</div>
<input type="hidden" name="key" value="sub-745-9.224;1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0;;subscribe-224.htm">
<input type="hidden" name="followup" value="19">
<input type="submit" name="submit" id="submit-button" value="Notify Me">
<div id="error"></div>
</fieldset>
</form>
I can't understand what is causing IE to act differently, any assistance would be greatly appreciated.
I can provide more information if needed.
Thanks in advance!
Try the following:
$('#form_notify').submit(function(e) {
e.preventDefault();
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});

Resources