Javascript/HTML:Java script for Radio button not working properly - javascript

I have a problem with my java script and radio button.
I want to make radio button only can be choose only one in each row based on the id value from database, but in my case the function is working on the first row but the rest is not because it only return the first row value. the radio button is generate dynamically(the count of radio button row is based on how many id in db).
below is my java script:
function test1(){
var tes = document.getElementById('max');
var zes = document.getElementById('max1');
alert(tes.value)
if(tes.checked){
zes.checked = false;
}
}
function test2(){
var tes = document.getElementById('max');
var zes = document.getElementById('max1');
alert(zes.value)
if(zes.checked){
tes.checked = false;
}
}
This is my radio button code:
<td align = 'center'>
<?php
$test = $col['id'];
$testing = "select training.* from training inner join rekod on training.id = rekod.id where rekod.id = '$test'";
$userx = mysql_query($testing) or die (mysqli_error());
$u = mysql_fetch_assoc($userx);
echo $u['id'];
echo "<input type ='radio' name='x' onchange='test1();' required id='max' value ='".$u['id']."'>";?>
</td><td align='center'>
<?php
$te = $col['id'];
$tes = "select training.* from training inner join rekod on training.id = rekod.id where rekod.id = '$te'";
$us = mysql_query($tes) or die (mysqli_error());
$ux = mysql_fetch_assoc($us);
echo $ux['id'];
echo "<input type ='radio' name='x1' onchange='test2();' required id='max1' value ='".$ux['id']."'>";?>
</td>
The code above will generate something like this (the number is id):
I want to make like this:
but it become like this:
can someone tell me what wrong with my code ?

There is no need of JS logic, you have to use radio button grouping by name, if you are using loop then append same index in radio's name for both columns and then your html should be like,
<tr>
<td>
...
<input type="radio" name="x_1" .../>
</td>
<td>
...
<input type="radio" name="x_1" .../>
</td>
</tr>
<tr>
<td>
...
<input type="radio" name="x_2" .../>
</td>
<td>
...
<input type="radio" name="x_2" .../>
</td>
</tr>
Read more about input-type-radio

You are using document.getElementById and trying to access multiple elements, that is not correct. If you have multiple DOM elements to access and manipulate then you need to go with document.getElementsByClassName or document.getElementsBtTagName. In an HTML page, you can have only one element with a unique id (id of two elements can never be same).
In your case, you are using a loop and assigning the same id to all elements in the loop. That is the problem.
Thank you.

Related

using javascript to build on php loop with classes only logging first result

I'm currently building a form and the data within it is build from a PHP Foreach loop
I'm using Javascript so that I can make the action of checking/unchecking a checkbox will make an ajax call.
The issue right now (using class names) is that when I click the checkbox and console log the data, each checkbox does trigger properly but it only console logs the first table row's data
So if my php loop builds 5 rows, each with their own values and their own checkboxes, each checkbox triggers the log but they each log only the first set of values.
What am I doing wrong here?
$(".addToLineup").click(function (e) {
var number = document.getElementsByClassName("number")[0].innerHTML;
var detail = document.getElementsByClassName("detail")[0].innerHTML;
var category = document.getElementsByClassName("category")[0].innerHTML;
updatedata.number = number;
updatedata.detail = detail;
updatedata.category = category;
console.log(updatedata);
)};
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="number">{{$list['GROUP']}}</td>
<td class="detail">{{$list['COVER']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup" type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>

javascript/jquery: how to add/remove variables from array depending on whether a checkbox is selected

I'm outputting order addresses for a takeout restaurant: each individual order is output as a table, each table has a checkbox. I want to put the addresses into an array when the .ordercollected checkbox is ticked, and remove it from the array if it is unticked.
At the moment, rather than appending each new address I get each order address on its own in the array, which updates each time I tick the .ordercollected checkbox.
Really new to programming so any help appreciated!
//get the addresses from selected tables
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
$(this).each(function() {
//if checkbox is ticked
if ($(this).is(':checked')) {
//get address from table
var address = $(this).closest('.ordertable').find('.address').text();
//append value of address into activeaddress array
activeaddress.push(address);
};
});
console.log('active address: ', activeaddress);
});
edit to add in the tables I am creating:
<table class="ordertable">
<tr>
<td>
<p>Order #
<?php echo $order_id; ?> —
<time datetime="<?php the_time('c'); ?>">
<?php echo the_time('d/m/Y g:i:s A'); ?>
</time>
</p>
</td>
<td>
<?php echo $order->billing_first_name . ' ' . $order->billing_last_name ?>
</td>
<td>
<?php if ($order->billing_phone) : ?>
Tel.
<?php endif; ?>
</td>
<td>
<p class="address"><?php echo $order->shipping_address_1 . ' ' . $order->shipping_postcode ?></p>
<td/>
<td>
<a class="maps-activate" href="#">Open in Maps</a>
</td>
<td>
<form action="">
<input type="checkbox" class="ordercollected" value="0" />
</form>
</td>
</tr>
</table>
Rather than remake your entire activeaddress array every time a checkbox changes, the best thing to do here would be to add or remove only the selected address when a checkbox changes. To do this activeaddress will have to be available outside of that function. I also think it will be cleaner if you use a JS object instead of an array.
var activeaddress = {};
$('.ordercollected').change(function() {
// get table id
var orderTableID = $(this).closest('.ordertable').attr('id');
// if checkbox is ticked
if($(this).is(':checked')) {
// get address from table
var address = $(this).closest('.ordertable').find('.address').text();
// append value of address into activeaddress object
activeaddress[orderTableID] = address;
} else { // checkbox is NOT ticked
// remove address from object
delete activeaddress[orderTableID];
}
console.log("active address: ", activeaddress);
});
As you can see, this code assumes that each table with class .ordertable has a unique id that can be used as the key in the activeaddress object. This is better than looping over the entire array/object each time because, especially if you have a very big set of orders. If you had included your HTML I would be able to help more, but as the question is this is as far as I can help. Let me know if you have any follow up questions.
A couple of things to note:
Using pascalCase for variable names and class names makes code more readable (e.g. activeAddress instead of activeaddress)
In my opinion, using an object instead of an array is a better way to add and remove a specific item
When asking question on SO, please give as much information as possible, such as including your HTML
Finally some links:
Adding a key value pair to an object
Removing a key value pair from an object
try something like this?
HTML:
<input type="checkbox" class="ordercollected" value="apple" />
<input type="checkbox" class="ordercollected" value="mango" />
JS
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
if (this.checked) {
activeaddress.push(this.value);
}
else {
var index = activeaddress.indexOf(this.value);
if (index > -1) {
activeaddress.splice(index, 1);
}
}
console.log('active address: ', activeaddress);
});

Checking variable for multiple inputs after onChange event

So I have a dynamic form that has two columns. One has a job name and the other has an input box where the user could enter their on description of the job.
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name" name="job_name"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" name="job_desc" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,)" />
</td>
</tr>
';
}
So as you can see I have a while loop that populates this form. So it could potentially have a lot of input boxes that you can use to describe the jobs.
The issue I am having is that, when I handle this form with the AJAX I have set up. The javascript simply grabs the last job on the list and uses that as it's jobs name. So in essence it is grabbing the input box correctly it's just placing it in the wrong row.
Here is the javascript that handles this change.
var job = document.getElementsByNames("job_name").value;
var comment = document.getElementsByNames("job_desc").value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php
echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
I know I should be grabbing the elements with getElementByNames but I just don't know how to pair up the comment with the proper job that it's supposed to go with. So if someone comments next to the input box for Granite Job the comment should be paired up with the job name 'Granite Job' in the database. Instead currently it will just be paired up with the last job on the list which is 'Cabinet Assembly'.
Any help would be appreciated.
First of all, you have a HTML error for the attribute id
You may not in HTML standards to give a same value for id attribute to a multiple elements.
But fortunately we can use this unique identifier to make your code works
You can edit your PHP code to some thing like this:
$counter=0;
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name_'.$counter.'"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" id="job_desc_'.$counter.'" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,'.$counter.')" />
</td>
</tr>
';
$counter++;
}
You can see we added a counter to identify our rows
Updating your Javascript code will be as follow:
var insertCommentInstall=function(value,identifier){
var job = document.getElementById("job_name_"+identifier).value;
var comment = document.getElementById("job_desc_"+identifier).value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
}
When you use a selector like getElementsByClassName or getElementsByTagName you are retrieving a nodelist of all elements with the specified attribute (adding a classname to your inputs would make this easier). You need to specify one particular node out of the nodelist in order to fetch it's value. In order to retrieve all values in your nodelist you need to loop through it and push the values of all its nodes into an array.
//finds all elements with classname "jobs"
var jobs = document.getElementsByClassName("jobs");
//create new array that we push all the values into
var jobValues = [];
//loop through our jobs nodelist and get the value of each input
for (var i = 0; i < jobs.length - 1; i++) {
jobValues.push(jobs[i].value);
}
jobValues; //gives you a list of all the values you pushed into the array
jobValues[5]; //gives you the value of the 6th input you looped through

How do I reset the value from the parameter passed by URL from Javascript in JSP

This is my first question ever in this website which I hope I can explain it well. I did find the same problem but mostly in PHP and I don't really understand (e.g- How to replace url parameter with javascript/jquery?). Here my explaination:
I have a function in Javascript (in page testStudentFile.jsp):
<script language="javascript">
function onParamChange(){
var thisForm = document.frmParam;
var strBranch = thisForm.reqBranch.value;
var strFaculty = thisForm.reqFaculty.value;
var strCourse = thisForm.reqCourse.value;
location.href ="testStudentFile.jsp?reqBranch="+strBranch+"&reqFaculty="+strFaculty+"&reqCourse="+strCourse;
}
</script>
Which get the value from here (and post at the same page):
<form name="frmParam" action="testStudentFile.jsp" method="POST">
<tr>
<td width="20%"><strong>Branch:</strong></td>
<td>
<%renderDropDownList2(out, "reqBranch", arrBranch, requestValue.strBranch,"onchange=\"onParamChange()\"");%><%=strBranchDesc%>
</td>
</tr>
<tr>
<td width="20%"><strong>Faculty:</strong></td>
<td>
<%renderDropDownList2(out, "reqFaculty", arrFaculty, requestValue.strFaculty,"onchange=\"onParamChange()\"");%><%=strFacultyDesc%>
</td>
</tr>
<tr align="left">
<td><strong>Course: </strong></td>
<td>
<%renderDropDownList2(out, "reqCourse", arrCourse, requestValue.strCourse,"onchange=\"onParamChange()\"");%><%=strCourseDesc%>
</td>
</tr>
<tr align="left">
<td> </td><td><strong><%out.print(arrStudent.size() + " students");%></strong>
</td>
</tr>
<tr>
<td></td>
<td><input name="reqSearch" class="iform" type="submit" value="Search"></td>
</tr>
</form>
And the data was retrieved from the method void that called data using sql query. Example one of the query:-
<%!
public void populateBranch(JspWriter out, Connection ConnTC, ArrayList arrBranch)throws Exception{
String sqlSelect = " SELECT DISTINCT branch FROM university"+
" WHERE active='Y'"+
" AND branch='PK'"+
" OR branch='ZZ'";
//out.print(sqlSelect);
PreparedStatement stmtSelect = ConnTC.prepareStatement(sqlSelect);
ResultSet rsSelect = stmtSelect.executeQuery();
while(rsSelect.next()){
String strBranch = getValue(rsSelect.getString("fbrncd"));
arrBranch.add(strBranch);
}
rsSelect.close();
stmtSelect.close();
}
%>
Here is my problem:
When I choose PK for branch, it will automatically list down the related faculties and next the related courses from the dropdownlists, but when I choose ZZ, the faculty and course choosen from PK branch didnt reset to the default(empty) before I can choose a faculty and a course for branch ZZ. How do I reset the dropdownlist (without reset button) to the default in the value of the parameter of the URL as stated in the Javascript above whenever the branch changed?
(Example)
From--> http://xxx.xxx.xx.x/portal/testApp/request/testStudentFile.jsp?reqBranch=PK&reqFaculty=FAS&reqCourse=AV
To--> http://xxx.xxx.xx.x/portal/testApp/request/testStudentFile.jsp?reqBranch=ZZ&reqFaculty=&reqCourse=
Warm Regards <3,
Eja ;-)
Do you want clear strFaculty and strCourse when branch is ZZ??
Then, just try this
var thisForm = document.frmParam;
var strBranch = thisForm.reqBranch.value;
var strFaculty = strBranch == 'ZZ' ? '' : thisForm.reqFaculty.value;
var strCourse = strBranch == 'ZZ' ? '' : thisForm.reqCourse.value;
location.href = ....
I hope that this is useful for you. Thanks.
Here is my solution to reset a dropdown list when another changes.
Based on this thread and this one.
Simply call a function when the value is changed in one dropdown:
onchange="reset()"
In your reset function, select the element you wish to change index of and set it to 0:
var element = document.getElementById('id');
element.value = 0; // first value, an empty option in this example
Updated JSFiddle

Get elements from Parent Row of checked checkboxes

I have the following row in a table.
<tr class="data_rows" ng-repeat='d in t2'>
<td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td>
<td class="tds"><a href='perf?id={{d.ID}}'>{{d.ID}}</a></td>
<td class="tds">{{d.HostOS}}</td>
<td class="tds">{{d.BuildID}}</td>
<td class="tds">{{d.Description}}</td>
<td class="tds">{{d.User}}</td>
<td class="tds">{{d.StartTime}}</td>
<td class="tds">{{d.UniqueMeasure}}</td>
<td class="tds">{{d.TotalMeasure}}</td>
</tr>
Here's the HTML for button that will invoke the function to collect the ids from checked check boxes and store them.
<div id='compButtonDiv' align='center' style="display: none;">
<input id='cButton' type='button' value='compare selections' onclick='submitSelection()' style= "margin :0 auto" disabled>
</div>
The data is in t2 which consists of an array of length 15-20.
What i want to do is get the value of ID i.e, {{d.ID}} of the 2 checked check boxes so that i can store them in a variable and pass them as query parameters to URL using `location.href = url?param1&param2'
Here's the javascript:
function keepCount(obj){
debugger;
//var count=0;
if(obj.checked){
obj.classList.add("checked");
}else{
obj.classList.remove("checked");
}
var count = document.getElementsByClassName("checked").length;
var cBtn = document.getElementById('cButton');
//alert(count);
if(count == 2){
cBtn.disabled = false;
}
else if(count < 2){
cBtn.disabled= true;
}
else{
cBtn.disabled= true;
alert("Please Select two sets for comparison. You have selected: " + count);
}
}
function submitSelection(){
// what should be the code here??
location.href= "existingURL?a&b";
}
Now can someone please tell me how to get the id's?? I need to extract ID from the checkboxes that are checked(on the click of button whose code i've mentioned above'.
Thanks.
-Ely
Firstly when we use angularjs we tend to depend less and less on DOM manipulation.
For this reason, what you can do is to attach ngModel to the checkbox.
Like:
<input class='checkBoxInput' ng-model='d.isChecked' type='checkbox' onchange='keepCount(this)'>
What this does is, it attaches the variable (in your case the property of item in the list) to the check box. If it is checked it is true, if unchecked, initially it will be undefined, later on checking and then unchecking it will be false.
Now, when you submit, just loop over the original list in the function and check the values of d.isChecked (true/falsy values). Then you can add the necessary items in a separate list for submission.
The only concern is when checking the list on submission , check if(d.isChecked), so that it ignores the falsy values(false/undefined).

Categories