I know nothing of JavaScript.
I had to add a group of two radio buttons to an HTML form with values "yes" and "no".
Now I need to make them "required"
There are several other required fields in the form and this piece of JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!--
reqd_fields = new Array();
reqd_fields[0] = "name";
reqd_fields[1] = "title";
reqd_fields[2] = "company";
reqd_fields[3] = "address";
reqd_fields[4] = "city";
reqd_fields[5] = "state";
reqd_fields[6] = "zip";
reqd_fields[7] = "phone";
reqd_fields[8] = "email";
reqd_fields[9] = "employee";
function validate(form_obj) {
if (test_required && !test_required(form_obj)) {
return false;
}
It was done by someone else, not me.
What I did is just added my field to this array, like this:
reqd_fields[10] = "acknowledge";
However it doesn't seem to be working.
Please guide me as I am totally ignorant when it comes to JavaScript.
Why don't you just make one selected by default then one will always be selected.
A link to your page or a sample of your HTML would make this easier, but I'm going to hazard a guess and say that the values in the array match the "name" attribute of your radio button elements.
If this the case, "acknowledge" should be the name of both radio buttons, and to make things easier, one should have the attribute "checked" set to "true" so there is a default, so you'll get a value either way.
So, something like this:
<input type="radio" name="acknowledge" value="yes" /> Yes <br/>
<input type="radio" name="acknowledge" value="no" checked="true" /> No <br/>
I know question is ancient but this is a simple solution that works.
<script type="text/javascript">
function checkForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
return false;
}
document.getElementById('submit').value='Please wait..';void(0);
return true;
}
</script>
<form name="formname" onsubmit="return checkForm(this)"
<input type="radio" value="radio1" name="radiobuttonname" style="display:inline;"> Radio 1<br>
<input type="radio" value="radio2" name="radiobuttonname" style="display:inline;"> Radio 2<br>
<input type="submit" value="Submit">
</form>
Without seeing your HTML and more context of your validate function it's unclear exactly what you're looking for, but here's an example of how to require a selected value from a radio group:
<form name="form1">
<input type="radio" name="foo"> Foo1<br/>
<input type="radio" name="foo"> Foo2<br/>
</form>
<script type="text/javascript">
var oneFooIsSelected = function() {
var radios = document.form1.foo, i;
for (i=0; i<radios.length; i++) {
if (radios[i].checked) {
return true;
}
return false;
};
</script>
Here is a working example on jsFiddle.
I always recommend using jQuery validate seems better to me than trying to re-invent the wheel
Related
I've searched all the web about it but i couldn't find a solution in javascript without jquery. The problem is the following: I have an entire array of radio elements, which should be checked or unchecked depending on database data. And this is accomplished. Now i have to make the radio button "uncheckable" to change the database data through the form.
I tried to make it in plain javascript as i don't want to think about frontend libraries for the moment.
The html is the following:
<td>
<input class="graphs" name="g4" value="S" defaultvalue="N" checked="true" type="radio">
</td>
<td>
<input class="graphs" name="g5" value="S" defaultvalue="N" type="radio">
The Javascript is the following:
<script type="text/javascript">
window.onload = (function(){
return function(){
var allRadios = document.getElementsByClassName('graphs');
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(this.checked == true){
this.checked = false;
}else{
this.checked = true
}
};
}
}})();
</script>
I've tried to debug and the result is always the same: the first if is executed and always true, even when the element is not checked.
I've tried the same script in jsfiddle and it works right. Is it a problem of my browser?
Thanks in advance.
this.checked == true in else block is not an assignment
If you want a radio to be uncheckable the you can disable it statically, you don't need to use any javascript.
For Unckecked disabled
<input type="radio" name="foo" value="N" disabled>
Four Checked disabled
<input type="radio" name="foo" value="N" checked disabled>
(Duplicate?) I've tried several Stackoverflow postings related to this, but I cannot get a javaScript example to work. I'd like to avoid having to use jQuery, for the time being.
I want to create the information shown by radio buttons dynamically, using javascript. In this example, I would want to write a function that displays some other values for these radio buttons 'Answer 1' and 'Answer 2'. For example, I don't actually want 'Answer 1'. Goal is for the user to click on one of the multiple choice answers, then hit submit/save to self-check their own knowledge.
I have already learned, through my more complex project code, that a submit/save button that is hard-coded into the html <form> section does not seem to associate with values displayed by the radio buttons, that I managed to add in using javaScript * It seems to me that changing hardcoded information already displayed by the radio buttons might work.
When user clicks on the submit/'save' button, I don't need to refer to the actual answer information that the radio button is displaying. I only need to know whether , in this case, it's the first or second answer chosen.
<html>
<script type="text/javascript">
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" name="operation" value="1" checked>Answer 1
<input type="radio" name="operation" value="2">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
</html>
(I don't know if I should include this following example I tried as well)
BTW Here is another of the example I tried - a posting but I cannot get this idea to work . I was trying to get the first radio button to display 'junk' instead of 'Answer1' as originally hard coded. But I have an error from code borrowed from posting, that I cannot resolve.
It's from
Javascript how to change radio button label text?
<html>
<form name="myform" onsubmit="return OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1" checked <label for="alsoFirst"> Answer 1
<input type="radio" id = 'second' name="operation" value="2"<label for="alsoSecond">Answer 2
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementById('first').getElementsByTagName('alsoFirst') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.myform.operation[1].checked == true)
{
alert ( "You have selected the SECOND answer" );
}
if (document.uniqueName.checked == true){
alert ( "You have selected the THIRD answer" );
}
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
I previously got values from my arrays to display by inserting table rows and concatenating strings. This worked, and went into the table, but did not tie into the submit/save button hardcoded into original <form>. I still plan to have radio answer buttons in a table, but I'm trying to make a more basic example here.
I Have made some modifications for getting label through document.getElementByTagName() and also some changes to OnSubmitForm() function. And just pasted your code with those changes below and demo link at the end.
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//http://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
Demo : https://jsbin.com/sojojiy/27/edit?html,console,output
Hope this helps. Thanks !
I've read variations on this for a few days and can't find a working solution to what I want. And it's probably easier than I'm making out.
I have a set of radio buttons, and want to pass the checked value to part of a URL.
<input type="radio" name="link" value="one" checked="checked">One
<input type="radio" name="link" value="two">Two
<input type="radio" name="link" value="three">Three
And I want the value of whichever one is checked to be passed to a variable such as
dt which then passes to the Submit button which takes you to a url that includes text from the radio buttons.
<input type="button" value="OK" id="ok_button" onclick="parent.location='/testfolder/' + dt;>
But I'm struggling to find out how to get
var dt = document.getElementByName('link').value;
to work for me when I try and apply a for loop to make sure it's checked.
Does my onclick='parent.location.... in the submit button need to be in a function rather than part of the submit button? So the same function can grab the value of the radio button?
So I'm appealing to StackOverflowers for hopefully a bit of guidance... Thanks
First of you want to know which value your combobox has with this easy to use on-liner.
document.querySelector('[name="link"]:checked').value;
I suggest using event handlers to handle the javascript, so don't write it in the onclick attribute.
var btn = document.getElementById('ok_button');
btn.addEventListener('click', function(){ /*handle validations here*/ })
jsfiddle
you can try below code
<input type="button" value="OK" id="ok_button" onclick="functionName();'>
JavaScript Code
<script type="javascript">
function functionName(){
var radios = document.getElementsByName('link'),
value = '';
for (var i = radios.length; i--;) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
window.location.href='/testfolder/'+ value
}
</script>
var dt = document.getElementsByName('link')[0].value works for me
you can use it in either the inline onclick handler or a function you define
<input type="radio" id="1" name="link" onchange="WhatToDo()" value="one">One</input>
<input type="radio" id="2" name="link" onchange="WhatToDo()" value="two">Two</input>
<input type="radio" id="3" name="link" onchange="WhatToDo()" value="three">Three</input>
<script type="text/javascript">
function WhatToDo() {
var rButtons = document.getElementsByName('link');
for (var i = 0; i < rButtons.length; i++) {
if (rButtons[i].checked) {
alert(rButtons[i].value);
}
}
}
</script>
Maybe something like this. Use onchange and then loop through your radio buttons. Whilst looping look to see if the radio button is checked. Its a starting point.
I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;
I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.