Edit: altered example code to include relevant typescript
I have a form with different buttons for the user to select. The button to submit the form is disabled until the user selects a button. The trick here is that I would like one of the options to not enable the submission button, but to instead show a textbox. The button should then be enabled if the user enters something into the textbox. At the moment, my HTML looks a little something like this:
<h1>Do you like sandwiches?</h1>
<form id="my-form" action="onSubmit()">
<div>
<button *ngFor="let option of myOptions"
class="form-button"
(click)="selectThisButton(option)">{{ option }}</button>
<div id="other-input" *ngIf="showInput">
<label for="text-input">Please elaborate.</label>
<input id="text-input" type="text" required>
</div>
</div>
</form>
<!--...some other code...-->
<button id="submit-button" form="my-form" type="submit" disabled="!my-form.valid">Next</button>
The typescript class is fairly straightforward as well:
selectedOption: string
showInput = false
needsExplanation = false
myOptions = ["Yes", "No", "I don't understand", "Other"]
selectThisButton(option: string){
this.selectedOption = option
this.needsExplanation = (option === "I don't understand")
this.showInput = (option === "Other")
}
onSubmit(){
if(this.selectedOption === "Other"){
this.selectedOption = (document.getElementById("text-input") as HTMLInputElement).value
}
continueAndDoOtherStuff()
}
All of this works except for the last step, i.e. entering something into the textbox doesn't enable the "next" button when it should.
I've also tried not using a form and just putting an EventListener on the textbox after the ngIf has rendered to listen for a keyup event, but that didn't work either.
Any help would be appreciated, especially suggestions that don't rely on jQuery.
a little bit short on time, so I'll work this answer further out later if you would like me to do so.
Why don't you add a (keyup.enter)-event in the input-box, e.g. (Angular 6 add input on enter key)?
The method you link to this event in the html-template, use it in the typescript template to switch a boolean true/false and link that boolean to the submit-button you want to enable/disable. (Like you're already doing.)
Please let me know:
(i) if you want this answer to be worked out
(ii) if it didn't help you (and what happened).
Take care and good luck.
(Sorry for the limited answer.)
Is there a motivation for using plain buttons instead of radio buttons?
Then, why don't you use the the APIs that Angular gives you?
First of all you could use [(ngModel)] instead of the selectThisButton function:
<form id="my-form" #form="ngForm">
<div>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="yes" id="yes" name="selection" />
<label for="yes">Yes</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="no" id="no" name="selection" />
<label for="no">No</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="dont-understand" id="dont-understand" name="selection" />
<label for="dont-understand">I don't understand the question</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="other" id="other" name="selection" />
<label for="other">Other</label>
<div id="other-input" *ngIf="selectedValue === 'other'">
<label for="text-input">Please elaborate.</label>
<input id="text-input" type="text" required>
</div>
</div>
</form>
<!--...some other code...-->
<button id="submit-button" form="my-form" type="submit" [disabled]="!form.valid">Next</button>
The only thing you need on your component.ts file is the selectedValue field:
#Component({
selector: ...,
templateUrl: './....component.html',
})
export class YourComponent {
selectedValue: string = undefined;
}
And your text input should be shown only when the other button is selected
Related
I want to store the correct answer(option) and the other 3 options as well. But for the other 3 options I will store those in database saying is_correct(column) 0/no/False. But for that, I'll have to have such logic that will figure out which radio button is for which input field. How do I bind/map a radio input field to a text input field?
I can, extract values out of these elements but can't figure out the logic.
<div id="option" class="form-group">
<input type="radio" name="option" required/><input type="text" name="option_1" required/><br/><br/>
<input type="radio" name="option" required/><input type="text" name="option_2" required/><br/><br/>
<input type="radio" name="option" required/><input type="text" name="option_3" required/><br/><br/>
<input type="radio" name="option" required/><input type="text" name="option_4" required/>
</div>
I just can't figure out the next step! Seen similar types of posts but not so similar tbh despite the concept being same.
First off, I really don't understand why you use radio buttons and a input text. In my opinion, just switch the input text to labels, or if you want the user to type the answer just give him 1 input text.
That being said, keeping the design you've made:
HTML:
<div id="options" class="form-group">
<input type="radio" id="option_text" required/><input type="text" id="option_1" required/><br/><br/>
<input type="radio" id="option_text2" required/><input type="text" id="option_2" required/><br/><br/>
<input type="radio" id="option_text3" required/><input type="text" id="option_3" required/><br/><br/>
<input type="radio" id="option_text4" required/><input type="text" id="option_4" required/>
<button type="submit" id="sub">
Press me
</button>
</div>
<div id="output1">
</div>
<div id="output2">
</div>
<div id="output3">
</div>
<div id="output4">
</div>
Javascript:
$("#sub").on('click',function(){
let eachone=[];
eachone[0]=$("#option_1").val();
eachone[1]=$("#option_2").val();
eachone[2]=$("#option_3").val();
eachone[3]=$("#option_4").val();
$("#output1").html(eachone[0]+" - "+$("#option_text").prop("checked"))
$("#output2").html(eachone[1]+" - "+$("#option_text2").prop("checked"))
$("#output3").html(eachone[2]+" - "+$("#option_text3").prop("checked"))
$("#output4").html(eachone[3]+" - "+$("#option_text4").prop("checked"))
})
If you want to alter something, or test for your exact test case, here is the fiddle
Jfiddle.
Note I'm using jQuery, just for ease of code, you can change most of the jquery references to document.getElementById
Edit:
Updated fiddle with checkboxes: JFiddle
Edit2:
Updated fiddle with single option checkboxes:
Jfiddle2
Warning: the event created might break some other input type checkboxes you have in your code!
First I think you should use the value attribute of the radioButtons instead of the second input, just put the text in a span or a label :
<input type="radio" id="option1" name="option" value="option1">
<label for="option1">8</label>
then you can get the selected value by doing:
var selectedOption = null;
if (document.getElementById('option1').checked) {
selectedOption = document.getElementById('option1').value;
}
After that, you can query the db to see if the selected option is correct or not.
How about instead of submitting the form with form data, you submit a JSON string/object?
So, your object for question can be something like
{
"question" : "How many planets orbit around the sun?",
"options" : [{
"name" : "1",
"value" : "7",
"isAnswer" : false
}, {
"name" : "2",
"value" : "8",
"isAnswer" : true
}]
}
Now, what's left is to create this object when the submit button is clicked.
To do that, you can have ids such as
<input type="radio" id="radio-1" name="option" required/>
<input type="text" id="text-1" required/>
These elements can be created dynamically, or manually if you are making the page just for a single question.
Now, when the button to submit the form, is clicked, you can run the below code which constructs a JSON object.
let question = {};
question.question = $("#question").val(); //Assuming you are using jQuery and id for question input box is question.
question.options = [];
for(i=0; i<4; i++) {
let option = {};
option.name = (i+1); //convert to ascii if you want alphabets
option.value = $("#text-"+(i+1)).val();
option.isAnswer = $("#radio-"+(i+1)).checked;
question.options.push(option);
}
You can now send this question object to your server.
<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />
So basically, this is my html. What I want to do now, is to use JavaScript, not jQuery, to clear the text input field (if something had previously been entered) whenever the radio buttons are clicked and to uncheck the radio buttons whenever someone clicks onto the text field. I quickly found a jQuery solution, but got the task to use JavaScript instead. As I'm not having very much experience with JS, I can't wrap my head around it to get it to work.
Any thoughts?
Would appreciate very much.
You can use .querySelectorAll() and .querySelector() in order to find the elemnts and .addEventListener() to attach the event handlers:
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.addEventListener('change', function(e) {
document.querySelector('#locationName').value = '';
});
});
document.querySelector('#locationName').addEventListener('input', function(e) {
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.checked=false;
});
})
<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />
How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});
To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo
OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!
I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!
I have some test code here
<input type="radio" name="group1">1
<input type="radio" name="group1">2
<input type="radio" name="group1">3
<br>
<input type="text" name="text1">
<br>
<input type="radio" name="group2">1
<input type="radio" name="group2">2
<input type="radio" name="group2">3
<br>
<input disabled type="submit">
Please can you tell me if there is a way to watch multiple fields so that if their values changes i can enable a button..
So in short instead of having 3 .change rules watching each other... can't i do one piece of code that watches all 3 and if the values equals a particular something it enables the submit button ?
Thanks
Lee
$(':radio').change(function() {
if ($(this).attr('name') == 'group2')
$(':submit').removeAttr('disabled');
});
You can use the click event hander. For e.g.:
$(":radio[name='group1'],:radio[name='group2'],:radio[name='group3']").live("click",function(){
//do something
});
if i correct understood ur question, here it is:
set classes (for less JS code):
<input type="radio" class="g1-1" name="group1">1
<input type="radio" class="g1-2" name="group1">2
<input type="radio" class="g1-3" name="group1">3
<br>
<input type="text" class="text" name="text1">
<br>
<input type="radio" class="g2-1" name="group2">1
<input type="radio" class="g2-2" name="group2">2
<input type="radio" class="g2-3" name="group2">3
<br>
<input disabled type="submit">
JS:
$(function(){
$('input').click( function(){
if ( ($('.g1-2').is(':checked')) && ($('.g2-1').is(':checked')) && ($('.text').val()=="ok" ))
{
// event
}
});
});
Sounds like a candidate for http://knockoutjs.com/ - You associate DOM elements with a client-side view model. When the data model's state changes, the UI updates automatically.
If your jQuery selector matches more than one element, when you bind a callback function to an event, that function will be bound to all the elements the selector matches.
Example:
$('input[type="radio"]').change(function() {
$('body').append('changed');
});
See a working fiddle here