Validate input based on radio input - javascript

Is there a way to validate a field text input based on radio button selection? I'm trying to validate a user's input into a Title field, based on the radio selection of whether the identity is male or female.

Create two radio button with same name attribute. and read value of selected radio button
var radio= document.getElementsByName('radioname');
var val;
for(var k =0; k< radio.length; k++){
if(radio[k].checked){
val = radio[k].val;
break;
}
}
var text = document.getElementById('textfield');
if(val == 'male'){
validateMale(text);
}
else{
validateFemale(text);
}
function validateMale(text){
// validation code
}
function validateFemale(text){
// validation code
}

You can use <input type="radio" onchange="myFunction()"> and set the function in JS to submit your form like that :
var myFunction = function(){
document.forms["myform"].submit();
}
There the onchange function in JQuery : http://api.jquery.com/change/

Related

Validation on RadioButton of same group in .net using javascript

I want to give validation on two radiobuttons of same group using javascript in .net. There will be a button clicking on which the text of selected radiobutton will store on database. But if none of the radio button is selected then a alert will be shown and nothing will be stored in database. Please give me a solution
Assuming its a radio button list, on client click of button,
<asp:Button ID="btnSubmit" runat="server" Text="Validate" OnClientClick="return Validate()" />
embed the below function.
function Validate() {
var rb = document.getElementById("<%=RadioButtonList1.ClientID%>");
var radio = rb.getElementsByTagName("input");
var isChecked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select an option!");
}
return isChecked;
}

tetxtbox enable/disable on checkbox select/unselect using Javascript

I have a table with three columns and multiple rows. 2nd and third column consist of a textbox(first child of a container) and a checkbox respectively.
Textbox
<td class="SBS1 c4">
<input class="Medium InputText" type="text" name="QR~QID33#1~1~1~TEXT" id="QR~QID33#1~1~1~TEXT" value="" disabled="">
<label class="offScreen" for="QR~QID33#1~1~1~TEXT">&nbsp; - &nbsp; - hh</label>
</td>
Checkbox
<td class="SBS2 c7">
<input type="checkbox" id="QR~QID33#2~1~1" name="QR~QID33#2~1~1" value="Selected">
<label class="q-checkbox q-checked" for="QR~QID33#2~1~1"></label>
<label class="offScreen" for="QR~QID33#2~1~1">&nbsp; - 󠆺random text</label>
</td>
I have to disable and enable the textboxes in each row on checkbox check and uncheck respectively using javascript. but there seem to be some pagelifecycle issues with the script I am using. Here is the Javascript that I am using in my Qualtrics survey JS interface,
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your JavaScript Here*/
var count=document.getElementsByClassName("q-checkbox").length;
for(var i=0;i<count;i++)
{
document.getElementsByClassName("q-checkbox")[i].parentNode.addEventListener("click",hideFunc);
}
function hideFunc()
{
console.log(this.className);
if(this.classList.contains("checkers"))
{
//this.classList.toggle("checkers");
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="false";
this.classList.add("checkers");
return;
}
else
if(!(this.classList.contains("checkers")))
{
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="true";
this.classList.remove("checkers");
return;
}
}
});
I am just trying to toggle or add/remove the class "checkers"and setting "disabled" property of the texboxes accordingly. The code above in HideFunc is one of the work-around I have tried but it is not working.
Is there another way to check for checkbox change?
As the first comment hinted, a better approach is to check the status of the checkbox rather than add/remove a class. Also, making use of prototypejs makes it easier. Try this:
Qualtrics.SurveyEngine.addOnload(function() {
var qid = this.questionId;
$(qid).select('tr.Choice').each(function(choice,idx) { //loop through each row
var cbox = choice.select('td.SBS2').first().down(); //cbox enables 1st question in row
var txtEl = choice.select('td.SBS1').first().down(); //text input to be enabled/disabled
if(cbox.checked == false) { //initialize text input disabled status
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
cbox.on('click', function(event, element) { //enable/disable text input on cbox click
if(cbox.checked == false) { //unchecked
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
else { //checked
txtEl.disabled = false; //enable text input
}
}); //end on function
}); //end row loop
});
This is another solution I could come up with ,apart from the correct solution by T. Gibbons
var $j= jQuery.noConflict();
$j("td.SBS2 ").click(function(){
$j(this).closest("tr").find(".InputText").prop("disabled",$j(this).children("input")[0].checked);
$j(this).closest("tr").find(".InputText").prop("value","");
var len=document.getElementsByClassName("InputText").length;
for(var i=0;i<=len;i++)
{
document.getElementsByClassName("InputText")[i].style.width="300px";
}
});

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Getting the ID of a radio button using JavaScript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

Could someone please explain a piece of Javascript code?

I am doing a project in school, and as part of that I had to include radio buttons in my html form. Below is the Javascript code which some parts I don't quite understand. The code works fine. Could someone plz give me an explanation of how the code works.
var check = false;
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
if (document.ExamEntry.Level[i].checked)
{
var radiovalue = document.ExamEntry.Level[i].value;
check =true;
var usermessage=confirm("You have chosen: ".concat(radiovalue));
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
<!--I understand the code below, its just some parts of the above code.
if (check ==false)
{
msg+="ERROR:You must select an entry level \n";
document.getElementById ('Levelcell'). style.color = "red";
result = false;
}
I added comments to help explain this:
var check = false;
// set a variable 'i' from 0 up to the ExamEntry level length (so for each radio)
// if there are 10 items, this code will run 10 times, each time with 'i' a different value from 0 to 9
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
// is the radio button checked? If so, do the stuff inside. If not, skip this part
if (document.ExamEntry.Level[i].checked)
{
// set variable radiovalue to the value of the particular radio button
var radiovalue = document.ExamEntry.Level[i].value;
// set the check variable to true
check =true;
// ask the user to confirm the value and set usermessage based on confirmation
var usermessage=confirm("You have chosen: ".concat(radiovalue));
// if the user hits no on confirm, it will reset the radiomessage to blank and check to false
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
All form elements are bound to the global HTML document variable. So somewhere on the page there must be a form with the name of ExamEntry:
<form name='ExamEntry' id='ExamEntry` ...
The next part refers to an element in the form. Since they are expecting a radio button, Level must be an input of type radio:
<label name="Level" id="1" type="radio" ....
<label name="Level" id="2" type="radio" ....
The loop iterates through all radio buttons. If the the button is checked, it grabs the checked value, and shows that message. If it does not find a checked button, then it displays an error message.

Categories

Resources