How to make radio buttons with same value reusable? - html

I am a beginner to Vue, and learning something by doing. I was able to make a checkbox reusable, but getting some weird result for radio buttons.
I have the data in an array format in ProgramDesign.vue:
data() {
return {
strategies: [
"Not Important",
"Slightly Important",
"Moderately Important",
"Very Important",
"Extremely Important",
],
};
},
These are the options that get repeated on every question.
I made a separate component for the radio like this:
<template>
<div>
<span v-for="strategy in groups" :key="strategy">
<input :id="strategy" class="radio-style" name="strategy" type="radio" />
<label :for="strategy" class="radio-style-3-label">{{strategy}}</label>
</span>
</div>
</template>
<script>
export default {
props: {
groups: Array,
},
};
</script>
This is how it's used in ProgramDesign.vue:
<p>first question goes here ?</p>
<RadioButton :groups="strategies" />
<div class="line"></div>
<p>second question goes here ?</p>
<RadioButton :groups="strategies" />
I was able to get the reusable output, but when I click on the radio button for the second question, the buttons for the first question get selected. How can I fix this?

The problem is the input IDs and names are not unique between component instances, as can be seen in the rendering of your two RadioButton components (simplified for brevity):
<!-- RadioButton 1 -->
<div>
<span>
<input id="Not Important" name="strategy" type="radio">
<label for="Not Important">Not Important</label>
</span>
</div>
<!-- RadioButton 2 -->
<div>
<span>
<input id="Not Important"❌ name="strategy"❌ type="radio">
<label for="Not Important">Not Important</label>
</span>
</div>
Each label is linked to an input by matching the for and id attributes, such that clicking the label causes the linked radio input to change values. When there are multiple inputs with the same identifier, the browser links the label to the first matching input, causing the behavior you observed.
The name must also be unique between groups (RadioButton instances), since the browser creates radio groups of inputs that have matching names.
Solution
Alternatively, a label and input can be linked by putting the input inside the label, resolving the id/for duplication (and improving readability):
<label>
<input name="strategy" type="radio">
Not Important
</label>
And one way to resolve the duplicate names is to base the name on a counter incremented per instance:
<template>
<div>
<label v-for="strategy in groups" :key="strategy">
<input :name="'strategy' + groupId" type="radio">
{{strategy}}
</label>
</div>
</template>
<script>
let groupId = 0
export default {
props: {
groups: Array
},
data() {
return {
groupId: groupId++
}
}
}
</script>

Related

Is there a way to check the already checked Formik Checkbox on re-rendering?

So basically, I have two screens. One screen has a form which I am rendering through Formik and on the other page I am printing the response from my API based on the form values and a back button to go back to the previous screen (having the form).
My concern is when I enter the fields correctly including the checkbox and then submit the form then go onto second screen and then when I come back to the first screen(form screen), the fields which takes written input as their respective values show as filled but the checkboxes show as unchecked.
My code for useFormik is as following:
const metalsFormData = useFormik({
initialValues: {
metal: [],
riskLevel: "Select Risk Type",
age: "",
retirement: "",
retirementZipCode: "",
retirementVehicle: "",
dependantAge: ""
},
validationSchema: Yup.object({
metal: Yup.array().min(1, 'Please select an option'),
age: Yup.string().required('Please enter an age.'),
retirement: Yup.array().min(1, 'Please select an option'),
retirementZipCode: Yup.string().required('Please enter a zip code.'),
retirementVehicle: Yup.array().min(1, 'Please select an option')
}),
onSubmit: (rawObject) => {
props.portfolioData(rawObject);
setStep2(true);
}
});
My HTML for checkbox is as following:
<div className='secure-checkboxes'>
<div role="group" aria-labelledby="checkbox-group">
<label>
<input type="checkbox" name="retirement" value="Yes" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
<span>Yes</span>
</label>
<label className='ml-4'>
<input type="checkbox" name="retirement" value="No" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
<span>No</span>
</label>
</div>
</div>
I would like that when I come to the second screen after filling all the fields including checkboxes and then come back to the first screen having the form, all the fields should be prefilled with the values I had written and the checkboxes shall be shown as checked.

How to create a popup that provides user multiples options?

Currently I am designing a user opinion page where I planned to get input from user like "Is it suitable?"
Possibly the input could be YES / NO / No Idea
The native controls such as alert() or confirm(), prompt() etc doesn't provide more than two options.
Is there a native control , that can provide more than two options..?
If not, How can I create one using angular-ui or jquery-ui?
<input type="radio" name="group1" value="yes"> Yes<br>
<input type="radio" name="group1" value="no"> No<br>
<input type="radio" name="group1" value="no_idea" checked> No Idea<br>
It's just standard html. Why you think it's need jquery or angular ?
You can use the jQuery UI dialog widgets buttons option.
It accepts either an object whose keys are the buttons's label, and value is the callback function or an array of objects defining the attributes, properties, and event handlers to set on the button.
The context of the callback functions is the dialog element. You can use the target property of event in case you want to access the button.
$(function() {
$("#dialog").dialog({
title:"Is it suitable?",
buttons: [{
text: "Yes",
click: function(event) {
$(this).dialog("close");
}
}, {
text: "No",
click: function(event) {
$(this).dialog("close");
}
}, {
text: "No Idea",
click: function(event) {
$(this).dialog("close");
}
}]
});
});
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

Checkbox Value not populating

I could not figure out why checkbox is not displaying value . the original code is
<input type="checkbox" name="#row.Checkbox.Name" value="#row.Checkbox.Text"/>
generated HTML Is
<input type="checkbox" name="chkparent" value=" I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times."/>
I tried to put generated html directly in page but still it does not show value .
what i see is only the checkbox box.
A checkbox's value cannot be used for showing text. You need to put a div or similar next to the checkbox. Like so:
<div>
<input type="checkbox" name="chkparent" style="float:left;margin-right:5px;"/>
<div>
I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times.
</div>
</div>
If you want to make this easy for the user, you should attach a click handler to the text (assuming jQuery):
<div>
<input type="checkbox" id="chkparent" name="chkparent" style="float:left;margin-right:5px;"/>
<div id="chktext" style="cursor:pointer;">
I am the parent or legal guardian of the named child/children in my family membership and I give consent for them to take part in organised paddling activities (Kayak and/or Canoe) and I agree they will abide by the rules and regulations of Totnes Canoe Club at all times.
</div>
</div>
<script>
$(function(){
$("#chktext").on("click", function(){
if ($("#chkparent").is(":checked")) {
$("#chkparent").prop("checked", false);
} else {
$("#chkparent").prop("checked", true);
}
});
});
</script>
You would be better off creating a strongly typed view model with a bool property for this and decorating it with a display name.
The display name can then be used to render a label for as follows:
View Model
public class AViewModel
{
[DisplayName("Selection 1")]
public bool MySelection { get; set; }
}
View
#Html.LabelFor(m => m.MySelection)
#Html.CheckBoxFor(m => m.MySelection)
Working example
You can validate the row.Checkbox value in your controller before returning the View, to check whether the checkbox should or should not be checked.
Then, assign that information to a ViewBag variable:
ViewBag.checked = "checked";
And in your View:
<input type="checkbox" name="#row.Checkbox.Name" #ViewBag.checked/>
This will produce an HTML of
<input type="checkbox" name="#row.Checkbox.Name" checked/>
if the checkbox should be checked and
<input type="checkbox" name="#row.Checkbox.Name"/>
for an unchecked checkbox
Without modifing your current model, code should look like this:
<label for="#row.Checkbox.Name">#row.Checkbox.Text #Html.CheckBox(row.Checkbox.Name, false)</label>

How to indicate that a group of radio buttons are required [duplicate]

This question already has answers here:
How to use the "required" attribute with a "radio" input field
(5 answers)
Closed 8 years ago.
I understand how to place an icon in a text field to indicate to the user that it is required and in HTML5 form get the tip indicating that the field should be filled out.
is there any similar mechanism for radio buttons and check boxes?
Below is a simple group of radio buttons that I am using.
<!DOCTYPE html>
<polymer-element name='marital-status-form'>
<template>
<style">
#col1 { order:1; }
#col2 { order:2; align-self:flex-start; }
#hr { order:3; }
</style>
<form id='form'
name='form'
on-change='{{updateModel}}'>
<section
<label for='marriedRdo' id='marriedLbl' >Married</label>
<label for='divorcedRdo' id='divorcedLbl' >Divorced</label>
<label for='singleRdo' id='singleLbl' >Single</label>
<label for='visitingRdo' id='visitingLbl' >Visiting</label>
</section>
<section >
<input id='marriedRdo'
name='status'
type="radio"
value='Married'
on-click='{{submit}}'>
<input id=divorcedRdo name='status' type='radio' value='Divorced'>
<input id='singleRdo' name='status' type="radio" value='Single' >
<input id=visitingRdo name='status' type='radio' value='Visiting'>
</section>
<hr id='hr'>
<delete-dispatch-form id='delete-dispatch-form'></delete-dispatch-form>
<button id='submit-btn'
type='submit'></button>
</form>
</template>
<script type="application/dart">
import 'package:polymer/polymer.dart' show CustomTag, observable, PolymerElement;
import 'dart:html' show Event, Node, InputElement;
#CustomTag( 'marital-status-form')
class MaritalStatusForm extends RooleElement
{
#observable String choice= '';
MaritalStatusForm.created() : super.created();
void updateModel(Event e, var detail, Node target)
{
//maritalStatus.status = (e.target as InputElement).value;
//print( encode( maritalStatus ) );
}
void submit ( Event e, var detail, Node target )
{
$['form'].onSubmit.listen( ( e )
{
e.preventDefault();
} );
}
}
</script>
</polymer-element>
A simple solution to this problem is select a radio button by default. That way, the user can either stay with the default, or pick a different option. This, in effect, 'requires' a group of radio buttons.
From a html point of view, you can add the 'required' attribute to one of the radio inputs in the group and it will require one of the options to be selected.
<input id='marriedRdo'
name='status'
type="radio"
value='Married'
on-click='{{submit}}'
required="required">
See this fiddle for a demo: http://jsfiddle.net/lickmydesign/5y4Lv6gc/

Refresh Angular output on input reset

I have several <input> fields within a <form>. Angular takes the value from those fields regardless of the <form> (which is actually there only for Bootstrap to apply the right styles to inner fields).
Now, I want to be able to reset the fields, and so get Angular update the output associated to them as well. However, a regular <input type="reset"/> button is not working. It resets the values of all the <input> fields, but Angular is not refreshing the output that is based on the fields after it.
Is there any way to tell Angular to refresh the outputs based on the current state of the fields? Something like a ng-click="refresh()"?
Let's say you have your model called address. You have this HTML form.
<input [...] ng-model="address.name" />
<input [...] ng-model="address.street" />
<input [...] ng-model="address.postalCode" />
<input [...] ng-model="address.town" />
<input [...] ng-model="address.country" />
And you have this in your angular controller.
$scope.reset = function() {
$scope.defaultAddress = {};
$scope.resetAddress = function() {
$scope.address = angular.copy($scope.defaultAddress);
}
};
JSFiddle available here.
You should have your values tied to a model.
<input ng-model="myvalue">
Output: {{myvalue}}
$scope.refresh = function(){
delete $scope.myvalue;
}
JSFiddle: http://jsfiddle.net/V2LAv/
Also check out an example usage of $pristine here:
http://plnkr.co/edit/815Bml?p=preview