Jquery get value of text box next to a radio button - javascript

I am creating a form with multiple radio buttons and text boxes.
Each Text box is next to radio button like below:
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="correct_answer_id">
Correct
</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required>
</div>
</div>
There are several radio button and text box pair like above in the form.
On click of the radio button, i want to get whatever has been written in the corresponding text box
i am trying to use Jquery's next() function like below:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).next('input[type="text"]').val());
}
});
But my log shows undefined. What i am doing wrong?

Try this : find parent div of radio and do next().next() to get input box div and then find input box to get value.
NOTE - You need not to check if ($(this).is(':checked')) as when you click on radio button it will get checked always.
$('input[type="radio"]').click(function(){
var value = $(this).closest('.radio').next().next('.col-sm-10').find('input[type=text]').val();
console.log(value );
});

use below code using parents(); see working fiddle
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parents('div.radio').next().next('div.col-sm-10').find('input[type="text"]').val());
}
});

You should put the value that you want submitted in the value attribute of your input elements.
e.g. <input type="radio" name="correct_answer_id" value="correct">
Your click handler would change to:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).val());
}
});
If there's some value that you don't want to place in the value attribute then it's still best to have a reference to the value in the input element instead of relying on a particular document layout.

Try this
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parent().parent().siblings().find('input[type="text"]').val());
}
});
Working Demo

If you can change the html a little, here is a different approach http://jsfiddle.net/xa9cjLd9/1/
<div class="form-group">
<div class="radio">
<label data-for='answer[]'>
<input type="radio" name="correct_answer_id" />Correct</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required />
</div>
</div>
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
var data = $(this).closest('label').attr('data-for');
console.log($('input[name=' + '"' + data + '"' + ']').val());
}
});
Just Define a data attribute to the label , which contains the name of the related input.

Related

Adding +1 in the end of the class

I have been studying JavaScript/JQuery lately on my free time. I am trying to make script choose between 2 checkboxes. If first checkbox is true then the second is false, if first one is false then second is true. This one works but it doesn't work on multiple classes. I have added 2 classes .checkbox-group1 and .checkbox-group2. I tried to make script add +1 to .checkbox-group 2 times but it only adds so I would get classes .checkbox-group1 and .checkbox-group2 but I only get .checkbox-group1.
Javascript/JQuery
$(document).ready(function(){
var i = 0;
if(i<2){
i++;
}
else{
i = 1;
}
$('.checkbox-group'+ i +' input:checkbox').click(function() {
$('.checkbox-group'+ i +' input:checkbox').not(this).prop('checked', false);
});
});
HTML CHECKBOXES
<div class="checkbox-group1 required">
Yes: <input type="checkbox">
No: <input type="checkbox">
</div>
<div class="checkbox-group2 required">
yes: <input type="checkbox">
No: <input type="checkbox" >
</div>
You dont need a loop, you can get the right checkbox in a var and then set all checkbox of the div to false. Finally, you set the right one to checked.
I commented my code.
$(document).ready(function(){
// we get div with class name starting like : checkbox-group
$("div[class^='checkbox-group'],div[class*='checkbox-group']").click(function(event) {
// we save current clicked element in a var
var getCurrentChecked = event.target;
// we set all input checked to false
$(this).find('input:checkbox').prop('checked', false);
// then we check the right one
$(getCurrentChecked).prop('checked', true);
console.log($(this).attr('class') + ' - ' + $(getCurrentChecked).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML CHECKBOXES
<div class="checkbox-group1 required">
Yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>
<div class="checkbox-group2 required">
yes: <input type="checkbox" value="0">
No: <input type="checkbox" value="1">
</div>

when check a checkbox, checked other checkbox with same value with javascript

I have two forms with radio type inputs, I would like that when we check an input in the 1st form another input is automatically checked in the second.
Here is the code of the 1st form:
<div class="color-box cta-box">
<label>Colors</label>
<div class="vpc-single-option-wrap">
<input id="cta-couleur_noir-color-selector" type="radio" name="couleur-color-selector" data-field="couleur-field" checked="" data-qtip="no">
<label for="cta-couleur_Noir-color-selector" class="vpc-custom-color custom" data-selector="couleur-field" data-color="Noir" data-name="Noir" data-oriontip="Noir" style="background-color:#000000"></label>
</div>
<div class="vpc-single-option-wrap">
<input id="cta-couleur_bleu-color-selector" type="radio" name="couleur-color-selector" data-field="couleur-field" data-qtip="no">
<label for="cta-couleur_Bleu-color-selector" class="vpc-custom-color custom" data-selector="couleur-field" data-color="Bleu" data-name="Bleu" data-oriontip="Bleu" style="background-color:#0419bd"></label>
</div>
</div>
And here is the code of the 2nd form:
<div class="color-box cta-box">
<label>Colors</label>
<div class="vpc-single-option-wrap">
<input id="cta-texte-en-tete-centre_noir-color-selector" type="radio" name="texte-en-tete-centre-color-selector" data-field="texte-en-tete-centre-field" checked="" data-qtip="no">
<label for="cta-texte-en-tete-centre_Noir-color-selector" class="vpc-custom-color custom" data-selector="texte-en-tete-centre-field" data-color="Noir" data-name="Noir" data-oriontip="Noir" style="background-color:#000000"></label>
</div>
<div class="vpc-single-option-wrap">
<input id="cta-texte-en-tete-centre_bleu-color-selector" type="radio" name="texte-en-tete-centre-color-selector" data-field="texte-en-tete-centre-field" data-qtip="no">
<label for="cta-texte-en-tete-centre_Bleu-color-selector" class="vpc-custom-color custom" data-selector="texte-en-tete-centre-field" data-color="Bleu" data-name="Bleu" data-oriontip="Bleu" style="background-color:#0419bd"></label>
</div>
</div>
So I would like that when I check the input with the ID cta-couleur_noir-color-selector in the 1st form, the input with the ID cta-texte-en-tete-centre_noir-color-selector "is automatically checked in the second form and the same for the id" cta-couleur_bleu-color-selector "which would correspond to the ID" cta-texte-en-tete-center_bleu-color-selector .
I tried with this script but it doesn't work:
<script type="text/javascript">
jQuery('input[type=radio][name=couleur-color-selector]').on('change', function () {
if ( jQuery(this).attr('id') == 'cta-couleur_bleu-color-selector'.checked) {
jQuery('#cta-texte-en-tete-centre_bleu-color-selector').prop(checked, true);
}else
{
jQuery('#cta-texte-en-tete-centre_noir-color-selector').prop('checked', true);
}
});
</script>
Could someone help me?
You must set unique value for each radio box in 1st form.
and check when radio click => get value and check to same unique value in 2nd form.
example:
$(document).on('click', '[type="radio"]', function () {
let value = $(this).val();
$('[value="'+value+'"]').prop('checked', true);
});

Use checkbox to clear/update radio buttons in html/angularjs

My form has a checkbox followed by several radio buttons.Basically, the design calls for a user to be able to use a checkbox to clear a set of radio buttons (or set a default value). If the user should select a radio button then the checkbox will also be set.
Overall most of the requirements are met by the code below, however there is one condition when it doesn't work:
User Selects Checkbox. (Check appears in checkbox)
User Selects Radio button. (Radio button is selected)
User Selects Checkbox Again. (Check disappears from checkbox and radio button deselects)
User Selects Radio button. (Check appears in checkbox and radio button selects)
User deselects Checkbox. (Check disappears but the value isn't updated so the radio button does not deselect)
What is happening? How can this be written to get the behavior my user wants?
Thanks,
Matt
Here is the code:
var myAngular=angular.module('myApp',[]);
myAngular.controller('myController',function($scope){
$scope.title="Angular Radio Buttons";
$scope.selectedValue='i10';
$scope.numStatus = 0;
$scope.numStatusChanged = function () {
console.log('numStatusChanged:')
if ($scope.numStatus === 0) {
$scope.numStatus = 3;
console.log('From 0 to 3.');
} else {
$scope.numStatus = 0;
console.log('From ' + $scope.numStatus + ' to 0.' )
}
};
$scope.$watch('numStatus', function(newValue,oldValue,scope){
console.log('newVal:' + newValue + ' oldValue:' + oldValue);
});
$scope.$watch('aBool', function(newValue,oldValue,scope){
console.log('aBoolNew:' + newValue + ' aBoolOld:' + oldValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller='myController'>
<p>Selected Value: {{numStatus}}</p>
<div class="checkBoxGroup">
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-checked="numStatus !== 0" ng-change="numStatusChanged()">
<label for="isCheckbox">A Value Is Selected</label>
<div class="radio-button-vertical">
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="1" name="numStatus" /> One</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="2" name="numStatus" /> Two</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="3" name="numStatus" /> Three</label>
</div>
</div>
</div>
</div>
</div>
You are using ngChecked and ngModel together, I would expect that your issue is that those two properties are conflicting with each other since they represent similar bindings (other SO post explaining this).
Just rewrite the checkbox to be:
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-change="numStatusChanged()">
and then do the numStatus !== 0 check in the numStatusChanged() method and use the result to set aBool.

Add required to input of hidden div when radio is checked

What I'm trying to do is to set hidden div with inputs depended on checked radio input.
This is the logic:
If the first radio is checked the first div is shown, there I want to add hidden inputs with some values...
If the second radio is checked I want the input to be added with required..
And, it shouldn't be required if the 2nd radio isn't checked...
I've tried a few things over some time and got some effects but can't get it work as I want, Here is the code that i'm currently trying to work with, sorry but it's messed up and fails...
So Any help will be much appreciated...
/*
// this code is working but I messed the HTML while trying to get it work with the other code below...
$(document).ready(function() {
$("div.hiddendiv").hide();
check();
$("input[name$='name02']").change(check);
function check() {
var test = $("input[name$='name02']:checked").val();
$("div.hiddendiv").hide();
$("#" + test).show();
}
}
*/
// The code i'm trying to work with...
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
//add required
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="closed" value="01"> Closed
<input type="radio" id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" type="text" value="">
</div>
Here is the JSFiddle,
try this code
give same name of radio button so it will work as a group and
also set id of input tag as name02 so its use as a #name02 in jquery
so it will work
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
$(this).click(function() {
if ($('#closed').is(':checked')) {
hidden.show();
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='btn' id="closed" value="01"> Closed
<input type="radio" name='btn' id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" id="name02" type="text" value="">
</div>
Part of your problem is that you need to set the name attribute of your radio buttons to be the same value, otherwise the HTML won't know that they belong to the same group.
I've updated the JSfiddle here
https://jsfiddle.net/hba4d83k/2/
What i have done is add a change event handler to your the radio group and then did some conditional logic to show/hide the relevant inputs.

JQuery: how to check if checkbox is checked and add attributes to field

I'm trying to check whether a check box is checked, and if it is checked, then I want to add the "required" attribute to an adjacent text field. I've tried it two different ways with no success. Here are the form elements and my two JQuery attempts.
neither of those will actually trigger the event. My browser either does nothing at all or triggers an "Empty string passed to getElementById()." event
Form elements:
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<g:textField name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label"/>
<label class="checkbox-inline">
<g:checkBox name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" onclick="chkboxYesChecked()"/>
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<g:textField name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label"/>
</div>
JQuery:
function chkboxYesChecked(){
if($('#checkboxYesNo').prop('checked')){
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
}else{
$('#someTextField').removeAttr('required');
}
}
$(document).ready(function() {
$('#checkboxYesNo').click(function() {
if($(this).is(":checked"))
{
$('#someTextField').prop('required',true);
$('#someTextField').append('<span class="required-indicator">*</span>');
} else {
$('#someTextField').removeAttr('required');
}
});
});
With your markup this becomes more convoluted than it needs to be.
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
Notes
This approach uses event delegation.
There are no IDs involved, because I suppose you need the same thing more than once on your page. Tying it to a specific element ID is counter-productive.
This approach relies on the specific document structure from your sample Grails template. If you want something more flexible and easier-to-read, change your HTML.
This applies to all checkboxes that have a text field in the immediately following <div>. Use CSS classes on your elements to filter it/make it apply to specific ones only.
If there is no immediately following <div> with a text box, the function does nothing.
$(this).is(":checked") is superfluous. You don't need jQuery to find out if the current DOM element is checked. this.checked is a lot simpler and has the same effect.
Don't use inline event handlers (onclick="..."). Ever.
See it in action:
$(document).on("click", ".checkbox-inline :checkbox", function () {
var $nextTextbox = $(this).closest("div").next("div").find(":text").first();
if (this.checked) {
$nextTextbox.prop("required", true).after('<span class="required-indicator">*</span>');
} else {
$nextTextbox.prop("required", false).next('.required-indicator').remove();
}
});
input[required] {
background-color: #FFD1D1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label id="checkboxNumber-label" class="toplabel" for="checkboxNumber">Checkbox</label>
<input type="text" name="checkboxNumber" value="${...checkboxNumber}" class="form-control" required="" aria-labelledby="checkboxNumber-label" />
<label class="checkbox-inline">
<input type="checkbox" name="checkboxYesNo" id="checkboxYesNo" value="${...checkboxYesNo}" />
</label>
</div>
<div class="col-sm-5">
<label id="someTextField-label" class="toplabel" for="someTextField">Some Text Field Here</label>
<input type="text" name="someTextField" id="someTextField" value="${...someTextField}" class="form-control" aria-labelledby="someTextField-label" />
</div>

Categories