I have a radio button that will show a div with an input text when it is checked 'NO'. But it is not showing the div, however when I play around the radio button then the div will show. Where am I missing?
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
if (firstCheckbox.checked == true) {
rmk.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmk.style.display = "block";
document.getElementById("rmk").required = true;
}
}
<div>
<label>Have you registered the course?</label>
<table border=0>
<tr>
<td>YES </td>
<td><input type="radio" name="register" value="Y" id="check1" onclick="CheckboxCheck('first')"> </td>
<td>NO </td>
<td><input type="radio" name="register" value="N" checked id="check2" onclick="CheckboxCheck('second')"></td>
</table>
</div>
<div id="rmk" style="display:none">
<label>Reasons</label>
<input type="text" name="remarks" class="form-control">
</div>
There are a few structure and accessibility proposals going on in this suggestion but I think strictly speaking, the easiest solve for you is to invoke the function on page load. Give this example a look:
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
var rmkdiv = document.getElementById("rmk-div");
if (firstCheckbox.checked == true) {
rmkdiv.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmkdiv.style.display = "block";
rmk.required = true;
}
}
CheckboxCheck()
<div>
<p>Have you registered the course?</p>
<label>
YES<input
type="radio"
name="register"
value="Y"
id="check1"
onclick="CheckboxCheck()"
/></label>
<label>NO
<input
type="radio"
name="register"
value="N"
checked
id="check2"
onclick="CheckboxCheck()"
/>
</label>
<div id="rmk-div" style="display: none">
<label>Reasons</label>
<input id="rmk" type="text" name="remarks" class="form-control" />
</div>
</div>
Your input field will only be visible when the function CheckboxCheck is executed. Since "NO" is checked from the beginning, the function will not be executed because it is only called when a change takes place.
Related
I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)
I want to save the checked values of the radio boxes but when I try to submit the button and redirect to a url based on the 3 choices it doesnt work. I debugged it, and apparently the problem is that my program is only saving the last value in the variable but not the values before. What can I do to save all the choices in 3 different variables?
HTML:
<div id="schritt1">
<p stlye="text-align:center;">frage 1</p>
<input id="1a" type="radio" name="a" value="eins" onclick="checkedvalue('a')"/>
<label for="1a">1</label><br/>
<input id="1b" type="radio" name="a" value="zwei" onclick="checkedvalue('a')"/>
<label for="1b">2</label></br>
<input id="1c" type="radio" name="a" value="drei" onclick="checkedvalue('a')"/>
<label for="1c">3</label>
</div>
<div id="schritt2" style="display:none;">
<p stlye="text-align:center;">Frage 2</p>
<input id="2a" type="radio" name="b" value="zweieins" onclick="checkedvalue('b')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="b" value="zweizwei" onclick="checkedvalue('b')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="b" value="zweidrei" onclick="checkedvalue('b')"/>
<label for="2c">3</label>
</div>
<div id="schritt3" style="display:none;">
<p stlye="text-align:center;">Frage 3</p>
<input id="2a" type="radio" name="c" value="dreieins" onclick="checkedvalue('c')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="c" value="dreizwei" onclick="checkedvalue('c')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="c" value="dreidrei" onclick="checkedvalue('c')"/>
<label for="2c">3</label>
</div>
<div id="finish-button" style="display:none;">
<a class="btn btn-buy" onclick="checkedvalue('finish')">Ergebnis</a>
</div>
JS:
<script>
function checkedvalue(choice){
var eins;
var zwei;
var drei;
if(choice == "a") {
eins = (jQuery('input[name=a]:checked').val());
window.alert(eins);
document.getElementById('schritt1').style.display = 'none';
document.getElementById('schritt2').style.display = 'block';
}
else if(choice == "b") {
zwei = (jQuery('input[name=b]:checked').val());
window.alert(zwei);
window.alert(eins + zwei);
document.getElementById('schritt2').style.display = 'none';
document.getElementById('schritt3').style.display = 'block';
document.getElementById('finish-button').style.display = 'block';
}
else if(choice == "c") {
drei = (jQuery('input[name=c]:checked').val());
}
else if(choice == "finish") {
window.alert(eins + zwei + drei);
if(eins == "eins" && zwei == "zweieins" && drei == "dreieins" )
{
console.log("If 2 works");
window.location.href = "//";
}
}
}
The issue is every time this onclick() method is calling and refreshing the Javascript method.So it will be loose the previously saved values.
You can Collect all the radio Button group values At the time of form submitting using
var eins;
var zwei;
var drei;
declare these variable globally(Outside of all functions) and add below code inside form submit method (write a OnSubmit method in your submit button and write the code inside )
$('input:radio').each(function() {
if($(this).is(':checked')) {
// You have a checked radio button here...
var val = $(this).val();
var name = $(this).attr('name');
if(name=="a")
{
eins=val;
}
else if(name=="b")
{
zwei=val;
}
else
{
drei=val;
}
}
else {
// Or an unchecked one here...
}
});
I didn't test the code,So modify as per your requirements.
I have nine checkboxes linked to nine images and three of them use the name 'correct' using the code shown below.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"/>
</div>
The remaining six are unnamed using the code shown below.
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4"/>
</div>
I currently have the following code to produce an alert if the three checkboxes with the name "correct" are checked but it isn't working.
<script>
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
</script>
Can anyone help me with this?
Loop over all of the checkboxes, checking their state. Once this is done, create a variable "correct" and initialize it to true. Then go to each state in the variable and, if you find that its name isn't "correct" and it is checked or its name is "correct" and it isn't correct, set the variable to false. Then check if the variable is true and, if it is, display the alert.
View an example here: https://repl.it/GxsE/9
Using ES6:
const correctInputs = [...document.querySelectorAll('input[name="correct"]')];
const alertIfThree = () => {
const checkedCorrectInputs = correctInputs.filter(input => input.checked);
if (checkedCorrectInputs.length > 2) {
alert('Alert');
}
};
correctInputs.forEach(input => input.addEventListener('click', alertIfThree));
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
document.querySelectorAll('input[name="correct"]') gets all inputs with name "correct".
[...CODE] is spread operator, it converts code from previous point to array.
correctInputs.forEach(input => input.addEventListener('click', alertIfThree)) adds click event listener to each of them. That event listener is function alertIfThree().
alertIfThree() filters out those input elements that are not checked and produces alert if there are more than 2 of them.
EDIT
In response to your comment:
// jshint esnext: true
const inputs = [...document.querySelectorAll('input[name="correct"], input[name="incorrect"]')];
const alertIfCorrect = () => {
const checkedInputs = inputs.filter(input => input.checked),
noIncorrectCheckedInputs = checkedInputs.find(input => input.name === 'incorrect') === undefined;
if (checkedInputs.length > 2 && noIncorrectCheckedInputs) {
alert('Alert');
}
};
inputs.forEach(input => input.addEventListener('click', alertIfCorrect));
<p>Correct:
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
</p>
<p>Incorrect:
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
</p>
const is ES6 constant. "The value of a constant cannot change through re-assignment, and it can't be redeclared".
[...CODE_HERE] is so called spread syntax. Here, it turns what it contains after ellipsis into an array. Other way to do it would be to use Array.from().
() => { and input => CODE_HERE are arrow functions. They are ES6's syntactic sugar for function declaration.
What stands before => are parameters. () stands for 0 parameters. If you wanted function that takes few parameters, those braces would need to have those few parameters inside them. For one parameter, parameter's name can replace braces altogether (like in second code in this bullet point).
What stands after => is either expression or group of statements. Statements are surrounded by curly brackets ({}). If you omit them, you are writing an expression that your function will return. For example input => input.checked is equivalent to function(input) { return input.checked; }.
filter() and find() are methods of array prototype. They respectively filter and search an array using condition defined in a function that is passed to them as a parameter. Read more by following those two links.
If you need something else explained, let me know. Those functions and structures here are pretty... fresh, so you can just not know them yet.
I put this in a JSfiddle and it works for me. I just wrapped your JS in a function and added an onclick event.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"onclick="validate()"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4" onclick="validate()"/>
</div>
<script type=text/javascript">
function validate()
{
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
}
</script>
It will require some javascript. You will need o check the checkboxes each time one changes. So to start with you will need to check your checkboxes, assuming they have an assigned class of 'chk'. This can be done with a querySelector.
Each time a checkbox changes, the function 'check_checkboxes()' is called. This function will see for each checkbox with name='correct' if it is checked and then increment 'count'
var checkboxes = document.querySelectorAll(".chk");
var correct = document.querySelectorAll("[name=correct]");
function check_checkbox() {
var count = 0;
[].forEach.call(correct, function(item) {
if (item.checked) {
count++;
}
});
if (count >= 3) {
alert("count of 3 or more");
}
}
[].forEach.call(checkboxes, function(item) {
item.addEventListener("change", function() {
check_checkbox();
}, false);
});
<div class="nine">
<label for="correct1"><img class="picture1" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
Check the loop. Use for (i = 0; i < correct.length; i++) { instead for (i = 0; i <= correct.length; i++) {
var i, correct = document.getElementsByName('correct');
var correct_answers = [];
function validate(){
correct_answers = [];
for (i = 0; i < correct.length; i++) {
var element = correct[i].getAttribute("id");
var checked = correct[i].checked;
correct_answers.push({element,checked});
}
}
function show(){
document.getElementById('results').innerHTML ="";
for(var e=0;e<correct_answers.length;e++){
var box = document.createElement('div');
box.innerHTML = correct_answers[e].element+ " " + correct_answers[e].checked+ "<br>";
document.getElementById('results').appendChild(box);
}
}
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct1" name="correct"/>
</div>
<div class="nine">
<label for="correct2"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct2" name="correct"/>
</div>
<div class="nine">
<label for="correct3"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct3" name="correct"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect4"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect5"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect6"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect7"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect8"/>
</div>
<button onclick="show();">show results</button>
<div id="results"></div>
Use document.querySelectorAll('input[name]=correct') in your code.
I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>
I have a form with multiple yes/no radio buttons and text area I would like to disable ("grey out") when yes is selected and enable when no is selected.
What I have currently only works for the first text area, all other radio buttons only effect the first text area because they have matching ids.
This is my view I am using.
#for (int i = 0; i < Model.Questions.Count; i++)
{
<tr>
<td>
<div>
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, true, new { id = "radio" + i, #class = "class" + i, value = "yes", }) Yes
#Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id = "radio" + i, #class = "class" + i, value = "no" }) No
</div>
</td>
<td>
#Html.TextAreaFor(p => Model.Questions[i].ActionToTake, new { id = "text" + i })
</td>
</tr>
}
I know I will need to generate unique ids somehow for each pair of radio buttons and bind them to the text area somehow. This is the script I'm currently using.
$(document).ready(function() {
$(".class1").change(function (e) {
if ($(this).val() === 'True') {
$("#text1").prop('readonly', true);
$("#text1").css('background-color', '#EBEBE4');
} else if ($(this).val() === 'False') {
$("#text1").prop('readonly', false);
$("#text1").css('background-color', '#FFFFFF');
}
});
})
Whats a good way to approach this? I'm still new to javascript so any additional explanation for what you're doing would be helpful.
As I said in my comments, you do not need to have IDs unless you use them elsewhere. You can simply have a group, may be a DIV with a class and radio buttons and text area as the group children. Did you want something like this?
$(function() {
var $choices = $(".group").find(":radio");
$choices.on("change", function() {
var $this = $(this);
var choice = $.trim( $this.val() );
var tarea = $this.closest(".group").find("textarea");
tarea.prop("readOnly", choice === "yes");
if ( choice === "yes" ) {
//do your stuff when val = yes
} else {
//do your stuff when val = no
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group">
<input type="radio" name="choice1" value="yes" />Yes
<input type="radio" name="choice1" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice3" value="yes" />Yes
<input type="radio" name="choice3" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>
<div class="group">
<input type="radio" name="choice4" value="yes" />Yes
<input type="radio" name="choice4" value="no" />No
<textarea rows="4" cols="20"></textarea>
</div>