I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]
Related
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.
Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.
To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
I need to be able to set the onclick function without onclick being in the input tag. The below code works great, but the input tags are generated and I cannot add the onclick event to them. Jquery solution is fine too.
function setValue(){
var val="";
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
for(var n=0;n<cbs.length;n++){
if(cbs[n].checked){
val+=cbs[n].value+",";
}
}
var temp = val.split(",");
temp.pop();
frm.textname.value=temp
}
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="tea" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="beer" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="soda" onclick="setValue(this.value);">
<input type="checkbox" name="amenities[]" value="orangejuice" onclick="setValue(this.value);">
<input type="text" name="textname">
</form>
Use the .map() function
$(".checkbox").change(function() {
$("#text").val( $('.checkbox:checked').map(function() { return this.value; }).get().join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="checkbox" class="checkbox" name="amenities[]" value="coffee" >
<input type="checkbox" class="checkbox" name="amenities[]" value="tea" >
<input type="checkbox" class="checkbox" name="amenities[]" value="beer" >
<input type="checkbox" class="checkbox" name="amenities[]" value="soda">
<input type="checkbox" class="checkbox" name="amenities[]" value="orangejuice" >
<input type="text" name="textname" id= "text">
</form>
//attach a change handler to the form.
//the change event bubbles up to the parent
var $form = $('#form1').on('change', function(){
//set the value of the textname
$form.find('[name="textname"]').val(
//get all the checked checkbox and map all their values to an array
$form.find(':checkbox:checked').map(function(){
//return the value for each checked element
return this.value;
}).get() //use get() to get a basic array, not a jQuery object
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input type="checkbox" name="amenities[]" value="coffee">
<input type="checkbox" name="amenities[]" value="tea">
<input type="checkbox" name="amenities[]" value="beer">
<input type="checkbox" name="amenities[]" value="soda">
<input type="checkbox" name="amenities[]" value="orangejuice">
<input type="text" name="textname">
</form>
you can try this:
$('input[type=checkbox]').change(function() {
//logic goes here
});
Plain JS:
var mForm = document.getElementById("form1");
mForm.addEventListener("click", function(event){
console.log("clicked", event.toElement); // do whatever you want with this element, add condition to sort checkboxes only
});
UPDATED:
var frm = document.getElementById("form1");
var cbs = document.getElementById("form1")['amenities[]'];
function setValue(frm, cbs){
var output = [];
for( var n in cbs){
if(cbs[n].checked){
output.push(cbs[n].value);
}
}
frm.textname.value=output.join();
}
frm.addEventListener("click", function(event){
if (event.toElement.type == "checkbox") {
setValue(frm, cbs);
}
});
i am doing a mobile application survey form using phonegap and firebase.
My data from the form is inserted to firebase however it only work for textbox and not radio button. is there something wrong with my codes? This is what shown in firebase.
The following is my code
<form id="testForm">
<b style="font-size: 27px;">Survey Form<p></p></b>
<b class=fs>Name of client:</b> <br><input type="text" name="name" id="name"><br>
<b class=fs>Date: </b><br><input type="date" name="date" id="date"><p></p>
<b class=fs>1)Do you worry? In the past month?</b> <p>
<input type="radio" name="q1" value="0" id="q1"> 0
<input type="radio" name="q1" value="1" id="q1"> 1 <p>
<b class=fs>2) Have you been sad or depressed in the past month?</b> <p>
<input type="radio" name="q2" value="0" id="q2"> 0
<input type="radio" name="q2" value="1" id="q2"> 1 <p>
<input type="submit" class="button" value="Submit">
</form>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
//reference messages collection
var testRef = firebase.database().ref('test');
// listen for form submit
document.getElementById('testForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
var name = getInputVal('name');
var date = getInputVal('date');
var q1 = getInputVal('q1');
var q2 = getInputVal('q2');
saveMessage(name,date,q1,q2);
}
function getInputVal(id){
return document.getElementById(id).value;
}
function saveMessage(name,date,q1,q2){
var newMessageRef = testRef.push();
newMessageRef.set({
screenby:name,
date:date,
q1:q1,
q2:q2,
});
}
</script>
</body>
</html>
I'm trying to get a function working that hides a label in the form depending on the radio button option selected. Here's my code so far.
HTML
<form action="">
<input type="radio" id="test" value="first"> first<br>
<input type="radio" id="test" value="second"> second<br>
<input type="radio" id="test" value="third"> third
</form>
<label class="hidden">Hide this</label>
Javascript
var rbtn = document.getElementById("test");
var x = document.getElementsByClassName("hidden");
function hidelabel() {
if (rbtn == 'third') {
x.style.display='none';
}
}
You must fire your hide function after radio button clicked like this:
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
if (radVal == 'third') {
document.getElementsByClassName("hidden")[0].style.display = 'none';
}
}
ps: document.getElementsByClassName returns an array. So you cannot use x.style.display='none';.
Working example: https://jsfiddle.net/5ts0dak4/
First name the radio button ID's with something decent:
<form action="">
<input type="radio" id="first" value="first"> first<br>
<input type="radio" id="second" value="second"> second<br>
<input type="radio" id="third" onclick="hide();" value="third"> third
</form>
<label class="hidden" id="hidden">Hide this</label>
Then try this:
function hide(){
var x = document.getElementById('hidden');
if(document.getElementById('third').checked) {
x.style.display='none';
}
}
You can test it here https://jsfiddle.net/o54mzrk5/
Try this one.
CSS:
<style type="text/css">
.hidden{ display:none; }
</style>
HTML:
<form action="">
<input type="radio" name="test" value="first" onclick="func(this, true);"> first<br>
<input type="radio" name="test" value="second" onclick="func(this, true);"> second<br>
<input type="radio" name="test" value="third" onclick="func(this, false);"> third
</form>
<label class="hidden">Hide this</label>
Script:
<script type="text/javascript">
func = function(ctrl, visible) {
if(visible)
document.getElementsByClassName("hidden")[0].style.display='block';
else
document.getElementsByClassName("hidden")[0].style.display='none';
};
</script>
How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO