Selecting a default radio input on page load Javascript - javascript

I have a page that when I change radio boxes it shows different content.
It works when I click radio boxes. But in an edit form, I would like the second radio option to be selected and content of second radio option to be shown on page load. The content is not shown when I populate 'checked' on the radio as shown in the demo.
Demo.
var aTag = document.querySelector("a.mylink");
aTag.addEventListener("click", function(e) {
e.preventDefault();
var query = document.querySelector("input[data-for='" + e.currentTarget.id + "']").value;
window.open(e.currentTarget.href + "?query=" + query, "_blank");
}, false);
// radio element click event handler
var radioClickHandler = function() {
var first = document.querySelector('.first');
var second = document.querySelector('.second');
second.classList.add('hidden');
// show/hide required elements depending on which radio element was clicked.
if (this.value == 'product') {
first.classList.remove('hidden');
second.classList.add('hidden');
}
if (this.value == 'keyword') {
first.classList.add('hidden');
second.classList.remove('hidden');
}
}
// Get All Radio Elements
var radios = document.querySelectorAll('[type=radio]');
// Apply click event
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener('click', radioClickHandler);
}
// Apply Default
radioClickHandler.apply(radios[0]);
.hidden {
display: none;
}
<div class="col-md-8 offset-md-2">
<div class="m-form__group form-group row">
<div class="col-9">
<div class="m-radio-inline mt-3 type_selector">
<label class="m-radio">
<input type="radio" name="type" value="product" data-id="specific_product"> First
<span></span>
</label>
<label class="m-radio">
<input type="radio" name="type" value="keyword" required="" data-id="search_term" checked> Second
<span></span>
</label>
</div>
</div>
</div>
<style>
/*hides element*/
</style>
<div class="first">
<label for="" class="mt-2 mb-2"><strong>First Content</strong></label>
<select class="form-control m-select2 select2-hidden-accessible" id="m_select2_1" name="product_id" data-select2-id="m_select2_1" tabindex="-1" aria-hidden="true">
<option value="" data-select2-id="" disabled selected>Blabla
</option>
</select>
</div>
<div class="second">
<label for="exampleInputEmail1" class="pt-3"><strong>Second Content</strong></label>
<div class="row mt-1 ">
<div class="col-xl-8">
<input type="text" class="form-control m-input m-input--solid" data-for="search_term" name="{{$default_template->notification_toggle_id}}_search_term" value="" id="m_autosize_1" placeholder="blabla">
</div>
<div class="col-xl-4 align-self-center">
First Content
<script>
</script>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</div>
I tried several things like. But I couldn't succeed.
window.onload = radioClickHandler;
After
window.onload = function() {
The whole javascript snippet
};
Also this
var radios = document.querySelectorAll('.type_selector .m-radio input[type=radio]');

Working fiddle.
You could simply invoke the click event using :
radios[1].click();
Edit:
The problem happens since you're attaching the click event to all the radio button in the current document in the following line :
var radios = document.querySelectorAll('[type=radio]');
To fix this issue you need to encapsulate the first & second radios so you could attach the click to them separately :
<div id="first-second" class="m-form__group form-group row">
Then attach the event just to them like :
var radios = document.querySelectorAll('#first-second [type=radio]');

The onchange or onclick event does not fire when the selected option of the select object is changed programmatically or you fill the input value programmatically. So you do require to trigger that onchange or onclick after changing it in window.onload or init function.
To trigger the event use How to trigger event in JavaScript?

EDIT: I think it is the addition of the other radio buttons are being added to the same group so second is not your second radio but 5th so this will now work
radioClickHandler.apply(radios[5]);
http://jsfiddle.net/wy9xbhdo/

Related

How to checkbox enable/disable with Struts 2

I would like to show 2 checkboxs in my page (called box1 and box2). The default value is box1 = false and box2 = false. But I also have to enable box2 only if box1 = true. So I have created the following JS function :
function myTest() {
var check = document.getElementById('box1');
if (check.checked == false) {
$('#box2').prop('disabled', true);
} else {
$('#box2').prop('disabled', false);
}
}
Now I don't really understand how to use myTest function in the JSP file. I have tried to use it with onload="myTest()" as follow, but it doesn't work (box2 is always disabled).
<body onload="myTest()" />
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box1" />
</label>
<div class="col-sm-9">
<s:checkbox id="box1" name="box1"> </s:checkbox>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box2" />
</label>
<div class="col-sm-9">
<s:checkbox id="box2" name="box2"></s:checkbox>
</div>
</div>
It seems you are using jQuery in the page. Here is my solution.
<script type="text/javascript">
$( document ).ready(function() {
// on page load unchecking and disabling box2
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
});
$("#box1").on("change", function(){
if ($(this).prop("checked")){
// box1 is checked
$("#box2").prop("disabled", false);
}
else{
// box1 is not checked
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
}
});
</script>
There is onchange attribute for <s:checkbox> tag which is used for
Set the html onchange attribute on rendered html element
This tag generates a simple input field of checkbox type.
Renders an HTML input element of type checkbox, populated by the specified property from the ValueStack.
The action bean is on top of the ValueStack, so you can get the specified property there.
To define JS function in JSP you should use html <script> tag. You can do it in the <head> tag or after the rendered element.
<s:checkbox id="box1" name="box1" onchange="myTest()"/>
<s:checkbox id="box2" name="box2" %{box1?'':'disabled="disabled"'}/>
<script>
function myTest() {
if ($(this).prop("checked") === "checked") {
$("#box2").removeAttr("disabled");
} else {
$("#box2").attr("disabled","disabled");
}
}
</script>

Checkbox click is not working in safari for the first time

The delete button is disabled when the page load. There are multiple checkboxes on the form and when a user clicks a checkbox then the delete button change to enable. When a user unchecks the checkbox (didn't select any checkbox) then the delete button change to disabled. Also, all the selected checkbox value will be assigned to an input field separated by a comma.
Below code is working fine in chrome. But it's not working fine in Safari. In Safari user need to check, uncheck again they have to check (third time) or when they select the second checkbox then only the delete button change to enabled and the selected value is displaying in the input field. I don't know whats wrong with this code.
Please check this demo in Chrome and Safari you will get it.
DEMO
$(document).on("click", ".imgtitleclick", function (e) {
$checks = $('.imgtitleclickmodal');
$checks.on('change', function() {
var string = $checks.filter(':checked').map(function(i,v){
return this.value;
}).get().join(',');
$('.hiddenimgnumdis').val(string);
$('.hoverforport-img-del').prop('disabled', $checks.filter(':checked').length < 1);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button class="btn-danger hoverforport-img-del floatright" disabled data-toggle="modal" data-target="#confirm-delete-portfolio">Delete</button>
<ul class="photo-grid lightgalleryselector">
<div class="col-sm-4 col-xs-6 col-md-3 col-lg-3 shw mblpad hoverforport-img">
<label class="width100 editbtnprofilea nopadd posabsol imgtitleclick color5" for="1">
<input type="checkbox" value="1" class="imgtitleclickmodal" id="1">
</label>
</div>
<div class="col-sm-4 col-xs-6 col-md-3 col-lg-3 shw mblpad hoverforport-img">
<label class="width100 editbtnprofilea nopadd posabsol imgtitleclick color5" for="2">
<input type="checkbox" value="2" class="imgtitleclickmodal" id="2">
</label>
</div>
</ul>
<input type="text" class="hiddenimgnumdis"/>
Looks like you're binding the change event multiple times (anytime .imgtitleclick is clicked). It's also going to do it for all .imgtitleclickmodal because you haven't scoped it to the current checkbox... here's an example that is working for me:
$(document).on("click", ".imgtitleclick", function (e) {
$(this).find('.imgtitleclickmodal').trigger('change');
});
$(document).on("change", ".imgtitleclickmodal", function (e) {
var $checks = $('.imgtitleclickmodal');
var string = $checks.filter(':checked').map(function(i,v){
return this.value;
}).get().join(',');
$('.hiddenimgnumdis').val(string);
$('.hoverforport-img-del').prop('disabled', $checks.filter(':checked').length < 1);
});

Focus on next div when valid radio selection or text input has been made

I have a form. Whenever a user hits the enter key on a text input, or when they tap or click on a radio button, I want to be able to set the focus to the next
"formItem" div.
The structure of my form is set up like this:
<div class="formItem" ng-class="{'invalidField' : calculate.wasSkipped(calculationForm.nonsustainedVT)}">
<ng-form name="nonsustainedVT" novalidate>
<div class="header"><span class="title">3) Nonsustained VT </span></div>
<div class="content">
<div class="radioGroup">
<div class="radio-wrapper">
<input id="nonsustainedVTYes" type="radio" required name="nonsustainedVT" ng-value="true" ng-model="calculate.formData.nonsustainedVT" ng-click tabindex="4">
</div>
<div class="label-wrapper">
<label for="nonsustainedVTYes">Yes</label>
</div>
</div>
<div class="radioGroup">
<div class="radio-wrapper">
<input id="nonsustainedVTNo" type="radio" required name="nonsustainedVT" ng-value="false" ng-model="calculate.formData.nonsustainedVT" ng-click tabindex="5">
</div>
<div class="label-wrapper">
<label for="nonsustainedVTNo">No</label>
</div>
<span class="radioValidationHack!" ng-show="false">{{calculate.formData.nonsustainedVT}}</span>
</div>
</div>
</ng-form>
</div>
Every input has a tabindex, so I was considering using this somehow, but once a user has made a selection I do not wish to necessarily just move the focus to the next tabindex because it may be in the same radio group. I wish to set the focus to the next "formItem" div.
Please see the following Plunkr for a larger code example:
http://plnkr.co/edit/FQzOFEZLi6ReAuJninxA?p=preview
You don't need tab index, you can use the order of the tab items inside the form. I would make a myFormItem directive like this:
directive('myFormItem', function() {
return {
link: function(scope, element, attr) {
var form = element.closest('form'),
items = form.find('[my-form-item]'),
index = items.index(element),
nextFormItem = $(items[index+1]);
element.find('input[type=radio]').on('click', function() {
nextFormItem.find('input').focus();
});
element.find('input[type=text]').on('keypress', function(e) {
if (e.which === 13) {
nextFormItem.find('input').focus();
}
});
}
};
});
and you need to add the my-form-item attribute to each .formItem (btw, you should probably use kebab-case for classes)

How to get the value of a selected radio button before the change?

I have multiple radio button sharing the same name. One of them has a hidden div next to It.
When the correct radio button is selected, I want to show/hide the div that is next it to it "if one is there"
Here is an example
Radio 1
Radio 2
Radio 3
Radio 4
Next to Radio 2 there is a hidden div. I want to show it when Radio 2 is selected. Then when Radio 4 is selected, I want to hide the Radio 2 div
Here is what I have done
$(function(){
function getGroupElement(value)
{
return '#group_' + value.replace(':', '_');
}
var previous;
$("input[type='radio']").click(function(e) {
// Store the current value on focus and on change
previous = $(this).val();
console.log('Current:' + previous);
}).change(function(e) {
var previousGroupId = getGroupElement(previous);
var newGroupName = $(this).data('show-group');
//Hide the previous Group
$(previousGroupId).hide();
if ( ! newGroupName){
return;
}
$(newGroupName).show();
});
});
My code above is not working because previous is set to the next selected item.
How can I hide/show the correct box?
If needed here is my HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<fieldset class="survey-control-fieldset">
<div class="survey-control-title">
Select a store
</div>
<div class="radio">
<label for="item_529"><input checked id="item_529" name=
"control_111" type="radio" value="112:529"> None</label>
</div>
<div class="radio">
<label for="item_530"><input id="item_530" name="control_111" type=
"radio" value="112:530"> Don't Know/No Answer</label>
</div>
<div class="radio">
<label for="item_532"><input data-show-group="group_112_532" id=
"item_532" name="control_111" type="radio" value="112:532">
Other</label>
<div id="group_112_532" style="display: none;">
<div class="form-group">
<label for="control_113">Specify Other Store Name</label>
<input class="form-control" id="control_113" name=
"control_113" placeholder="" type="text" value="">
</div>
</div>
</div>
<div class="radio">
<label for="item_531"><input id="item_531" name="control_111" type=
"radio" value="112:531"> Refused</label>
</div>
</fieldset>
</body>
</html>
Hide all the DIVs that are next to radios, then show the one next to the selected radio.
$(":radio").next("div").hide();
$(this).next("div").show();
If you give each of the hidden div's the same class name, you can just hide them all before you show the new one:
$('.hidden-divs').not(newGroupName).hide();
$(newGroupName).show();

Jquery get value of text box next to a radio button

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.

Categories