Im making a page that has a search function. I would like to be able to click the results in the table and have it insert the information into a form below it. For Example: a page for medical records where you would search by last name, it would populate the table with the customers info, and you can click one of the results in the table for it to fill in all the information into the form below the table.
I currently have the table pulling the results and entering the data into the form but i have to click a button before it will allow me to select anything in the table. I really dont want to have to press the button. Below is the Javascript code, and php. If you need more, I can provide it.
Javascript: I have think what requires the button to be pressed is the var row = td.parentNode line, because when its just taken away, the selecting functionality ceases.
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
populateFields(row);
}
PHP
echo '<input id="selectstyle" type="button" value="Select" onclick="test()"><br><table class="table-search" id="searchresulttable"><br>';
if(count($row)) {
$end_result = '';
echo "<tr><td><u>Last Name</u></td><td><u>First Name</u></td><td><u>Phone #</u></td><td><u>Address</u></td><td><u>License</u></td><td><u>Tax Exempt</u></td><td><u>Tax ID</u></td></tr>";
foreach($row as $r) {
$result = ucwords($r['bidlname']);
// we will use this to bold the search word in result
$bold = '<td>' . ucwords($r['bidlname']) . '</td>' . '<td>' . ucwords($r['bidfname']) . '</td><td>' . $r['bidphnum'] . '</td><td>' . $r['bidaddress'] . '</td><td>' . $r['bidlicense'] . '</td><td>' . $r['bidtaxexempt'] . '</td><td>' . $r['bidtaxid'] .'</td>';
$end_result .= '<tr>' . $bold . '</tr>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
echo '</table><br>';
I would like to be able to just click the entry i want to insert, without having to click the button first. Thoughts or ideas?
If I understood correctly your question my answer is the following snippet:
var ishigh;
function populateFields(row) {
// get the form elements
var frmElements = document.getElementById('frm');
// for each cell in current row
for(var i=0; i< row.cells.length; i++) {
// copy the cell value to the input value
frmElements[i].value = row.cells[i].textContent;
}
}
// when document is ready
window.addEventListener("DOMContentLoaded", function(event) {
// associate the click handler for the table
document.getElementById('searchresulttable').onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement;
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
// populate the form with the content of current row
populateFields(row);
}
});
function test() {
// do nothing.....
}
.highlighted {
background-color: #ffff99;
}
<input id="selectstyle" type="button" value="Select" onclick="test()"><br>
<table class="table-search" id="searchresulttable"><br>
<tr>
<td><u>Last Name</u></td>
<td><u>First Name</u></td>
<td><u>Phone #</u></td>
<td><u>Address</u></td>
<td><u>License</u></td>
<td><u>Tax Exempt</u></td>
<td><u>Tax ID</u></td>
</tr>
<tr>
<td>1bidlname</td>
<td>1bidfname</td>
<td>1bidphnum</td>
<td>1bidaddress</td>
<td>1bidlicense</td>
<td>1bidtaxexempt</td>
<td>1bidtaxid</td>
</tr>
<tr>
<td>2bidlname</td>
<td>2bidfname</td>
<td>2bidphnum</td>
<td>2bidaddress</td>
<td>2bidlicense</td>
<td>2bidtaxexempt</td>
<td>2bidtaxid</td>
</tr>
<tr>
<td>3bidlname</td>
<td>3bidfname</td>
<td>3bidphnum</td>
<td>3bidaddress</td>
<td>3bidlicense</td>
<td>3bidtaxexempt</td>
<td>3bidtaxid</td>
</tr>
</table>
<br>
<form id="frm">
Last Name:<br>
<input type="text" name="lastname"><br>
First Name:<br>
<input type="text" name="firstname"><br>
Phone #:<br>
<input type="text" name="phonenumber"><br>
Address:<br>
<input type="text" name="address"><br>
License:<br>
<input type="text" name="license"><br>
Tax Exempt:<br>
<input type="text" name="taxexempt"><br>
Tax Id:<br>
<input type="text" name="taxid"><br>
</form>
I haven't 50 rep yet so I'll have to sort of hack my approach here...
Are you using regular js or are you running a library like jQuery or underscore?
Is this specifically for touch-enabled devices or not (its okay to have both but this info would help)
My recommendation is that you use any JS library that can do batch click assignment here.
Maybe add a button to the row to trigger the action or even adjust your PHP to add properties to an and in JS preventDefault on the event then take the data from off it.
something like...
<a class="click_here_for_population" data-fisrt-name="FirstName" data-last-name="LastName" data-anything-else="foo">Add to form</a>
then...
$('click_here_for_population').click(function(e){
e.preventDefault();
// do the population stuff from $(this) or pass $(this) to the function
})
This way the event target holds the data you need without having to navigate parents/siblings.
Related
May I know that how do i retrieve data from the HTML table which the data value is actually retrieve from firebase.
Scenario:
When I need to edit the first row of data (user1,timmyscottmy#gmail.com,lecturer), I will just click the edit button inside the first row.Then, it will prompt up a form which display as in the https://i.stack.imgur.com/AVzSg.png, I plan to get the specific data for example, when I click the edit button from first row of data, inside the form, It will only append first row of data in the form and the HTML form for input placeholder will show the current specific row data of data. For example, when inside the form, when I click the input field for the email, the placeholder will show up that the current data is timmyscottmy#gmail.com.
1: https://i.stack.imgur.com/lXSfP.png
2: https://i.stack.imgur.com/AVzSg.png
3: https://i.stack.imgur.com/IDOCS.png
code in HTML:
<div id="abc">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="#" id="form" method="post" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2 >Edit</h2>
<hr>
<input id="userID" name="UserID" placeholder="User = user1" type="text">
<input id="email" name="email" placeholder="Email = timmyscottmy#gmail.com" type="text">
<input id="usertype" name="usertype" placeholder="User type = lecturer" type="text">
Update
Cancel
</form>
</div>
<script src="form.js"></script>
Code in javascript = form.js
firebase.database().ref("users").orderByKey().once("value").then(function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var user = childSnapshot.ref.getKey();
var email = childSnapshot.child("email").val();
var usertype = childSnapshot.child("usertype").val();
$("#table_body1").append('<tr><td>' + user +'</td> <td>' + email +'</td> <td>'
+ usertype +'</td> <td>' + `<div class="Edit" onclick="div_show()"><img src =
"edit.png"></div>`+'</td> <td>' + `<div class="Edit" onclick="delete_show()">.
<img src = "delete.png"></div>` + '</td> </tr>');
});
});
//ref.getKey() to get the users
//childSnapshot.ref.getKey(); to get the user1,user2, user3
// Validating Empty Field
function check_empty() {
if (document.getElementById('userId').value == "" || document.getElementById('email').value == "" || document.getElementById('usertype').value == "") {
alert("Fill All Fields !");
} else {
document.getElementById('form').submit();
alert("Form Submitted Successfully...");
}
}
//Function To Display Popup
function div_show() {
document.getElementById('abc').style.display = "block";
var user = document.getElementById("user").value;
firebase.database().ref('users/'+user).once('value').then(function (snapshot){
var email = snapshot.val().email;
var usertype = snapshot.val().usertype;
document.getElementById("email").innerHTML=email;
document.getElementById("usertype").innerHTML=usertype;
// var email = childSnapshot.child("email").val();
// var usertype = childSnapshot.child("usertype").val();
})
}
//Function to Hide Popup
function div_hide(){
document.getElementById('abc').style.display = "none";
}
Since it seems that your data entries don't have any unique ID's because you can even change the "user1" to whatever you'd like, what i did in a similar situation was to save that data they change into the table, and then just update the entire table row by row into firebase, instead of trying to look for one data point to change.
And just for a better user experience i would suggest taking your edit form and replacing the placeholders with the actual values of the input so that your user does not need to retype the entire field in case they only want to change one thing.
I have a table and i want to update the values of the table cell on click .
I want to show an input field containing current value .
Current value is showing but when i click on input filed to edit then suddenly the input field become empty .
$('td#11').click(function(event){
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" +valuee+ "></form>");
});
An alternative other solutions:
$('td#11').click(function(event){
if($('td#11').find('form, input').length == 0) {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input id='txt11' style='color:black;' value=" +valuee+ "></form>");
}
});
You can add another snippet with above snippet to remove text-box on losing focus to it as below:
$(document).on('blur', 'input#txt11', function() {
$('td#11').html($('input#txt11').val());
});
Working demo
jsFiddle
The problem is that your click event fires again and again and so on.
To avoĆd this, use event.target.tagName And check if it does not match "INPUT"
$('td#11').click(function(event) {
if (event.target.tagName != "INPUT") {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>");
}
});
Working Demo below
$('td#11').click(function(event) {
if (event.target.tagName != "INPUT") {
var valuee = $('td#11').text();
$('td#11').html("<form method='post'><input style='color:black;' value=" + valuee + "></form>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="11">text</td>
</tr>
</table>
In this webpage I am generating multiple textbox dynamically and each textbox is meant to hold unique value and I want to get that value dynamically.But I'm not being able to catch the value of the textbox according to its position. This code is only working for the firstly generated textbox. I have code like this
<tr>
<td align="center"><input type="text" name="serialNoArray[]" id="serialArray" onChange="checkusername()" ><span id="std_id_status"></span></td>
</tr>
<script>
function checkusername() {
var s = _("serialArray").value;
if(s != "") {
_("std_id_status").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true){
_("std_id_status").innerHTML = ajax.responseText;
}
}
ajax.send("std_id_check="+s);
}
}
</script>
First you should use classes not id, because an element with id must be unique for the entire document.
And since you use onChange you can pass the element using this like that onChange="checkusername(this)" .
I guess you should also change the code of the restrict function onkeyup="restrict('serialArray')" also but i do not see that code so I cannot help you more if you do not provide this code too...
<tr>
<td align="center"><input type="text" name="serialNoArray[]" class="serialArray" onkeyup="restrict('serialArray')" onChange="checkusername(this)" ><span class="std_id_status"></span></td>
</tr>
Then you can get only the value of the element being changed and change the html of the matching span only.(I use jQuery in the example so you should include it in your document.)
<script>
function checkusername(s) {
if (s.value != "") {
$(s).nextAll('.std_id_status').first().html('checking ...');
var ajax = ajaxObj("POST", "sellingDetails.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
$(s).nextAll('.std_id_status').first().html(ajax.responseText);
}
}
ajax.send("std_id_check=" + s.value);
}
}
</script>
Since i do not have all your javascript code I could not test it but something like this should work.
I have not tested but this should do it
All the dynamically generated textboxes, give them a class
<input type="text" class="tagMe" placeholder="Enter Serial No." onkeypress="return isNumberKey2(event)" onkeyup="restrict('serialArray')" onChange="checkusername()" required autofocus >
Collecting the data
var info= "";
$('.tagMe').each( obj, function( key, value ) {
if(info != "")
info += "^"; // ^ is a delimiter
info += value;
});
Send info to your server, split on ^ and parse data (careful of empty elements)
I am trying to submit a laravel form
Using a button I am adding dynamic rows with javascript. Code is
<input type="button" value="Add Particular" onClick="addRow('dataTable')"/>
Laravel Form:
<table class="table" id="dataTable">
<tr>
<td>
<label for="Fee Category" > Fee Category * </label>
<select name='CategoryID[]' rows='5' class='CategoryID' code='{$CategoryID}'
class='select2 ' requred ></select>
</td>
<td>
<label for="Amount">Amount *</label>
{{ Form::text('amount[]', $row['amount'],array('class'=>'form-control', 'placeholder'=>'', 'required'=>'true', 'parsley-type'=>'number' )) }}
</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
Javascript Functions to add & Delete Rows:
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount<5)
{
var row = table.insertRow (rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0;i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML= table.rows[0].cells[i].innerHTML;
}
}
else
{
alert("Max Reached")
}
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
I am unable to use Laravel form validation error results to newly added rows. Its working fine on hard coded form rows. Please help
Also How can I keep minimum of one row. Currently delete button deletes all rows
You can add an onchange event on every field even in the dynamic ones, they will call the validator as sson as they are changed so the user knows in no time if it was a valid entrance.
I wrote this code in a hurry, color example is applied, new line example is too, remove is added too, empty box on focus is applied too and all other things asked.
<html>
<head>
<script type="text/javascript">
/**
A dynamic name is assigned to a new field created.
*/
var id=0;
var dbq="\"";
/************************* addRow function end ******************************************/
function addRow(count)
{
/**
Decide what fieldset is going to host the row
*/
var myFieldset='fieldset2';
var section='2';
if(count==4){
myFieldset='fieldset1';
var organisationID = id++;
var positionID = id++;
var section=''
}
/**
Create ids
*/
divID = id++;
nameID = id++;
emailID = id++;
/**
The row will be hosted in a div
*/
var myDiv = document.createElement("div");
myDiv.setAttribute("id", divID);
/**
Create the text boxes
*/
myDivInnerHTML=
'<input type=text name=name'+section+'[]'+' value=Name id='+nameID+
' onFocus='+dbq+'emptyTheBox('+nameID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+nameID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+nameID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=email'+section+'[]'+' value=Email id='+emailID+
' onFocus='+dbq+'emptyTheBox('+emailID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+emailID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+emailID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+'>' ;
/**
Decide if we need 4 or 2 boxes
*/
if(count==4)
myDivInnerHTML=myDivInnerHTML+
'<input type=text name=organisation'+section+'[]'+' value=Organisation id='+organisationID+
' onFocus='+dbq+'emptyTheBox('+organisationID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+organisationID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+organisationID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=position'+section+'[]'+' value=Position id='+positionID+
' onFocus='+dbq+'emptyTheBox('+positionID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+positionID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+positionID+');'+dbq+
' style='+dbq+'color:#66634F'+dbq+'>' ;
/**
Create a button to remove the row too.
*/
myDivInnerHTML=myDivInnerHTML+
'<input type=button class="remove" value="Remove" onClick='+dbq+'removeDiv('+divID+','+ myFieldset +');'+dbq+' >';
/**
Add the div-row to the fieldset
*/
myDiv.innerHTML = myDivInnerHTML;
document.getElementById(myFieldset).appendChild(myDiv);
}
/************************* addRow function end ******************************************/
/**
Change the color of the text being entered
*/
function changeInputColor(caller){
document.getElementById(caller).style.color = 'black';
}
/**
Remove a row on demand
*/
function removeDiv(divID, myFieldset){
myFieldset.removeChild(document.getElementById(divID));
}
/**
Empty the box on initial click
*/
function emptyTheBox(caller)
{
var val=document.getElementById(caller).value;
if(val=='Name' || val=='Email' || val=='Organisation' || val=='Position' )
document.getElementById(caller).value='';
}
/**
Display a message
*/
function echo(message)
{
document.getElementById('message').innerHTML="<h3>"+message+"</h3>";
}
/**********************Validates a single field, return false on fail************************/
function fieldValidator(caller)
{
var error='';
/**
Identify the field (if it is email, name etc) by getting the first character
which is always the same,also get its value and full name
*/
var currentFieldCategory = document.getElementById(caller).name.charAt(0);
var currentFieldValue = document.getElementById(caller).value;
var currentField = document.getElementById(caller);
/**
Check for empty value
*/
if(currentFieldValue == '')
{
echo('Please fill the data!');currentField.focus();
return 'Please fill the data!';
}
/**
Check if default value left behind
*/
if(currentFieldValue.toLowerCase()=="name" || currentFieldValue.toLowerCase()
=="email" || currentFieldValue.toLowerCase()=="organisation" ||
currentFieldValue.toLowerCase()=="position" )
{
echo('Please check you entry, default data left behind!');currentField.focus();
return 'Please check you entry, default data left behind!';
}
/**
Validate the NAME field
*/
if(currentFieldCategory=='n')
{
if(currentFieldValue.match(/^[ |'|-]/)||!(/^[a-zA-Z- ']*$/.test(currentFieldValue))
|| currentFieldValue.length<4 || currentFieldValue.length>70)
{
echo('Non valid name found!');currentField.focus();
return 'Non valid name found!';
}//inner if
}//outer if
/**
Validate a non empty EMAIL name field
*/
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("#");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Non valid email found!');currentField.focus();
return 'Non valid email found!';
}//inner if
}//outer if
/**
Validate a non empty ORGANIZATION name field
*/
if(currentFieldCategory=='o')
{
if(currentFieldValue.length<2 || currentFieldValue.length>50)
{
echo('Use at least 2 letters and less than 50 for your organisation.');
currentField.focus();
return 'Use at least 2 letters and less than 50 for your organisation.';
}//inner if
}//outer if
/**
Validate a non empty POSITON name field
*/
if(currentFieldCategory=='p')
{
if(currentFieldValue.length<7 || currentFieldValue.length>40)
{
echo('Use at least 7 letters and less than 40 to describe your position.');
currentField.focus();
return 'Use at least 7 letters and less than 40 to describe your position.';
}//inner if
}//outer if
/**
Now on success do the rest
*/
document.getElementById(caller).style.backgroundColor = '#FF9900';
document.getElementById('message').innerHTML="";
return true;
}
/*****************fieldValidator ***function ends*****************************************/
/*******************************************************************************************/
function finalValidator()
{
/**
Get the form object
*/
var myForm=document.getElementById('booking').elements;
/**
Check if the form has no rows, for now 3 indicates no rows,
BE CAREFULL it might change if more buttons added,
just alert the length to see.
*/
if(myForm.length==3)
return false;
/**
Iterate through the form for all fields
*/
for(var i = 0; i < myForm.length; i++)
{
//If it is a text field validate it
if(myForm[i].type=='text')
{
var validation = fieldValidator(myForm[i].id);
if(validation!==true)
{
echo (validation);
return false;//prevent submit
}//validation if
}//field type if
}//for loop
}//function
/*******************************************************************************************/
</script>
</head>
<body bgcolor=gray>
<div id="add-buttons"><span class="add" onclick="addRow(4);"><input type="button" class="button" value="Add Waged Person"></span><span class="add" onclick="addRow(2);"><input type="button" class="button" value="Add Unwaged Person"></span></div>
<div id="message" ></div>
<div id="form-wrap">
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset id="fieldset1">
<div class="subtitle">Waged/Organisation Rate</div>
</fieldset>
<fieldset id="fieldset2">
<div class="subtitle">Unwaged Rate</div>
</fieldset>
<!-- return finalValidator will allow submit only if fields are validated-->
<p><input type="submit" name="submit" id="submit" onClick="return finalValidator();"
value="Submit booking" class="submit-button" /></p>
</form>
</body>
</html>
Validation added. The array and the color things are a bit trivial and you should show what effort you have done here your self.It is interesting to be involved only when you see the will on someone.
for adding the row
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount<5)
{
var row = table.insertRow (rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0;i<colCount; i++)
{
var newcell = row.insertCell(i);
newcell.innerHTML= table.rows[0].cells[i].innerHTML;
}
}
else
{
alert("Max Reached")
}
}
to delete the particular row use the rowIndex to find the particular row and deleteRow to delete the particular row from the table
function deleteRow(btn) {
var row = btn.parentNode.parentNode.rowIndex;
document.getElementById("dataTable").deleteRow(row);
}
for the valdation use the parentNode and childNodes because they will work on DOM
What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}