Checkbox click event - javascript

I have a group of checkboxes inside a table where I want to change the value of a different column in the row when the checkbox is checked. I have researched for a solution but nothing I have found seems to solve my problem. I realize that my stumbling block is my unfamiliarity with jquery so any suggestions would help. Ultimately I wish to total the columns where the change has occurred to get a total. So if an answer included ideas about that as well I would not complain. Thanks as always, you are a great group.
HTML
<tr>
<td><input name="amputeeGolfer" type="checkbox" id="amputeeGolfer" value="amputee" onchange="changeFee"/>
<label for="amputeeGolfer">Amputee Golfer</label></td>
<td align="left"><label for="amputeeFee">$50.00</label></td>
<td></td>
<td><input name="amputeeFee" type="number" id="amputeeFee" class="tblRight" size="10" value="0.00"/></td>
</tr>
jquery
<script>
function changeFee(val) {
$('#amputeeFee').val(), "$50.00";
}
</script>

Fully functioning snippet. No jQuery required!
When the onchange event fires, it checks whether the checkbox was just checked or unchecked, and toggles the price accordingly. It can even be combined with all sorts of other checkboxes.
function togglePrice(element,price){
if(element.checked){
document.getElementById("amputeeFee").value = parseInt(document.getElementById("amputeeFee").value) + price;
}else{
document.getElementById("amputeeFee").value = parseInt(document.getElementById("amputeeFee").value) - price;
}
}
<tr>
<td><input name="amputeeGolfer" type="checkbox" id="amputeeGolfer" value="amputee" onchange="togglePrice(this,50);"/>
<label for="amputeeGolfer">Amputee Golfer</label></td>
<td align="left"><label for="amputeeFee">$50.00</label></td>
<td></td>
<td><input name="amputeeFee" type="number" id="amputeeFee" class="tblRight" size="10" value="0"/></td>
</tr>
It works perfectly and you can even set how much the checkbox adds to the cost!

You can get closest tr closest('tr') to assure input in same row with check box and find input with name find("input[name='amputeeFee']") and change value for it.
function changeFee(val) {
var amputeeFee = $(val).closest('tr').find("input[name='amputeeFee']");
if($(val).prop("checked")){
amputeeFee.val(50.00);
}
else{
amputeeFee.val(0);
}
}
function changeFee(val) {
var amputeeFee = $(val).closest('tr').find("input[name='amputeeFee']");
//console.log(amp.length);
if($(val).prop("checked")){
amputeeFee.val(50.00);
}
else{
amputeeFee.val(0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input name="amputeeGolfer" type="checkbox" id="amputeeGolfer" value="amputee" onchange="changeFee(this)"/>
<label for="amputeeGolfer">Amputee Golfer</label></td>
<td align="left"><label for="amputeeFee">$50.00</label></td>
<td></td>
<td><input name="amputeeFee" type="number" id="amputeeFee" class="tblRight" size="10" value="0.00"/></td>
</tr>
</table>

To call a JavaScript function like changeFee(val) in an HTML's element event, the funciton has to be called as the same in the script. As all functions in an HTML' event: <element onclick="myFunction()">, and not <element onclick="myFunction"> beacuse it doesn't reconize it's a function in JavaScript.
Then the code will be:
<tr>
<td><input name="amputeeGolfer" type="checkbox" id="amputeeGolfer" value="amputee" onchange="changeFee(this.value)"/>
<label for="amputeeGolfer">Amputee Golfer</label></td>
<td align="left"><label for="amputeeFee">$50.00</label></td>
<td></td>
<td><input name="amputeeFee" type="number" id="amputeeFee" class="tblRight" size="10" value="0.00"/></td>

Related

Value not displaying in correct input

I have a 2 row table with input fields that does a calculation when I focusout on the first input. The problem I am experiencing is when I focusout on the second row, my new value is displayed in the first row corresponding input. I'm not sure why this is happening. I would greatly appreciate your help.
My expectation is when I enter a value in a row input (Cost) and focusout the new value should be set in the same row but in the input (New Cost).
function Calculate(element) {
var dollar = 216.98;
var id = element.id;
var oldcost = $(element).val();
var newcost = oldcost * dollar;
$("#" + id).closest("tr").find("td #new").val(newcost);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
</table>
There's several issues here. Firstly you're repeating the same id attribute which is invalid; they must be unique. I'd suggest using a class instead. Secondly, there's is no new attribute. I presume that's a typo and should be an id, but again see my first point.
Next, the function you defined is named Calculate() yet the call is to Caluculate().
Then you should also be using unobtrusive event handlers as on* event attributes are very outdated and should be avoided where possible. As you've already included jQuery in the page you can use the on() method. The input event would seem to be more applicable to your usage as well, especially given it also catches the up/down arrow usage on the number control, although you can change this to blur if preferred.
Finally, it's a simply a matter of amending your DOM traversal logic to work with the new classes, like this:
var dollar = 216.98;
$('.old').on('input', function() {
var oldcost = $(this).val();
var newcost = oldcost * dollar;
$(this).closest("tr").find(".new").val(newcost);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" class="old" /></td>
<td><input type="number" class="new" /></td>
</tr>
<tr>
<td><input type="number" class="old" /></td>
<td><input type="number" class="new" /></td>
</tr>
</table>
Your use of id's is kind of messed up. First of all be sure to use an id once in the entire HTML file.
For your usecase better use classes.
Also be sure to type your function names correct ;)
function Calculate(element) {
var dollar = 216.98;
var parent = $(element).closest('tr');
var oldcost = $(element).val();
var newcost = oldcost * dollar;
parent.find(".new").val(newcost.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
</table>
They have the same ID. You need to make the ID different
Firstly, there is a a typo.Change caluculate to calculate
There must not be the same id two elemnts have the same id.You could change the id of the first to old-1 or something different

Find Checkbox in HTML Table Using JQuery Find Method

I have a HTML table which has the following structure:
<table id="myTable">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
When the user clicks the 'edit' link, a Javascript function is called (see below). In this function I need to get the data from the table, i.e., FullName and whether or not isActive has been checked.
$("#namedTutors").on('click', '.editTutor', function () {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
});
I can get the FullName easy enough, but I'm having difficulties retrieving the data to see if isActive has been checked/ticked or not.
Could someone please help.
Thanks.
You could select the ckeckbox input by name [name=isActive] then use the .is(':checked') to check whether the ckeckbox is checked or not, like:
$("#namedTutors").on('click', '.editTutor', function() {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
var isActive = tr.find("input[name=isActive]").is(':checked');
console.log( isActive );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="namedTutors">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
if(tr.find('input[name="isActive"]:checked').length) {
console.log('it is checked');
}

Change readonly status of field if radio button selected, no jquery

I have a form, I want to initially have some normal fields and some readonly fields. Then a radio button with two options, if it's the default option nothing changes, if they select the second then the readonly fields become editable.
I need to do this without jquery.
Here's the form
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" checked> Fruit<br>
<input type="radio" name="individual" value="0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" readonly></td>
</tr>
</table>
Please assist
First, add the IDs in your HTML.
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" id="individual1" checked> Fruit<br>
<input type="radio" name="individual" value="0" id="individual0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" id="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" id="package_unit" readonly></td>
</tr>
</table>
Then, get the elements with getElementById, and add EventListeners in your JS.
const individual1 = document.getElementById("individual1"),
individual0 = document.getElementById("individual0"),
packing_name = document.getElementById("packing_name"),
package_unit = document.getElementById("package_unit");
individual1.addEventListener("change", function(){
packing_name.value = '';
package_unit.value = '';
packing_name.readOnly = true;
package_unit.readOnly = true;
});
individual0.addEventListener("change", function(){
packing_name.readOnly = false;
package_unit.readOnly = false;
});
CodePen: https://codepen.io/anon/pen/vVyVGx
You can remove readonly for an element with the following two options,
Option 1:
document.getElementById('elementId').removeAttribute('readonly');
Option 2:
document.getElementById('elementId').readOnly = false;
Use any of the above code on change of the radio button.
For triggering the click event use the attribute onclick, add the below as an attribute to the input element.
onclick="callBack()"
And inside your JS,
function callBack() {
document.querySelector('input[name="individual"]:checked').value; // get the value and check it with an if condition.
}
Use document.querySelector to get selected radio value based on the value you can disable or enable any I/p field dynamically in JavaScript
For Getting Radio value
document.getElementById(“input[id=‘eleid’]:checked”).value
for enabling / disabling
document.getElementById(elem).disabled = true/false

Creating a new form on click of link

How could I make it so the code below retains what it does now but does the following:
a) When the add menu link/button is clicked it shows the bookingName menu div and the same item and qty boxes
b) When the above happens it also needs the abilty to add more rows to that particular just added menu
Demo of current work
jQuery:
$(document).ready(function () {
$('<tr/>', {
'class': 'menuDetails',
html: getMenuHTMLDetails()
}).appendTo('#addMoreItemsButton');
$('#addItem').click(function () {
$('<tr/>', {
html: getMenuHTMLDetails()
}).hide().appendTo('.menuDetailsBlock').slideDown('slow');
});
})
function getMenuHTMLDetails() {
var $clone = $('.menuDetails').clone();
$clone.find('[name="item[]"]')[0].name = "item";
$clone.find('[name="qty[]"]')[0].name = "qty";
return $clone.html();
}
HTML:
<div class="formBlock">
<p><span class="bookingName">Menu<span class="required">*</span></span><span class="bookingInput"><input type="text" name="menu"/></span></p>
</div>
<div class="formBlock">
<table class="menuDetailsBlock">
<tr>
<td><span class="bookingName">Item<span class="required">*</span></span></td>
<td><span class="bookingName">QTY<span class="required">*</span></td>
</tr>
<tr class="menuDetails">
<td><span class="bookingInput"><input type="text" name="item[]" /></td>
<td><input type="number" name="qty[]" style="width: 50px"></span></td>
</tr>
<tr>
<td><span class="bookingInput"><input type="text" name="item[]" /></td>
<td><input type="number" name="qty[]" style="width: 50px"></span></td>
</tr>
<tr>
<td><span class="bookingInput"><input type="text" name="item[]" /></td>
<td><input type="number" name="qty[]" style="width: 50px"></span></td>
</tr>
</table>
<div class="appendMoreItems"></div>
</div>
<div class="formBlock">
Add Item Add Menu
</div>
</div>
The first thing you should be aware of is that your html is invalid. You can't have something like:
<td><span>...</td><td>...</span></td>
Because this form needs the ability to be duplicated, you need to remove all IDs (and ideally change to them classes). e.g. id="addMenu" -> class="addMenu".
Instead of using your standard click handler, you should use delegates to handle any clicks within your outer container - read http://api.jquery.com/on/.
As for your duplication problem, place a template of your elements to be duplicated inside a script tag with an id you can reference and clone (with .html()), or, even better, consider looking into http://handlebarsjs.com/ or http://akdubya.github.io/dustjs/.

using js functions within js functions in html.erb

ok should be an easy one for everyone,...
i am calling a javascript function in the tag of a button using inclick. Im trying to get that function to have three different parameters. The function then submits three different times, which should end up being three different records in a ruby table.
But i cant see why this doesnt work...
<script>
function submiteffort( elem )
{
// Elem 1
$("#effort_hours").val( $( elem ).val() );
$("#task_id").val( elem.id );
$("#effort_form").submit();
return true;
}
function medium( leave, toil, sick)
{
var dave = submiteffort(document.getElementsByName(leave));
if(dave == true){
var dave2 = submiteffort(document.getElementsByName(toil));
}
if(dave2 == true){
submiteffort(document.getElementsByName(sick));
}
}
</script>
<div class="startleft">
<table>
<tr>
<td>Leave</td>
<td><input class="dayinput" type="text" name="Leave" placeholder="0" ></td>
</t>
<tr>
<td>TOIL</td>
<td><input class="dayinput" type="text" name="TOIL" placeholder="0"></td>
</tr>
<tr>
<td>Sick</td>
<td><input class="dayinput" type="text" name="Sick" placeholder="0"></td>
</tr>
<tr>
<td>Total</td>
<td><input id="total" class="total_low" type="text" value="0" disabled="" name="Dave">
</tr>
<tr>
<td></td>
<td><button onclick="medium('Leave','TOIL','Sick')">Commit</button></td>
</tr>
</table>
</div>
For some reason this only submits 1 record into the table and i cant figure out why.
Well if you submit the form, the page refreshes, and the other 2 function calls don't execute. You'd have to use AJAX to send data to the backend in 3 separate function calls.

Categories

Resources