i am trying to output value of radio with innerHTML
But i do not succeed in this. What is going wrong?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
It's getElementsByName (plural).
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
jsFiddle example
And you probably want the value (userInputgender[i].value;) returned to your div.
You could use jquery, it's much better. Look at this example:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
http://jsfiddle.net/LZWau/1/
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
http://jsfiddle.net/ayy28/4/
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});
Related
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concate(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" name="gender" checked>Male
<input type="radio" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
I tried but i think there is a bug. I want to display whole line that the user enter but clicking it is not working. At mid, it was working but after not working. I want output as jaykumar jay#123 111111 Male . And also how to get Gender Male/Female in demo. Instead it is giving me only "on" .How to get value Male or Female in demo.
Because you didn't add value to radio input. According to Mozilla doc:
If you omit the value attribute in the HTML, the submitted form data assigns the value on to the group.
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concat(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" checked id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
you need to have a different treatment when it's a radio, in addition of adding the value for each radio
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
if ((x[i].type === 'radio' && x[i].checked) || x[i].type === 'text') {
para = para.concate(x[i].value);
}
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="text" name="fname"> email
<input type="text" name="email"> number
<input type="text" name="number"> Gender
<input type="radio" value="Male" name="gender" checked>Male
<input type="radio" value="Female" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
I am using the multistep form and I want to prevent input radio in step form if the radio is not selected then not forward another step. My input type of text is validated.
allNextBtn.click(function(e) {
e.preventDefault();
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]')
.parent()
.next()
.children("a"),
**curInputs = curStep.find(
"input[type='text'],input[type='url'],input[type='email'],input[type='phone'],input[type='date']"
),**
isValid = true;
$(".form-group").removeClass("alert alert-danger");
$(".msg_error").html("");
for (var i = 0; i < curInputs.length; i++) {
if (!curInputs[i].validity.valid) {
isValid = false;
$(curInputs[i])
.closest(".form-group")
.addClass(" alert alert-danger");
$(".msg_error").html("All fields are mandatory.");
}
//console.log(!curInputs[i].validity.valid);
}
<input type="radio" name="customer_budget" value="$0 - $15,000">
<input type="radio" name="customer_budget" value="$15,001 - $30,000">
<input type="radio" name="customer_budget" value="$30,001 - $50000">
<input type="radio" name="customer_budget" value="$50,001 - Above">
function getSelectedRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
}
function result() {
var score = 0;
score += parseInt(getSelectedRadioValue("q1")) || 0;
score += parseInt(getSelectedRadioValue("q2")) || 0;
score += parseInt(getSelectedRadioValue("q3")) || 0;
score += parseInt(getSelectedRadioValue("q4")) || 0;
document.getElementById('result').innerHTML = ("You selected " + score);
document.getElementById("questions").style.display = 'none';
document.getElementById('result').style.display = 'block';
}
window.onload = function() {
check.onclick = result;
}
<body>
<div class="topnav">
</div><br><br>
<div class="center123">
<br>
<div id="questions" class="divhide">
<div class="divh2">
<b>1) What is the square root of 64?</b>
<div class="answers"><br>
<label class="radiobox">
<input class="radio" type="radio" value="9000" name="q1">9000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="60000" name="q2">60000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="8000" name="q3">8000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="12000" name="q4">12000
</label>
<br><br><br>
</div>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />
<input class="button" type="button" id="check" value="SUBMITT">
<font align="center" size="10" color="black">
</div>
<p id="result" style="display:none;">Result</p>
</font><br>
Next Step
</body>
Try this
On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.
Firstly I apologies, I've just starting out with JavaScript
I have a problem with a form. I have two groups of Radio buttons on the form (age and bmi)
Everytime the 'Calculate' button is clicked, I want add the values of each checked Radio button and alert this to the screen.
It works in Chrome, but ALL other browsers give an NAN error.
Can anyone help?
<br>
<input type="radio" name="age" class="myradioButton" value = "1"/>
<input type="radio" name="bmi" class="myradioButton" value = "3"/>
<input type="button" name="Calculate" id="calculate"onclick="calculatehealth()" value="Calculate"/>
<br>
<script>
function calculatehealth() {
var valueAge = document.forms['myForm'].elements["age"].value;
var valueint = parseInt(valueAge);
var valueBmi = document.forms['myForm'].elements["bmi"].value;
var Bmiint = parseInt(valueBmi);
var total = Bmiint + valueint;
alert(total);
}
Demo: http://jsfiddle.net/z4RKx/
HTML
<form id="myForm">
<input type="radio" name="age" class="myradioButton" value="1" />
<input type="radio" name="bmi" class="myradioButton" value="3" />
<input type="button" name="Calculate" value="Calculate" onclick='calculatehealth()' />
</form>
JS
function calculatehealth() {
var valueint = 0;
if (document.forms['myForm'].elements["age"].checked) {
valueint += parseInt(document.forms['myForm'].elements["age"].value);
}
if (document.forms['myForm'].elements["bmi"].checked) {
valueint += parseInt(document.forms['myForm'].elements["bmi"].value);
}
alert(valueint);
}
And if you have many elements this might be a good alternative:
function calculatehealth() {
var valueint = 0;
for(i = 0; i < document.forms['myForm'].elements.length; i++) {
if (document.forms['myForm'].elements[i].checked) {
valueint += parseInt(document.forms['myForm'].elements[i].value);
}
}
alert(valueint);
}
I have the following code. I need to see how many checkboxes have been checked in my form and if there are 4 or less submit the form and if there are more display an error and don't submit.
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
any help would be appreciated.
Your javascript looks correct. I think the only you should need to do is return false; on your if (totalChecked > 4) statement.
Edit: Here's the section of your javascript function to modify:
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
Your function needs to return false to cancel the submission or true to proceed. That's why your onsubmit form attribute is set to "return XXX()" rather than just "XXX()"
As mentioned, you should return false from your check function to cancel the submit, and true if the check is okay.
How about something like this?
<html>
<head>
<title>Pizza Order Form</title>
</head>
<body>
<script>
function SetHiddenFieldValue() {
var totalChecked = 0;
var itemPrice = 5.99;
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var checks = document.getElementsByName('topping');
for (i = 0; i < checks.length; i++) {
if (checks[i].checked) {
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
}
else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
}
</script>
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<div id="toppings">
<input type="checkbox" name="topping" id="pepperoni" />Pepperoni
<input type="checkbox" name="topping" id="tomato" />Tomato
<input type="checkbox" name="topping" id="mushrooms" />Mushrooms
<input type="checkbox" name="topping" id="peppers" />Peppers
<input type="checkbox" name="topping" id="olives" />Olives
</div>
<input type="submit" name="my-add-button" value=" Add " />
</form>
</body>
</html>