Link Radiobox button to Input - javascript

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)

Related

How capture the input radio value in javascript?

For example I have the next options in html, define the global name and different id to each input radio:
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>
To read the value I read the selector, the global name and the checked attribute and then read the id property, you can use the value property as well.
const chooseMokepon = (e) => {
e.preventDefault();
const $selectedMokepon = document.querySelector('input[name=mokepon]:checked');
const { id: mokeponValue } = $selectedMokepon;
if (!mokeponValue) return;
console.log(mokeponValue);
}
$mokeponForm.addEventListener('submit', e => chooseMokepon(e));
You might use this snippet:
let submitBtn = document.querySelector('button[type="submit"]');
submitBtn.addEventListener('click', function(event){
event.preventDefault();
let selectedOption = document.querySelector('input[type="radio"][name="mokepon"]:checked');
if(selectedOption && selectedOption.value){
console.log('Selected: ' + selectedOption.value);
}
});
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge" value="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego" value="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya" value="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>

How to get fields via children or childnodes

I need to get the children of the Section block. Namely fields and rabiobuttons. Next, check them for fullness. How to do it. I tried to get through childNodes, children but nothing worked.
In this case, I want to get the context of the section block and check the fields
Such sections, I need to validate section by section and until the previous one is filled, I do not validate the next one.
const formStepTwo = document.getElementById("formStepTwo");
const Section = document.querySelectorAll(".Section");
formStepTwo.addEventListener("change", () => {
//console.log( Section.item(0))
let count = Array.from(Section).forEach((i) => {
let context = i.children;
context.item()
console.log( this.querySelectorAll(".input[type=radio]"))
//console.log(context.forEach());
});
});
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</div>
</form>
You can actually check for input fields by targeting 'label' since they directly wrap over the input tag. Targeting through .Section can get a bit tricky, but is doable.
Another alternative is to directly target input fields using querySelectorAll('input') and then check for their type.
I've added example of both in the code snippet :
const formStepTwo = document.getElementById("formStepTwo");
const labels = document.querySelectorAll("label");
formStepTwo.addEventListener("change", () => {
let count = Array.from(labels).forEach((i) => {
let children = i.children;
Array.from(children).forEach((node) => {
if(node.nodeName.toLowerCase() === 'input') {
switch(node.type) {
case 'number' : validateNumberField(node);
break;
case 'radio' : validateRadio(node);
break;
// add more cases as required
default:
console.log('add default');
}
}
});
});
});
// Can also be done by targeting input directly
const input = document.querySelectorAll('input');
formStepTwo.addEventListener("change", () => {
Array.from(input).forEach((node) => {
if(node.nodeName.toLowerCase() === 'input') {
switch(node.type) {
case 'number' : validateNumberField(node);
break;
case 'radio' : validateRadio(node);
break;
// add more cases as required
default:
console.log('add default');
}
}
});
});
function validateNumberField(node) {
console.log('validating number field');
// add your validation
}
function validateRadio(node) {
console.log('validation radio button');
// add your validation for radio
}
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</div>
</form>
Maybe this helps you:
const formStepTwo = document.getElementById("formStepTwo");
const sections = [...document.querySelectorAll(".Section")];
formStepTwo.addEventListener("input", () => {
sections.forEach(s=>{
const inps=[...s.querySelectorAll("input,select")].filter(el=>el.type!=="radio"||el.checked);
console.log(inps.map(el=>el.name+":"+el.value))
});
});
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</form>
The script goes through all sections (currently there is only one ;-)) and collects all input values. (Radio buttons are only picked up if they are "checked".)

Div not showing when radio button checked

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.

Save Radio Box Value in Variables

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.

Javascript help. Adding/removing form element to DOM

if radio button 2 is checked add input box into datesettings. How do i add an input box? If radio button 1 is checked do nothing but if button 2 was checked previously remove children. Can you help me
Thanks
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
//Remove o2 children
}
else if(o2.checked) {
//How do I add an input box?
}
}
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions();">
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions();">
<span id="datesettings">//Add input box here if dateoption2 is checked</span>
The simplest route would be:
<input type="radio" id="dateoption1" name="dateoption" value="1" ="ToggleDateOptions(true);" />
<input type="radio" id="dateoption2" name="dateoption" value="2" ="ToggleDateOptions(false);" />
<span id="datesettings">
<input type="text" id="dateSetting" />
</span>
<script>
function ToggleDateOptions(oneChecked) {
if(oneChecked)
{
$("#dateSetting").hide();
}
else
{
$("#dateSetting").show();
}
}
</script>
Or if you didn't want to use JQuery (Which is used above) you could do:
if(oneChecked)
{
document.getElementById("dateSetting").style.display = 'none';
}
else
{
document.getElementById("dateSetting").style.display = 'inline';
}
You can just use innerHTML to add the input field.
Something like this should work for you
<script type="text/javascript">
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.innerHTML = "";
} else if(o2.checked) {
eSettings.innerHTML = '<input type="text" name="field" />';
}
}
</script>
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions()"/>
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions()"/>
<span id="datesettings"></span>
Demo

Categories

Resources