Javascript onsubmit with cgi action? - javascript

I have a html form and have a cgi script running on the action and then I have a javascript onsubmit function that should check if the radio button was filled out otherwise it wont submit.
<script>
function checkscript()
{
.... check if a radio button was clicked otherwise dont submit.
}
</script>
<form action="default.cgi" method="post" onsubmit="return checkscript()" enctype=
"application/x-www-form-urlencoded">
<h1>Choose</h1>
<p><input type="radio" name="Radio" value="1" /><font size="5"
color="#0033CC">Instant Psychology</font><br />
<br />
<input type="radio" name="Radio" value="2" /><font size="5"
color="#CC0000">Instant Geography</font><br />
<br />
<form/>
Can I do this in a Javascript function in the html file or do I need to do that in the cgi script?

The following script works in all browsers. First, gets the inputs on the page, then loops through each checking the name attribute for Radio. As soon as it finds one Radio input that is checked (selected), it returns true which will submit the form. If, however, none of the inputs are checked (selected), the script returns false and prevents a submission.
function checkscript()
{
var inputs = document.getElementsByTagName("input");
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].name === "Radio" && inputs[i].checked) return true;
}
return false;
}

if you can use jquery, you do this
function checkscript(){
if($('#radio-button').is(':checked')) return true;
else return false;
}
and yes, you can just place it in your html file.
Hope this helps.

Related

form action to toggle a function?

<form action="" method="get" >
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
I have the following radio form and when I hit submit, I would like it to toggle some function in my js script. However, if I do something like:
document.getElementById("start").addEventListener('click',function ()...
Nothing works. I think I need something for the action tag, but I can only find examples that link to other websites/pages, which isn't what I want. Is toggling a function possible to do using the forms?
Thanks!
You're on the right track:
document.getElementById("start").addEventListener('click', function(e) {
e.preventDefault();
console.log('start!!');
const selected = document.querySelector('input[name="gender"]:checked');
console.log('you selected: ' + (selected ? selected.nextSibling.textContent : 'null'));
// your code here
});
<form>
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
You don't need an action or a method attribute. Make sure to use e.preventDefault() to prevent the form from submitting (redirecting the page) if you want to handle the form's values yourself.
You can define the submit function on form tag using onsubmit, Also this solution is accurate if you have multiple form tags on the same page.
function submitForm(form, event) {
event.preventDefault();
var val;
var radios = form.elements['gender'];
// loop through list of radio buttons
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) { // radio checked?
val = radios[i].value; // if so, hold its value in val
alert(val);
break; // and break out of for loop
}
}
alert("nothing selected");
return false;
}
<form onsubmit="return submitForm(this,event)">
<label><input type="radio" name="gender" id="male_sub" value="male">male</label><br>
<label><input type="radio" name="gender" id="female_sub" value="female">female</label><br>
<input type="submit" value="Let's Start!" id="start"><br>
</form>

How do I write JavaScript that validates input across multiple forms?

I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.
I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
forms = document.getElementsByTagName("form");
for(i=0; i<forms.length; i++)
{
inputs = forms.item(i).getElementsByTagName("input");
inputs.item(0).onclick = function()
{
if(this.checked)
inputs.item(1).removeAttribute("disabled");
else
inputs.item(1).setAttribute("disabled","disabled");
}
}
</script>
What I expect to happen: the checkboxes change the value of the submit button in the same form.
What actually happens: all the checkboxes change the value of the submit button in the last form.
The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.
Thanks in advance!
Try something like this:
document.body.onchange = function(e) {
// this delegates all the way to the body - if you have a more specific
// container, prefer using that instead.
e = e || window.event;
var t = e.srcElement || e.target;
if( t.nodeName == "INPUT" && t.type == "checkbox") {
// may want to add a className to the checkboxes for more specificity
t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
}
};
The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.

How can I vaildate radio buttons?

How i put validation on check box?
Here is my code:
<script>
function Validate(){
var cntct = document.getElementById("contact").value;
if (cntct.value=="")
{
alert("Please select contact medium");
return false;
}
}
</script>
<input type="radio" name="contact" id="contact" value="SMS">
<label>SMS</label> <input type="radio" name="contact" id="contact" value="CALL">
<label>CALL</label> <input type="radio" name="contact" id="contact" value="EMAIL">
<label>EMAIL</label>
please help..
in case of checkboxes and radiobuttons, the element is checked when the "checked" property is true:
function Validate(){
var selectedValue = "";
var cntct = document.getElementsByname("contact");
for(var i=0;i<cntct.length;i++) {
if (cntct[i].checked)
{
selectedValue = cntct.value;
}
}
if(selectedValue == "") {
alert("Please select contact medium");
return false;
}
return true;
}
UPDATE
I just noticed that you have multiple elements with the same ID. This is not allowed, in such case the browser will return only the last element with that ID. You need to iterate over the elements with the same name and pick one with attribute checked. See the code above
Simple:
if(cntct == "")
{
}
The cntct variable is the value!
How i put validation on check box?
I presume you mean "how do I make sure one of the radio buttons is checked when the form is submitted" (supposing there is a form you haven't shown).
The simple way is to make one checkbox selected by default, then you know that one will always be selected and you don't have to check, e.g.
<input type="radio" name="contact" value="CALL" checked>
<input type="radio" name="contact" value="EMAIL">
The other way is to loop over the radio buttons when the form is submitted (or whatever event you decide to base the validation on) and make sure one is checked. e.g.
function checkButton() {
var nodes = document.getElementsByName('contact');
for (var i=0, iLen=nodes.length; i<iLen; i++) {
// If find a checked one, job's done
if (nodes[i].checked) return true;
}
// Otherwise, none were checked
return false;
}
There is an input type text with a name of contact, but it won't have a checked property so will be treated like an unchecked radio.
Please try this:
<script>
function SubmitIt()
{
if (document.forms.myform.elements.contact.value == "")
{
alert("Please select contact medium...");
}
}
</script>
<form name="myform" id="myform">
<input type="radio" name="contact" id="contact" value="SMS">
<label>SMS</label> <input type="radio" name="contact" id="contact" value="CALL">
<label>CALL</label> <input type="radio" name="contact" id="contact" value="EMAIL">
<label>EMAIL</label>
<button onclick="SubmitIt();">Submit</button>
</form>

Enable/disable a form element after checking radio button checked states

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.
Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Validate HTML using Javascript

I have the following code; I want to make sure that submit does not actually post to the page specified by action unless one of the two radio inputs has been selected. I have tried multiple variations of this and other code, and cannot seem to figure out whats wrong. Whether the radio buttons are selected or not it still posts to somepage.py.
<html>
<head>
<title>
Test Page
</title>
<script language="JavaScript">
function validate(formEntry) {
if (formEntry.Q1.q11.checked != true && formEntry.Q1.q12.checked != true)
return false;
return true;
}
</script>
</head>
<body>
<form action="somepage.py" method="POST" onsubmit="return validate(this);">
<input type="radio" name="Q1" id="q11" value="1" />
<input type="radio" name="Q1" id="q12" value="2" />
<input type="submit" name="Submit" />
</form>
</body>
</html>
If you make one button checked by defualt, then one will always be checked:
<input type="radio" name="Q1" id="q11" value="1" checked>
<input type="radio" name="Q1" id="q12" value="2" >
Or the function can be simply:
function validate(formEntry) {
return formEntry.Q1[0].checked || formEntry.Q1[1].checked ;
}
if either is checked it will return true, otherwise false.
if (!formEntry.Q1[0].checked && !formEntry.Q1[1].checked)
Trying to access input by form_name.input_name.input_id is really strange.
Use jquery validation. Checkout this link for details
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Demo page here:
http://jquery.bassistance.de/validate/demo/
It seems to work, look at:
http://jsfiddle.net/EEgea/
Maybe you'd better use a framework like JQuery to prevent javascript flaws between different browsers
Or use a validation framework like JQuery validation, I highly recommend that.
try your function like :-
function validate(formEntry) {
var radiobtn=document.getElementsByName('Q1');
if(!(radiobtn[0].checked || radiobtn[1].checked))
return false;
return true;
}

Categories

Resources