form action to toggle a function? - javascript

<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>

Related

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

how to get checked radio button value in javascript

I have some set of radio button. I am trying to get checked radio button value using java script. But I got the error of uncaught id. I do the following code in html 5. I am not getting the value.
function timeout()
{
if (document.getElementById["RadioButton1"].checked)
{
choice = document.getElementById["RadioButton1"].value;
alert('choice');
}
if (document.getElementById["RadioButton2"].checked)
{
choice = document.getElementById["RadioButton2"].value;
alert('choice');
}
if (document.getElementById["RadioButton3"].checked)
{
choice = document.getElementById["RadioButton3"].value;
alert('choice');
}
if (document.getElementById["RadioButton4"].checked)
{
choice = document.getElementById["RadioButton4"].value;
alert('choice');
}
var c = document.getElementById("label1").value;
}
If you use the same name(in same radio button group) for all radio buttons like this
<input type="radio" id="RadioButton1" name="radio_group" value="1"/>
<input type="radio" id="RadioButton2" name="radio_group" value="2"/>
<input type="radio" id="RadioButton3" name="radio_group" value="3"/>
you can get the selected(checked radio button value ) using jQuery,in one line.
var Val = $("input[name=radio_group]:checked").val();
A set of radio buttons should all have the same name. So get the set, find the checked one and read its value:
function getValue(name) {
var rbs = document.getElementsByName(name);
for (var i=0, iLen=rbs.length, i<iLen; i++) {
if (rbs[i].checked) {
return rbs[i].value;
}
}
}
If the controls are in a form (which the usually are) and you have a reference to the form, you can get the set using:
var rbs = formRef[name];
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#result').html(result.val()+" is Checked");
}else{
$('#result').html(" No radio button is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>
The major problem visible from your code is a syntax error.
document.getElementById is a method and not an object, so you should call it with parens:
// --------------------v--------------v
document.getElementById("RadioButton1").value
This is ans for #yogi comment(
how we can implement same for checkboxes?)
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#result').html(resultstring);
}else{
$('#result').html(" No checkbox is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>

Javascript onsubmit with cgi action?

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.

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>

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources