If radio button checked add new form element using dom? - javascript

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.

Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3

You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>

Related

How to check if radiobutton is selected (javascript, html)

I am trying to check if a radio button is selected or not. If the "morn_before" radiobutton is selected, the data will be stored as "2", but if the "morn_after" radiobutton is selected instead, the data will be stored as "1".
Currently my code show below is not working. For example when i select the "morn_before" radiobutton, it doesnt print "morn_before checked true" in the console, despite me putting console.log("morn_before checked true") in that if statement.
HTML:
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="morn_before">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="morn_after">
<label for="morn_after">After Food</label><br><br>
</div>
Javascript:
function check() {
let user=firebase.
auth().currentUser;
let uid;
if(user!=null){
uid=user.uid;
}
var firebaseRef = firebase.database().ref();
if(document.getElementById("morn_before").checked){
console.log("morn_before checked true");
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("2");
}
else if(document.getElementById("morn_after").checked){
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("1");
}
}
check();
You don't need any JavaScript for this. You can have a completely different display than the stored value.
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="2">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="1">
<label for="morn_after">After Food</label><br><br>
</div>
Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you.
ADDITIONAL INFO: You are not supposed to read a radio button group that way.
You should go over some basics of HTML INPUT tag such as
https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/

Multi step form - how to show data from steps before?

Is this a good solution to check multiple radio buttons with 1 label? I have a form with multiple steps. The last step shows a summary about the previous steps and I need to get all data from there. Is there a better option? How can I get the text from the input fields and insert it to the summary? JavaScript?
$('label').click(function() {
id = this.id.split('-');
if (id[0] === '1') {
id[0] = '2';
} else {
id[0] = '1';
}
$('#' + id[0] + '-' + id[1]).prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<input type="radio" id="1-1" name="1-level">
<label for="1-1" id="1-1">1</label>
<input type="radio" id="1-2" name="1-level">
<label for="1-2" id="1-2">2</label>
</div>
<div class="two">
<input type="radio" id="2-1" name="2-level">
<label for="2-1" id="2-1">1</label>
<input type="radio" id="2-2" name="2-level">
<label for="2-2" id="2-2">2</label>
</div>
Add a form element to wrap your input elements in. Forms can access all the inputs that are inside of it and see their names and their values. So in this case it is important that you use the value attribute on your input elements. Start by doing the above and make your code look like the example below.
Also, be careful with id's. They need to be unique, so they can only appear once in every document. Right now the label and their input elements have the same id.
<form id="step-form">
<div class="one">
...
</div>
</form>
Like #Shilly suggested, use the FormData API. This API is designed to get all the values from a form, think input, textarea and select elements and puts all of that data into a single object. This way you can create as many form-elements as you want, add them to the form and store their values in a single object.
The data in that object will be read as key-value pairs, which in this case are the name and value attribute values. For example: ['1-level', '2'], here we see the input with the name '1-level' and the value '2'.
I would not recommend using other input elements to show your results or summary. This could be confusing for the user as it suggests input. Instead print your results in plain text or create a list.
I do not know the jQuery equivalent of many of these API's or methods, so I've used Vanilla JavaScript to create a demo which, hopefully, demonstrates what you try to accomplish.
If you have any question, I've been unclear, or have not helped you in any way. Please let me know.
const form = document.getElementById('step-form');
const summary = document.getElementById('step-summary');
const clear = document.getElementById('step-clear');
// Remove all children of the summary list.
function clearSummary() {
while(summary.firstElementChild) {
summary.firstElementChild.remove();
}
}
// Clear list on click.
clear.addEventListener('click', event => {
clearSummary();
});
form.addEventListener('submit', event => {
// Clear list first.
clearSummary();
// Create a fragment to store the list items in.
// Get the data from the form.
const fragment = new DocumentFragment();
const formData = new FormData(event.target);
// Turn each entry into a list item which display
// the name of the input and its value.
// Add each list item to the fragment.
for (const [ name, value ] of formData) {
const listItem = document.createElement('li');
listItem.textContent = `${name}: ${value}`;
fragment.appendChild(listItem);
}
// Add all list items to the summary.
summary.appendChild(fragment);
event.preventDefault();
});
<form id="step-form">
<div class="one">
<input type="radio" id="1-1" name="1-level" value="1">
<label for="1-1">1</label>
<input type="radio" id="1-2" name="1-level" value="2">
<label for="1-2">2</label>
</div>
<div class="two">
<input type="radio" id="2-1" name="2-level" value="1">
<label for="2-1">1</label>
<input type="radio" id="2-2" name="2-level" value="2">
<label for="2-2">2</label>
</div>
<div class="three">
<input type="radio" id="3-1" name="3-level" value="1">
<label for="3-1">1</label>
<input type="radio" id="3-2" name="3-level" value="2">
<label for="3-2">2</label>
</div>
<ul id="step-summary"></ul>
<button type="submit">Review form</button>
<button type="button" id="step-clear">Clear summary</button>
</form>

Selected value of Radio Button doesn't change

In the view, I have these two radio buttons:
#Html.RadioButtonFor(c => c.CampaignType, "Exclusive")<label>Exclusive</label>
#Html.RadioButtonFor(c => c.CampaignType, "Shared")<label>Shared</label>
The value for Model.CampaignType is set in the controller before the page loads. All of this works fine. If Exclusive is what's saved in the DB, then we get this rendered in the HTML:
<input checked="checked" id="CampaignType" name="CampaignType" type="radio" value="Exclusive"><label>Exclusive</label>
<input id="CampaignType" name="CampaignType" type="radio" value="Shared"><label>Shared</label>
So far, all's well.
But, inside an onclick() event for a button, if I do this:
var values =
{
"CampaignType": $('#CampaignType').val()
}
alert(values.CampaignType);
The alert always comes up as `Exclusive', even if I have changed the selection to 'Shared'.
What do I need to do so that values.CampaignType reflects the what is selected on the page, and not what was set when the page was loaded?
So you can do start with these:
Remove the invalid ids - multiple ids are invalid in CSS. For getting the value of the checked radio button you can use:
$('input[name=CampaignType]:checked').val()
or
$('input[type=radio]:checked').val()
For the label to work you have to link it with the corresponding radio button using the for attribute.
See demo below:
function submit() {
var values = {
"CampaignType": $('input[name=CampaignType]:checked').val()
}
console.log(values.CampaignType);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input checked="checked" id="CampaignType1" name="CampaignType" type="radio" value="Exclusive">
<label for="CampaignType1">Exclusive</label>
<input id="CampaignType2" name="CampaignType" type="radio" value="Shared">
<label for="CampaignType2">Shared</label>
<br/>
<button onclick="submit()">click here</button>
All the best!

how to validate form validation based on radio button

i have two radio buttons, one is for fruits and dry fruits. For every radio button i display two text fields, i want to validate these text fields based on the radio button( means based on user which radio button we select).
I hardly working from morning, any idea.
Consider following just as example and will help you to sort out your problem
Below code will be part of your HTML
<input name="radio_" type="radio" value="fruit" id="fruitRadio" />
<input name="radio_" type="radio" value="dryfruit" id="dryfruitRadio" />
<input name="inputforfruitradio" type="text" value="fruit" id="fruitRadioInputText" />
<input name="inputfordryfruitradio" type="text" value="dryfruit" id="dryfruitRadioInputText" />
Above HTML code will need Javascript to work as required
$("#fruitInputText").hide();
$("#dryfruitInputText").hide();
$('input[name="radio_"]').on('change', function() {
var checked_radio = $(this).prop('id');
var inputText_id_to_be_shown = "#" + checked_radio + "InputText" ;
$(inputText_id_to_be_shown).show();
});

Adding ID to button, but must change based on radio input selection

EDITED TO ADD HTML: not exactly the same since im not in my office anymore, but you'll get the idea.
The scenario is i have a part of a site where users can pick 1 of multiple addresses they have saved. The ID gets generated for each address and I need to apply that ID to a button to submit the form.
I've gotten it so the button receives the ID from the first click, but if I try to select a different address, the ID will not switch. How can I have the button use the ID of the most recently selected radio input? I'm using a data attribute to select this.
HTML:
<div>
<form>
<input type="radio" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" dat-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>
var radioID = $('*[data-js]').attr('id');
var addrContinue = $('.address-continue');
$('*[data-js]').click(function () {
$(addrContinue).attr('id', radioID);
});
Scenario: user clicks on address 1, so ID is then placed on the button for address 1. user made a mistake, meant to click on address 2. currently when i click address 2, the ID on the button doesn't change. it remains the same as the original click.
I need the ID on the continue button to change based on the proper radio selection.
Since id is unique use class
$('*[data-js]').click(function () {
var addrButton = $('.address-continue');
addrButton.removeClass(test123);
addrButton.removeClass(test124);
radioID = $('*[data-js]').attr('id');
addrButton.addClass(radioID);
});
Also your basic problem might be because you did not collect your radioID in ur radio function hence it wasn't updated so try this
$('*[data-js]').click(function () {
var radioID = $('*[data-js]').attr('id');
$(addrContinue).attr('id', radioID);
});
The following should do it for you hoping the corresponding elements are in the same order:
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
You cannot assign a second element in your document the id of another. IDs should be unique; therefore I have used data-id.
$('[data-js]').on('change',function() {
$('.address-continue').data('id', this.id);
});
$('.address-continue').on('click',function() {
alert( $(this).data('id') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form>
<input type="radio" name="address" data-js="select" id="Test123" /> (id created dynamically)
<label>Address 1</label>
<input type="radio" name="address" data-js="select" id="Test124" /> (id created dynamically)
<label>Address 2</label>
</form>
</div>
<button class="address-continue">Continue</button>

Categories

Resources