How to checkbox enable/disable with Struts 2 - javascript

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>

Related

Selecting a default radio input on page load 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/

How to remove a div containing a checkbox with a specific id?

I have different checkboxes generated dynamically.
Each checkboxes are contained within a div.
I would like to do the following action with jquery:
If a checkbox has an id="aucune", then remove its container (the div containing the checkbox with the id="aucune") from the html page.
I tried the following code:
// wait for DOM to be ready
$(document).ready(function() {
var empty = $("input:checkbox[id=aucune]");
if (empty == true) {
$(this).parent().remove();
}
});
Here is a the very simplified html:
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Here is my codepen:
I am quite new to code, I apologize for my silly simple question.
You can directly select the id with jQuery and remove the parent.
$('#acune').parent().remove();
Or if you know the class of the parent element
$('#acune').parent('.wrapper-checkbox').remove();
You are wrongly referencing this. It should be this way:
Replace this with empty.
Replace the boolean check with count.
Note: You can also use $("#aucune") instead of the selector $("input:checkbox[id=aucune]").
// wait for DOM to be ready
$(document).ready(function() {
// Or here you can also use $("#aucune").
var empty = $("input:checkbox[id=aucune]");
// Check if it is found.
if (empty.length > 0) {
// Remove the parent.
empty.parent().remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Boom! And the checkbox is gone! :)
You can directly use the aucune id selector in your JQuery and then get the closest div with class wrapper-checkbox to remove it:
$(document).ready(function() {
var empty = $("#aucune");
if (empty.length !== 0){
$(empty).closest('.wrapper-checkbox').remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="xxx" name="xxx" date-name="xxx">
<label for="xxx">xxx</label>
</div>
<div class="wrapper-checkbox">
<input type="checkbox" class="outsider" id="aucune" name="aucune" date-name="aucune">
<label for="aucune">aucune</label>
</div>
Try to do this..
$(document).ready(function() {
var checkbox = $("input:checkbox[id=aucune]");
if (checkbox.length > 0) {
checkbox.parent().remove();
}
});

Javascript set value of class & hidden input in nested divs

I have a span class "checkbox" and an attribute "value" associated with a hidden input field, both of which are contained within nested divs.
By default the checkbox is unchecked but I would like to change the span class to "checkbox active" and the input value to "1" so that it is checked and rendered to reflect that change.
This code is generated by a Wordpress plugin and there are no ids.
What's the best method to set these two attributes?
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="hidden" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
As per your requirement.Why dont you set like this ??
$(document).ready(myfunc);
function myfunc()
{
$('.checkbox').addClass('checked');
$('.true_false').val('1');
}
if($('.checkbox').hasClass('checked'))
{
alert($('.true_false').val());
}
Click on the demo below to see that value 1 is getting set and checked class is getting set.
You can do this on click of a button or checking a checkbox.
Click Here
Try this:
Also for demo purpose, I have kept input as text instead of hidden.
Fiddle
(function(){
$(".checkbox").on("click",function(){
$(this).toggleClass("checked");
var val = 0;
val = $(this).hasClass("checked")?1:0;
$(this).parent().find(".true_false").val(val);
});
})()
.checked{
background: blue!important;
}
.checkbox{
width:20px;
background:#eee;
padding:5px;
border:1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="text" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
<div class="field field-news_item" data-type="true_false" data-name="news_item" data-validator="">
<div class="cfs_true_false ready">
<span class="checkbox"></span>
<span>Is this a news item?</span>
<input type="checkbox" id="checkbox" />
<input type="text" name="cfs[input][6][value]" class="true_false" value="0">
</div>
</div>
$(document).ready(function(){
$('#checkbox').change(function(){
var checkboxValue = $(this).is(':checked');
if(checkboxValue == true){
$(".true_false").val('1');
alert('1');
}else{
$(".true_false").val('0');
alert('0');
}
});
});

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>

using a function to write the input of a text field to the document when all forms are submitted

<script src="jquery.js"></script>
<script>
function saveScore (score) {
score=document.input.$('.inputright').value
$('submit').click(function(event) {
$('<div>')
.append(score)
.appendTo('.wincolumn');
});
}
</script>
</head>
<body>
<form name= "myform">
<input class="inputright" type="text" value="Team?" onfocus='value=""' onblur="value='Team?'" onclick="saveScore(score)">
</form>
<div id="bottomcontainer">
<div class="personalcolumns" id="niccolumn">
<div class="playername"> Nic Meiring </div>
<div class="wincolumn WLRcolumn"> </div>
<div class="losscolumn WLRcolumn"> </div>
<div class="resultcolumn WLRcolumn"> </div>
</div>
</body>
I want to take the input in the text field called Team? and write it to the column with the class .teamcolumn
2 main problems(I think)
allowing the text field to have a default value of "Team?" but then switching its value to the input when the onclick method is called (and therefore the function is called)
how to best write to the document from within that function. document.writeln() maybe?
Thanks
I created a demo for you at jsFiddle. The input field defaults to "Team?" if no text is entered, however if text is entered then it is not changed. If the input field loses focus and it is empty, it returns to "Team?". Once the field is blurred the value (if not "Team?") is then appended to the .wincolumn div. I removed your savescore function and all your inline event handlers.
jQuery:
$('input[name="foo"]').change(function() {
$('div.wincolumn').html($(this).val());
}).focus(function() {
if ($(this).val() == 'Team?') {
$(this).val('');
}
}).blur(function() {
if (!$(this).val()) {
$(this).val('Team?');
}
})
HTML:
<form name= "myform">
<input name="foo" class="inputright" type="text" value="Team?">
</form>
<div id="bottomcontainer">
<div class="personalcolumns" id="niccolumn">
<div class="playername"> Nic Meiring </div>
<div class="wincolumn WLRcolumn"> </div>
<div class="losscolumn WLRcolumn"> </div>
<div class="resultcolumn WLRcolumn"> </div>
</div>
</div>

Categories