How to do a Select All checkbox in html? - javascript

I have a html form, which has lots of checkboxes, and there is a Select All box on top, how to make the Select All box auto select all the checkboxes below according to the Select All box choice ?
I didn't want to show the code, because it's nasty looking, I'm debugging an old app, but since you asked, here it is :
<script language="javascript">
function selectAll2(value) {
var elem = document.forms[1].getElementsByTagName("select");
var count = ${questionCount};
for(var i = 1; i <= count; i++) {
if(i != 23 || (i==23 && ${w.carrier.stateOfDomicile ne 'FL'})) {
elem[i].value = value;
showNoShowQuestionaire(i,'Y','N',value);
}
}
}
</script>
<!-- Question # ${n} -->
<tr>
<td class="${labelClass}" align="right" valign="top" width=26%>
${n}.
</td>
<td class="${labelClass}" align="left">
${q}
</td>
<c:choose>
<c:when test="${not_applicable eq 'Y'}">
<td valign="top">
<div id="QT_${n}">
<html:select disabled="${disabled}" property="answers" styleClass="display: none;" value="${s}">
<html:option value="Y">Yes</html:option>
</html:select>
</div>
<script language="javascript">
document.getElementById("QT_${n}").style.display = 'none';
</script>
</td>
</c:when>
<c:otherwise>
<td valign="top">
<html:select disabled="${disabled}" property="answers" styleClass="processSelect" value="${s}" onchange="showNoShowQuestionaire('${n}','${yes_exp}','${no_exp}',this.value);">
<html:option value="">--</html:option>
<html:option value="N">No</html:option>
<html:option value="Y">Yes</html:option>
</html:select>
</td>
</c:otherwise>
</c:choose>
</tr>
From the above code, I got an error message for firefox and Chrome, it says : elem[i] undefined. It works fine in IE.
Since my app needs to work in all browsers, is there a solution that works for all browsers ?

First, they are not checkboxes, they are select elements. Well you can use javascript (jquery).
$('.yesToAll').change(function(){
if ($( "select option:selected" ).text() == 'Y') {
//add attr selected to all other selects Yes options
}
});

I found the answer, I used the following code to fix the problem :
function selectAll2(value) {
var elements = document.forms[1].elements;
for (i=0;i<elements.length;i++) if (elements[i].tagName == 'SELECT') elements[i].value = value;
var count = ${questionCount};
for(var i = 1; i <= count; i++) if(i != 23 || (i==23 && ${w.carrier.stateOfDomicile ne 'FL'})) showNoShowQuestionaire(i,'Y','N',value);
}

Related

Hide asterisk only for one field but show up for other fields

I have a text field and a dropdown field shown below
When I select any value from the dropdown field called 'REASONS', hide the asterisk of VEHICLE_NO field , I'm doing the below but doesnt work,
asteriskV ID is used for other fields to show/hide asterisks, my goal is to hide only for VEHICLE_NO and not for other fields when any of the value is selected from REASONS dropdown, how can i achieve this?
<table>
<tr><td><font id="asteriskV" color="red">*</font>VEHICLE TAG:</td>
<td>
<INPUT TYPE="text" id="VEHICLE_NO" class="MandatoryVTxt" NAME="VEHICLE_NO" size="25"></td></tr>
<tr>
<td><font color="red">*</font>1)Reasons:</td><td>
<select id="REASONS" name="REASONS" class="MandatoryDD" style="width:200px">
</select>
</td></tr>
</table>
$('#REASONS').change(function () {
var sel = $(this).val();
if (sel == '1117' || sel == '1116' || sel=='1120' || sel=='1121'){
$("#testingForm #VEHICLE_NO #asteriskV").hide();
}
});
Dear shwetha you can try this code.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
<table>
<tr>
<td><font id="asteriskV" color="red">*</font>VEHICLE TAG:</td>
<td>
<INPUT TYPE="text" id="VEHICLE_NO" class="MandatoryVTxt" NAME="VEHICLE_NO" size="25">
</td>
</tr>
<tr>
<td><font color="red">*</font>1)Reasons:</td>
<td>
<select id="REASONS" name="REASONS" class="MandatoryDD" style="width:200px">
<option>Select Reason</option>
<option value="1117">Reason 1</option>
<option value="1116">Reason 2</option>
</select>
</td>
</tr>
</table>
<script>
$(function () {
$('#REASONS').change(function () {
var sel = $(this).val();
if (sel == '1117' || sel == '1116' || sel == '1120' || sel == '1121') {
$("#asteriskV").hide();
}
});
});
</script>
https://jsfiddle.net/qaaf5vs9/
Add a class only to the font for VEHICLE_NO, and hide it using that class
<table>
<tr><td><font id="asteriskV" class="VEHICLE_NO" color="red">*</font>VEHICLE TAG:</td>
<td>
<INPUT TYPE="text" id="VEHICLE_NO" class="MandatoryVTxt" NAME="VEHICLE_NO" size="25"></td></tr>
<tr>
<td><font color="red">*</font>1)Reasons:</td><td>
<select id="REASONS" name="REASONS" class="MandatoryDD" style="width:200px">
</select>
</td></tr>
</table>
$('#REASONS').change(function () {
var sel = $(this).val();
if (sel == '1117' || sel == '1116' || sel=='1120' || sel=='1121'){
$(".VEHICLE_NO").hide();
}
});
I'm as confused as jquery, where is the tag with 3 IDs? I think you want ...
$('#REASONS').change(function () {
var sel = $(this).val();
if (sel == '1117' || sel == '1116' || sel=='1120' || sel=='1121'){
$("#asteriskV").hide();
}
});
and for select not change ...
$('#REASONS').focus(function() {
var sel = $(this).val();
if (sel == '1117' || sel == '1116' || sel=='1120' || sel=='1121'){
$("#asteriskV").hide();
}
});
If you want to hide multible elements I suggest using a class for all elements and $(".allAsterisk").hide();

Autocomplete an Input based on another Input with Percentages

first of all, please excuse me if I'm missing any info or I'm not being clear, I'm very new at this, still getting the hang of it.
I have the following form:
Form
I need the two % input fields to autocomplete so the sum is 100%. If input one is 90%, input 2 should autocomplete to 10% and vice-versa.
This is the HTML:
<!-- Tabla - - - - - - - -->
<div id="distDosFondos" class="table-responsive cambioDist">
<p>Selecciona fondos y porcentajes a distribuir:</p>
<!--table-responsive-->
<table class="table">
<thead>
<tr>
<th>Fondo</th>
<th>%</th>
</tr>
</thead>
<tbody>
<!-- Fila Cambio y Distribución de Fondos -->
<tr>
<td>
<div class="inputForm">
<select class="chosen" id="fondos1" name="fondos1">
<option value="">Fondo</option>
</select>
</div>
</td>
<td>
<div class="inputForm">
<input id="porcentage1" name="porcentage" type="text" class="form-control porcentage porcentaje1">
</div>
</td>
</tr>
<!-- //Fila Cambio y Distribución de Fondos -->
<!-- Fila Cambio y Distribución de Fondos -->
<tr>
<td>
<div class="inputForm">
<select class="chosen" id="fondos2" name="fondos2">
<option value="">Fondo</option>
</select>
</div>
</td>
<td>
<input id="porcentage2" name="porcentage" type="text" class="form-control porcentage porcentaje2">
</td>
</tr>
<!-- //Fila Cambio y Distribución de Fondos -->
</tbody>
</table>
</div>
<!-- Tabla - - - - - - - -->
There are a number of ways that you could approach this, but this is a pretty simple solution.
First, set up a handler for the input event of your two inputs
$("[name='porcentage']").on("input", function() {
...
});
Now, inside of this, you'll be handling changing the other input. First, let's make sure the percentage can't be over 100 and can't be below 0.
if($(this).val() > 100)
$(this).val(100);
else if($(this).val() < 0)
$(this).val(0);
Next, you need to get the other input, the one you want to change.
var otherInput = $(this).attr("id") == "porcentage1" ? $("#porcentage2") : $("#porcentage1");
Finally, set the other input's value to make the two add up to 100.
$(otherInput).val(100 - $(this).val());
Full code:
$("[name='porcentage']").on("input", function() {
if($(this).val() > 100)
$(this).val(100);
else if($(this).val() < 0)
$(this).val(0);
var otherInput = $(this).attr("id") == "porcentage1" ? $("#porcentage2") : $("#porcentage1");
$(otherInput).val(100 - $(this).val());
});
Fiddle
One possibility is to use the jQuery library:
$('#porcentage1, #porcentage2').on('input', function (event) {
var inputValue = parseInt($(this).val());
if (inputValue >= 0 && inputValue <= 100) { //ensure number is between 0 and 100
var otherValue = 100 - inputValue;
if (this.id === 'porcentage1') { //determines which input element was filled
$('#porcentage2').val(otherValue);
} else {
$('#porcentage1').val(otherValue);
}
}
})
You may have to use other validations/checks to make sure that the user is actually inputting a number, etc.
Without jQuery:
// attach a bunch of events to both inputs to handle any kind of change
['change', 'keyup', 'paste'].forEach(function(event) {
// .bind here essentially serves to pass reference of the current updated input, and the other input wich will be updated
porcentage1.addEventListener(event, onPercentageChange.bind(null, porcentage1, porcentage2));
porcentage2.addEventListener(event, onPercentageChange.bind(null, porcentage2, porcentage1));
});
function onPercentageChange(updatedInput, otherInput) {
var updatedValue = parseInt(updatedInput.value) || 0;
otherInput.value = 100 - updatedValue;
}
https://jsfiddle.net/tb7a7joc/
works IE9+

Formatting currency and percentage in input field

I was only able to insert a "$" sign in a3. I also need to insert the "$" sign for a1 but when I insert format for a1 field in like this
$('#a3').val(format($('#a1').val(format) * $('#a2').val()));
I get an error. What is the best way to do this?
HTML
<table class="table">
<tbody>
<tr>
<td>You</td>
<td class="light-gray">Example</td>
</tr>
<tr>
<td width="20%">a1
<input type="textbox" class="form-control" id="a1" name="a1" />
</td>
<td width="20%" class="light-gray">$30,000</td>
</tr>
<tr>
<td>a2
<input type="text" class="form-control" id="a2" name="a2" />
</td>
<td class="light-gray">90%</td>
</tr>
<tr>
<td>a3
<input type="text" class="form-control" id="a3" name="a3" data-cell="a3" />
</td>
<td class="light-gray">$27,000</td>
</tr>
<tr class="heading">
<th colspan="2"> </th>
</tr>
</table>
jQuery
$(document).ready(function () {
var format = function (num) {
var str = num.toString().replace("$", ""),
parts = false,
output = [],
i = 1,
formatted = null;
if (str.indexOf(".") > 0) {
parts = str.split(".");
str = parts[0];
}
str = str.split("").reverse();
for (var j = 0, len = str.length; j < len; j++) {
if (str[j] != ",") {
output.push(str[j]);
if (i % 3 == 0 && j < (len - 1)) {
output.push(",");
}
i++;
}
}
formatted = output.reverse().join("");
return ("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};
$("#a1,#a2").keyup(function (e) {
$('#a3').val(format($('#a1').val() * $('#a2').val()));
});
});
JSFiddle Examples
Your problem is that you assume the values inside the inputs to be numbers. Since you format those with non-digit-characters they are not (and can not be casted to a number).
$('#a1').val() * $('#a2').val()
Since the values you are multiplying are no numbers an error is thrown.
To be able to multiply those strings (or to be exact the value they are representing) you need to unformat your strings before you can cast those to numbers and do your calculation!
You'll find an working example at https://jsfiddle.net/hn669das/18/.
By the way: Better use the change-event for formatting instead of the keyUp-event since the user won't be able to write into the input undisturbed when the input is manipulated while the user intends to write to it. The change-event will trigger when the input looses its focus and so won't disturb the user.
I hope that helps you!

Is using <div> inside a <table> valid? Select all option inside a table row

I've got some trouble building a select all checkbox inside a table. Originally the table has several rows and the first checkbox should be used to select all options.
I built a small example, but still could not figure out my mistake.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "httpd://www.w3.org/TR/html4/loose.dtd">
<html><head>
<script language="JavaScript">
function allClicked(clickedId)
{
var divId = "div-" + clickedId.substring(4);
var child = document.getElementById( divId );
var tdChildren = child.getElementsByTagName("td"); // appears to be empty
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
for (var i=0; i<tdChildren.length; ++i) {
tdChildren[i].elements.checked = setTo;
}
}
</script>
</head><body>
<div id="div-a">
<table>
<tr>
<td><input id="all-AP" onClick="javascript:allClicked('all-AP')" type="checkbox">Select All</td>
<div id="div-AP">
<td><input id="AP_A1K" checked="checked" type="checkbox"></td>
<td><input id="AP_A2K" checked="checked" type="checkbox"></td>
<td><input id="AP_A3K" type="checkbox"></td>
</div>
</tr>
</table>
</div>
</body></html>
During debugging the div with id="all-AP" is retrieved but appears to be empty. I expected it to have three td-elements in it.
Is a div separating the td's valid?
What should I fix?
You don't need a div either to perform a "select all".
Have a look on this fiddle.
First :
<body>
<table id="checkboxtable">
<tr>
<td>
<input onClick="javascript:allClicked()" type="checkbox" />Select All</td>
<td>
<input id="AP_A1K" checked="checked" type="checkbox" />
</td>
<td>
<input id="AP_A2K" checked="checked" type="checkbox" />
</td>
<td>
<input id="AP_A3K" type="checkbox" />
</td>
</tr>
</table>
</body>
Each input has its own id (you CANNOT affect one id to more than one element).
Then allClicked() :
function allClicked() {
var checkBoxTable = document.getElementById("checkboxtable");
var checkBoxes = checkBoxTable.getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; ++i) {
// if (/^AP_.*/.test(checkBoxes[i].id)) // getting them by regular expression
if (checkBoxes[i].getAttribute("type") == "checkbox") // getting them by type
checkBoxes[i].checked = true;
}
}
The code retrieve the table element by its id. Then it gets all its <input type="checkbox"> elements. Depending on your needs, you can also catch them by their id with a [Regexp][2].test() method (here it catches element whose id begins with "AP_").
This is just one example implementation. You can achieve it in many ways.
No it isn't. You can either put another table inside the second cell or have some javascript to hide/display the other cells.
My final result and working example looks like this:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8" />
<title>Testpage</title>
<script type="text/javascript">
function allClicked(clickedId)
{
var divId = "div-" + clickedId.substring(4);
var child = document.getElementById( divId );
var children = child.getElementsByClassName("AP");
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
for (var i=0; i<children.length; ++i) {
children[i].checked = setTo;
}
}
</script>
</head><body>
<table>
<tr id="div-AP">
<td><input id="all-AP" onClick="javascript:allClicked('all-AP')" type="checkbox">Select All</td>
<td><input class="AP" checked="checked" type="checkbox"></td>
<td><input class="AP" checked="checked" type="checkbox"></td>
<td><input class="AP" type="checkbox"></td>
</tr>
</table>
</body></html>
I used a validator to check the document. (http://validator.w3.org/check)
Using a class feature allows me to place the select all inside the same row.
The div doesn't work across table elements. Try this for your allClicked function instead:
function allClicked(clickedId)
{
var prefix = clickedId.substring(4);
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
var checkboxes = document.getElementsByTagName("input");
for (var i=0; i<checkboxes.length; ++i) {
var boxid = checkboxes[i].id;
if (boxid.indexOf(prefix)===0) {
checkboxes[i].checked = setTo;
}
}
}
This assumes your grouping of checkboxes have a common prefix. Just remove your div lines from the table entirely and rely on the id prefix of the input fields.

Check Checkbox from the Same Row as an Input Field

I want to check the checkbox next to each html row if the select dropdown in the same row has something selected. Here is my html code and script. Can someone please point out what's wrong?
<tr>
<td>Sohail Abbasi</td>
<td>N&S</td>
<td>1</td>
<td>2013-01-03</td>
<td>Thursday</td>
<td>09:21</td>
<td></td>
<td>
<select class="form-control" name="duty_status[3]">
<option value="" selected="selected">Select...</option>
<option value="2">Short Leave</option><option value="5">OD</option>
</select>
</td>
<td><input class="form-control" name="user_comments[3]" type="text"></td>
<td>
<input name="submit[]" type="checkbox" value="3">
</td>
</tr>
Javascript:
$('#SelectFilled').click(function($e)
{
var elements=$('select[name^=duty_status]');
var checkboxes=new Array();
for (var i=0; i<elements.length; i++) {
if(elements[i].value)
{
var parent=elements[i].parentNode.parentNode;
checkboxes[checkboxes.length]=parent.lastChild.firstChild;
}
}
for (var j=0; j<checkboxes.length; j++) {
checkboxes[j].checked=true;
}
});
You can simplfy your traversal code and make it far easier to read by using jQuery methods:
$('select[name^=duty_status]').each(function(){
if( this.value === VALUE_I_WANT ){ /* not sure where this value comes from */
$(this).closest('tr').find(':checkbox').prop('checked', true);
}
});
This code is based on the existing click handler triggering it. The goals in question are not very clear
You would have to use something like this:
$(function() {
$('td > select').on('change', function() {
var chk = $(this).closest('tr').find(':checkbox');
chk.prop('checked', this.selectedIndex !== 0 );
})
.change();
});
JSFIDDLE DEMO
Below code should works:
$('select[name^=duty_status]').on('change', function(){
if($(this).val() != ""){ //better put some value on the first option..
$(this).parents("tr").find(":checkbox").prop('checked', true);
}else{
$(this).parents("tr").find(":checkbox").prop('checked', false);
}
});

Categories