show/hide div based on radio button checked - javascript

I am trying to show/hide text fields based on checked radio buttons checked. Here is my code; it works fine if I don't use table tags, when using table tags, Javascript doesn't work
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked) {
document.getElementById(id + '_form_fields').style.display = 'block';
document.getElementById(other_id + '_form_fields').style.display = 'none';
} else {
document.getElementById(id + '_form_fields').style.display = 'none';
document.getElementById(other_id + '_form_fields').style.display = 'block';
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onchange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');">
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td><tr>
<!-- If Individual Form is checked -->
<div id="personal_form_fields">
<tr><td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr><td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
</div>
<!-- If Corporation Form is checked -->
<div id="corporate_form_fields" style="display: none;">
<tr><td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</div>
</table>

What putvande might mean by "strange markup" is that your <div id="personal_form_fields"> is in the table, with its parent being a table tag. That's not right. The tr should contain the td, which contains the div, not the other way around.
If you're trying to change visibility, this syntax error could be the problem.

Simply add a class to the TR of each group and show / hide the class...
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked)
{
class_display(id + '_form_fields','block');
class_display(other_id + '_form_fields','none');
} else {
class_display(id + '_form_fields','none');
class_display(other_id + '_form_fields','block');
}
}
function class_display(tr_class,display)
{
var tr_ele = document.getElementsByClassName(tr_class);
for (var i = 0; i < tr_ele.length; ++i) {
var item = tr_ele[i];
item.style.display = display;
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onChange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');" checked>
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td>
<tr>
<!-- If Individual Form is checked -->
<tr class="personal_form_fields">
<td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr class="personal_form_fields">
<td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
<!-- If Corporation Form is checked -->
<tr class="corporate_form_fields" style="display: none;">
<td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</table>

Related

how can i get table of values exist in a TD of a table use jquery?

i want when i check checkbox in table get array values check (NAME, FIRST NAME, SALAIRENET) in example below it gives me just SALAIRENET and give NaN a name for the line check, please help me.
he is my table
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
he is my code jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = parseInt($(currentHtml1)[0].innerText);
console.log(result);
console.log(result1);
}
});
});
</script>
It might be helpful to create functions to break up the work. Also you can use parseInt() but it must receive a String that represents an Integer, so "1000" versus "One Thousand".
Consider the following:
$(function() {
function checkToggleAll(c, v) {
$(".checkbox", c).each(function(i, el) {
$(el).prop("checked", v);
});
}
function checkAll(c) {
if ($(".checkbox:checked", c).length == $(".checkbox", c).length) {
$("#check_all").prop("checked", true);
} else {
$("#check_all").prop("checked", false);
}
}
function gatherData(c) {
var rows = {}
$(".checkbox:checked", c).each(function(i, el) {
var row = $(el).parent().parent();
rows[row.attr("id")] = {
Name: $(".first-name", row).text().trim(),
SurName: $(".sur-name", row).text().trim(),
SalaireValue: parseInt($(".salaireValue", row).text().trim())
};
});
return rows;
}
$("#check_all").change(function() {
checkToggleAll($("tbody"), $(this).prop("checked"));
console.log(gatherData($(".table tbody")));
});
$("tbody .checkbox").on("change", function() {
checkAll($(".table tbody"));
console.log(gatherData($(".table tbody")));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<thead>
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
</thead>
<tbody>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1001</td>
<td class="name">Simpson, Homer</td>
<td class="salaireValue">60000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>1002</td>
<td class="name">Leonard, Lenny</td>
<td class="salaireValue">40000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_3">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="3"></td>
<td>3</td>
<td>1002</td>
<td class="name">Carlson, Carl</td>
<td class="salaireValue">55000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</tbody>
</table>
I assume that the table content might get updated dynamically, so I am using .on() just in case. You can use .change() if needed.
Hope that helps.
A few changes in your for loop will make it:
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
I've also separated the names into two spans in order to make it easy to select them.
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">123</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>2</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">456</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</table>

Get all the values of td columns from table where checkbox is checked

I have a table as below:
..
There have been multiple questions asked for getting the values but in this case I should always have a parent item name. Suppose If a user selected only one subitem in "Shirts", then I should be able to get all the values from the selected tr and with that I need parent item name also i.e "shirts" and if some one clicks on all the subitems of a parent item, then all the values of all tr are need to be in some sort of array object on click of a "Save" button. I am trying hard to do this. Any help would be really appreciated. Though I have attached the HTML but this HTML is being generated at run time.
HTML:
<table>
<tr>
<td> </td>
<td> </td>
<td>Name</td>
<td>Sub Item</td>
<td>User Input</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup1" class="cls1" onclick="checkUncheckAll(this);" />
</td>
<td>Shirts
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item1</td>
<td>SubItem1</td>
<td>
<input id="1datepicker" name="1datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item2</td>
<td>SubItem2</td>
<td>
<input id="2datepicker" name="2datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item3</td>
<td>SubItem3</td>
<td>
<input id="3datepicker" name="3datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup2" class="cls2" onclick="checkUncheckAll(this);" />
</td>
<td>Jeans
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item4</td>
<td>SubItem4</td>
<td>
<input id="4datepicker" name="4datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item5</td>
<td>SubItem5</td>
<td>
<input id="5datepicker" name="5datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item6</td>
<td>SubItem6</td>
<td>
<input id="6datepicker" name="6datepicker" type="text" /><script>
</script></td>
</tr>
</table>
Script code looks like below:
<script>
function checkUncheckAll(sender) {
var chkElements = document.getElementsByClassName(sender.className);
for (var i = 0; i < chkElements.length; i++) {
chkElements[i].checked = sender.checked;
}
}
function CheckCorrespondingHeader(sender) {
ControlLength = $("[name='" + sender.name + "']").length;
var countchecks = 0;
$("[name='" + sender.name + "']").each(function () {
if ($(this).prop('checked') == true) {
countchecks = countchecks + 1;
}
});
if (ControlLength == countchecks) {
$("#chk" + sender.name).attr('checked', 'checked');
}
else {
$("#chk" + sender.name).prop('checked', false);
}
}
function PickAllCheckedRows() {
}
</script>
As far as I can tell your code should work if you fix one issue. You are determining the number of sub rows that need to be checked to make the header row be checked using $("[name='" + sender.name + "']").length;. But unless I'm mistaken sender.name is never set. Of course if you set it this still won't work because your each function will include the header row. There are several solutions to this but I would recommend using a data attribute instead of the name attribute like so:
Markup:
<table>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 1 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 2 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group2" ... /></td>
</tr>
<tr>
<!-- row 3 -->
<td><input type="checkbox" data-in-group="Group2" ... /></td>
</tr>
</table>
Script:
function CheckCorrespondingHeader(sender) {
var group = $("[data-in-group='" + sender.data('headForGroup') + "']");
var groupSize = group.length;
var countchecks = 0;
group.each(function () {
if ($(this).prop('checked') === true) {
countchecks = countchecks + 1;
}
});
if (groupSize === countchecks) {
$(sender).attr('checked', 'checked');
} else {
$(sender).prop('checked', false);
}
}

how to assign names to new table columns cells dynamically

At the moment ,this code can create new columns dynamically.I would like to be able to give a unique name to all cells belonging to the mother column.NB:the mother column is the tallest of them all with three columns always.Any thing with less columns is a child.
SO all the cells and the contents in the first group must have a unique name identifer like say name="Bx_1name" to identify them from the next mother's contents(BX_2name);
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
</script>
Javascript is wellcome too.the functionality must not be changed.it must be just like this;
jsfiddle
Try this if it fits what you need.
JSFIDDLE
var counter =0;
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME['+counter+']" value="BX_NAME['+counter+']"/>';
counter++;
}
item.appendChild(td);
});
}
i used a global counter to increment each time a cell is made.
this is just a hint you can implement this as you want to achieve. First assign same class name for all your input fields
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text"/>
</td>
</tr>
</tbody>
</table>
then assign diffrent id's using jquery like following
<script type="text/javascript">
$(document).ready(function (event) {
var IDCount = 1;
$('.text').each(function () {
$(this).attr('id', IDCount);
IDCount++;
});
</script>
Hope this will help

How to navigate textboxes in between different tables using arrow keys?

I have the following code, it is working that is navigating between the textboxes, but the issue is it is navigating only within one table, but am having different tables in my page. How to make it work?
$('input[type="text"],textarea').keyup(function(e){
if(e.which==39 || e.which==13)
$(this).closest('td').next().find('input[type="text"],textarea').focus();
else if(e.which==37 || e.which==8)
$(this).closest('td').prev().find('input[type="text"],textarea').focus();
else if(e.which==40 || e.which==13)
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
else if(e.which==38 || e.which==8)
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
});
<form>
<table width="960" align="center" cellspacing="20" cellpadding="15" id="navigate">
<thead>
<th align="center"></th>
<th align="center"></th>
<th align="center"></th>
<th align="center"></th>
</thead>
<tbody>
<tr>
<td colspan="4" style="font-size:15px;"><b>ADVERTISING:</b></th>
</tr>
<tr>
<th></th>
<th align="center">DOMESTIC($)</th>
<th align="center">INTERNATIONAL($)</th>
<th align="center">NOTES</th>
</tr>
<tr>
<td class="spending_table_title" title="<?php echo $this->data[14]->content; ?>"><span style="text-transform: uppercase;"><?php echo $this->data[13]->content; ?></span></td>
<td ><input type="text" value="" name="actual_marketing_dom_print" id="actual_marketing_dom_print" size="30" style="height:20px; width:155px;" onChange="total_dom_advt();total_marketing_spending();format(this);"/> </td>
<td ><input type="text" value="" name="actual_marketing_intl_print" id="actual_marketing_intl_print" size="30" style="height:20px; width:155px; " onChange="total_intl_advt();total_marketing_spending();format(this);"/></td>
<td ><textarea name="actual_marketing_print_notes" id="actual_marketing_print_notes" style="height:32px; width:300px;" rows="3" cols="20" class ="notes"> </textarea></td>
</tr>
</tbody>
</table>
</div>
<br>
<br>
<div class="divgrid">
<table width="960" align="center" cellspacing="20" cellpadding="15" id="navigate">
<thead>
<th style="width:60%;"></th>
<th></th>
<th></th>
</thead>
<tbody>
<tr>
<td colspan="3" style="font-size:15px;font-weight:bold;">TOTAL PRESS AND PUBLIC RELATIONS (DOMESTIC AND INTERNATIONAL COMBINED):</td>
</tr>
<tr>
<th></th>
<th align="center">$</th>
<th align="center">NOTES</th>
</tr>
<tr>
<td class="spending_table_title" title="<?php echo $this->data[31]->content; ?>"><span style="text-transform: uppercase;"><?php echo $this->data[30]->content; ?></span></td>
<td ><input type="text" value="" name="actual_marketing_industry_relations" id="actual_marketing_industry_relations" size="30" style="height:20px; width:155px; " onChange="total_press_public();total_marketing_spending();format(this);"/></td>
<td ><textarea name="actual_marketing_industry_relations_notes" id="actual_marketing_industry_relations_notes" style="height:32px; width:300px;" rows="3" cols="20" class ="notes"> </textarea></td>
</tr>
</tbody>
</table>
</form>
in my code am having two tables, after completing the textboxes in one table am not table to navigate to next table textboxes, i was not known how to do this
Interesting question, and hopefully you will find this helpful.
What I'm doing here is to check if there is an input above or below to go to with if (t.length == 0), and if not, move to the corresponding cell in the next or previous table instead.
$(document).ready(function () {
$('input[type="text"],textarea').keyup(function (e) {
if (e.which == 39) {
$(this).closest('td').next().find('input[type="text"],textarea').focus();
} else if (e.which == 37) {
$(this).closest('td').prev().find('input[type="text"],textarea').focus();
} else if (e.which == 40) {
var t = $(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
if (t.length == 0) {
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) + 1) + ')').find('tbody tr td').parent().first().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
}
t.focus();
} else if (e.which == 38) {
var t = $(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
if (t.length == 0) {
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
}
t.focus();
}
});
});
http://jsfiddle.net/zxTfb/5/
Please note that right now, this only works on multiple tables on top of each other, not side by side. If you need them side by side, you could copy what I did for keys 40 and 38 and modify it to work for 39 and 37 as well.
Hope it helps.
Further explanation
Let's break down this line of code and look at inner workings:
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
First we find the table above the one we are currently in. This is done with the selector :eq() which selects an element, table in this case, by it's index. We select the table with our current tables index -1 to get the table above.
$(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')')
Now that we have the table above our current position, we find the last <tr> element that does contain a <td>, by first looking for all <td>, then move up to it's parent <tr> with .parent() and finally select the last one (bottom row) with .last().
.find('tbody tr td').parent().last()
Now we know which <tr> to look in, so we move ahead and look for the specific <td> by index, so that we end up in the right column, corresponding to the one we are currently in. This is similar to when we found the <table> by index at the top.
.find('td:eq(' + $(this).closest('td').index() + ')')
Finally, we now have our correct <td> element and now all that remains is to find our <input> or <textarea> that isn't readonly. We do this simply by selecting them like so
.find('input[type="text"]:not([readonly]),textarea');
And now we know where to move in the table above. Since we set t to this new element, all that remains is to move the focus there with t.focus().
And there you have it!
How about this?
Use a global counter to assign IDs to your inputs. Then, since you know what ID triggered the event, you just add or subtract from that ID to get the new ID you should go to. Here's some code:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
console.log("hej");
$('input[type="text"],textarea').keyup(function(e){
if(e.which==39 || e.which==13) {
var thisId = parseInt(this.id);
$("#" + (thisId + 1)).focus();
} else if(e.which==37 || e.which==8) {
var thisId = parseInt(this.id);
$("#" + (thisId - 1)).focus();
} else if(e.which==40 || e.which==13) {
var thisId = parseInt(this.id);
$("#" + (thisId + 4)).focus();
} else if(e.which==38 || e.which==8) {
var thisId = parseInt(this.id);
$("#" + (thisId - 4)).focus();
}
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="1" name="5"></td>
<td><input type="text" id="2" name="6"></td>
<td><input type="text" id="3" name="7"></td>
<td><input type="text" id="4" name="8"></td>
</tr>
<tr>
<td><input type="text" id="5" name="5"></td>
<td><input type="text" id="6" name="6"></td>
<td><input type="text" id="7" name="7"></td>
<td><input type="text" id="8" name="8"></td>
</tr>
<tr>
<td><input type="text" id="9" name="5"></td>
<td><input type="text" id="10" name="6"></td>
<td><input type="text" id="11" name="7"></td>
<td><input type="text" id="12" name="8"></td>
</tr>
</table>
<table>
<tr>
<td><input type="text" id="13" name="5"></td>
<td><input type="text" id="14" name="6"></td>
<td><input type="text" id="15" name="7"></td>
<td><input type="text" id="16" name="8"></td>
</tr>
<tr>
<td><input type="text" id="17" name="5"></td>
<td><input type="text" id="18" name="6"></td>
<td><input type="text" id="19" name="7"></td>
<td><input type="text" id="20" name="8"></td>
</tr>
<tr>
<td><input type="text" id="21" name="5"></td>
<td><input type="text" id="22" name="6"></td>
<td><input type="text" id="23" name="7"></td>
<td><input type="text" id="24" name="8"></td>
</tr>
</table>
</form>
</body>
</html>

Javascript array into function not working?

I have used this website a lot for research etc and find it extremely useful.
I have been developing a little bit of code that will get a list of input id names and then add there values together using javascript/jquery.
This is what I have so far - it might be well off the mark as I am still a novice.
So far the code gets the names of the inputs fine. It also does the calculation fine but when I put the array into the "var fieldnames" the calculation stops working?
When I copy the array out (after putting it into an input) and pasting it into the "var fieldnames" it works fine.
The issue seems to be that the array doesnt pass over to the "var fieldnames" correctly??
Here is the code from the page - it puts the array into the inputs at the bottom for investigation purposes only but the calculation doesnt work unless you put the input names in manually!
Any help would be much appreciated.
Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head><body>
<script type="text/javascript" language="javascript">
function getTotal(oForm)
{
var arrayOfIDs = $('.myClass').map(function() { return this.id; }).get();
var test = (arrayOfIDs.length ? "'" + arrayOfIDs.join("','") + "'" : "");
document.getElementById("sum").value = test;
var field, i = 0, total = 0, els = oForm.elements;
var fieldnames = [test];
document.getElementById("sum1").value = fieldnames;
for (i; i < fieldnames.length; ++i)
{
field = els[fieldnames[i]];
if (field.value != '' && isNaN(field.value))
{
alert('Please enter a valid number here.')
field.focus();
field.select();
return '';
}
else total += Number(field.value);
}
return ' ' + total;
}
</script>
<div id="listing">
<form>
<table>
<td>8065020</td>
<td>2012-04-10</td>
<td>household</td>
<td><input class="myClass" id="pay47" type="text" name="pay47" value="38.45"/></td>
</tr>
<tr>
<td>8065021</td>
<td>2012-04-10</td>
<td>household</td>
<td><input class="myClass" id="pay48" type="text" name="pay48" value="37.4"/></td>
</tr>
<tr>
<td>8065022</td>
<td>2012-04-10</td>
<td>household</td>
<td><input class="myClass" id="pay49" type="text" name="pay49" value="375"/></td>
</tr>
<tr>
<td>8065014</td>
<td>2012-04-04</td>
<td>household</td>
<td><input type="text" class="myClass" id="pay50" name="pay50" value="06"/></td>
</tr>
<tr>
<td>8065015</td>
<td>2012-04-04</td>
<td>motorprotect</td>
<td><input type="text" class="myClass" id="pay51" name="pay51" value="01"/></td>
</tr>
<tr>
<td>8065011</td>
<td>2012-03-06</td>
<td>household</td>
<td><input type="text" class="myClass" id="pay52" name="pay52" value="55"/></td>
</tr>
<tr>
<td>8065012</td>
<td>2012-03-06</td>
<td>household</td>
<td><input type="text" class="myClass" id="pay53" name="pay53" value="56"/></td>
</tr>
<tr>
<td>1</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay54" name="pay54" value="56"/></td>
</tr>
<tr>
<td>2</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay55" name="pay55" value="52"/></td>
</tr>
<tr>
<td>3</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay56" name="pay56" value="53"/></td>
</tr>
<tr>
<td>4</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay57" name="pay57" value="55"/></td>
</tr>
<tr>
<td>8065001</td>
<td/>
<td>landlord</td>
<td><input type="text" class="myClass" id="pay58" name="pay58" value="5"/></td>
</tr>
<tr>
<td>8065002</td>
<td/>
<td>landlord-basic</td>
<td><input type="text" class="myClass" id="pay59" name="pay59" value="59"/></td>
</tr>
<tr>
<td>8065003</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay60" name="pay60" value="5"/></td>
</tr>
<tr>
<td>8065004</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay61" name="pay61" value="5"/></td>
</tr>
<tr>
<td>8065005</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay62" name="pay62" value="5"/></td>
</tr>
<tr>
<td>8065006</td>
<td/>
<td>landlord-basic</td>
<td><input type="text" class="myClass" id="pay63" name="pay63" value="64"/></td>
</tr>
<tr>
<td>8065008</td>
<td/>
<td>household</td>
<td><input type="text" class="myClass" id="pay64" name="pay64" value="5" /></td>
</tr>
<tr>
<td>8065010</td>
<td/>
<td>business-basic</td>
<td><input type="text" class="myClass" id="pay65" name="pay65" value="10" /></td>
</tr>
</table>
<input id="total" type="text" name="total" value="" readonly="readonly" />
<input type="button" value="Get Total" onclick="total.value=getTotal(this.form)" />
<br /><br />
<input name="totalpay" id="sum" type="text" />sum<br />
<input name="totalpay" id="sum1" type="text" />sum1
</form>
</div>
</body>
</html>
1- Replace the line
var test = (arrayOfIDs.length ? "'" + arrayOfIDs.join("','") + "'" : "");
By
var test = (arrayOfIDs.length ? arrayOfIDs.join(",") : "");
2- Replace
var fieldnames = [test];
By
var fieldnames = test.split(",");
3- Replace
field = els[fieldnames[i]];
By
field = document.getElementById(fieldnames[i]);
What i did here is only correct you code to resolve your problem, but i am covinced that you can do this in a more easiest way.
If I understood your question correctly and you just want to add up your values, while provideing basic validity check, your code is way to complicated. Frameworks like jQuery provide you with means to do this much simpler.
Instead of looping through all input elements, getting their id's and then looping through them again, just do it once.
var getTotal (oForm) {
var sum = 0;
// loop through all inputs with class "myClass" inside oForm
$("input.myClass", $(oForm)).each(function (index, value) {
// add up all values that are non empty and numeric
if (value !== "" && !isNaN(value)) {
// parse the value
sum += parseFloat(value, 10);
} else {
// show an alert, focus the input and return early from $.fn.each
alert("Please enter a valid number here!");
$(this).focus();
return false;
}
});
// set the value of
$("sum").val(sum);
}
This was written from the top of my head but should work fine.

Categories

Resources