get checkbox attribute using javascript (array) - javascript

Hello guys i want to get the attribute of my checkbox. The checkbox was an array so i want to get the attribute of the checked checkboxes and put it on the textbox anf separate it with comma.
Here's my php/html
$query = $db->select('owners_information',array('*'),$con);
foreach($query as $q){
//echo $q['lastname'];
$output .= '
<tr>
<td>'.$q["firstname"].'</td>
<td>'.$q["middlename"].'</td>
<td>'.$q["lastname"].'</td>
<td>'.$q["land_area"].'</td>
<td><input type="text" value="'.$q["OCPC_ID"].'" name="ocid[]">
<input type="checkbox" value="'.$q["land_area"].'" name="checkval[]" attr="'.$q["OCPC_ID"].'"></td>
</tr>
';
}
if($query > 0){
echo '<input type="text" name="textval" id="textval">';
echo '<br><input type="text" name="ocpc_id" id="ocpc_id">';
echo '<input type="button" name="merge" id="merge" value="Merge" onclick="mergeFunc()">';
echo '<input type="button" name="addNew" id="addNew" value="Add New RPU" onclick="addMerge()" style="display:none;">';
echo $output;
}else{
echo "No data found";
}
And here's my javascript
function mergeFunc() {
var checkboxes = document.getElementsByName('checkval[]');
var cd = document.getElementsByName("checkval[]");
var val_id = "";
for (var l=0, n=cd.length;l<n;l++)
{
if (cd[l].checked)
{
val_id += ","+cd[l].attr;
}
}
if (val_id) val_id = val_id.substring(1);
alert(val_id);
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
$('#ocpc_id').val(val_id);
$('#textval').val(vals);
$('#merge').hide();
$('#addNew').show();
}
i want to get the attribute of the checkbox named checkval[]. I want to get what's inside the attr array. I hope you could help me guys.

Try this
document.getElementById('btn').addEventListener('click',function(){
var checkboxes = document.getElementsByName('checkval[]');
var input = document.getElementsByName('ocid[]');
var checkval = '';
var checkid = '';
for(var i=0;i<checkboxes.length;i++) {
if(checkboxes[i].checked){
i==0 ? checkval += checkboxes[i].value : checkval += ","+checkboxes[i].value;
i==0 ? checkid += input[i].value : checkid += ","+input[i].value;
}
}
console.log(checkval+" "+checkid);
});
See the demo

var val_id = "";
for (var l=0, n=cd.length;l<n;l++)
{
if (cd[l].checked)
{
val_id += ","+cd[l].getAttribute("attr");
}
}
if (val_id) val_id = val_id.substring(1);
I've change val_id += ","+cd[l].attr; to val_id += ","+cd[l].getAttribute("attr");
Thanks for your time guys.

Related

PHP $_POST can't read values set by jQuery val()

I created a little script which allows users to shadow some input values from other inputs. The JavaScript part is working fine, but now when I'm trying to send the form, it doesn't send it, saying that the field the value is copied to is empty. What's the problem here? Thanks!
$(document).ready(function()
{
$(":text").blur(function()
{
var input = $(this);
var id = input.attr("id");
var fieldname = "#".concat(id);
for (i = 0; i < fields.length; i++)
{
if (fields[i][4] == id)
{
var boxname = "#copy_".concat(fields[i][0]);
if ($(boxname).prop("checked"))
{
var fieldname2 = "#".concat(fields[i][0]);
$(fieldname2).val($(fieldname).val());
}
}
}
});
$(":checkbox").change(function()
{
var input = $(this);
var id = input.attr("id");
id = id.substring(id.indexOf("_") + 1, id.length);
var fieldname = "#".concat(id);
var checked = input.prop("checked");
$(fieldname).prop("disabled", checked);
var field = FindField(0, fields[FindField(0, id)][4]);
if (checked)
{
var fieldname2 = "#".concat(fields[field][0]);
$(fieldname).val($(fieldname2).val());
}
});
});
function FindField(index, value)
{
for (i = 0; i < fields.length; i++)
{
if (fields[i][index] == value) return i;
}
return -1;
}
The form (without some irrelevant stuff):
<form method="post" action="sendform.php">
<table>
<?php
foreach ($fields as $field)
{
if ($field[0] == "divider") echo('<tr><td colspan="2"><hr /></td></tr>');
else
{
switch ($field[2])
{
case FIELD_TEXT:
{
echo('<tr><td><label for="' . $field[0] . '">' . $field[1] . ': </label></td><td>');
if ($field[4] != "")
{
foreach ($fields as $field2)
{
if ($field2[0] == $field[4])
{
echo('<input type="checkbox" id="copy_' . $field[0] . '" title="Kopeeri väljalt "' . $field2[1] . '"" />');
}
}
}
echo('<input type="text" id="' . $field[0] . '" name="' . $field[0] . '" placeholder="' . $field[1] . '" /></td></tr>');
break;
}
}
}
}
?>
<tr><td colspan="2"><hr /></td></tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Saada avaldus" name="saadaavaldus" />
</td>
</tr>
</table>
</form>
A sample of the fields array:
var fields = <?php echo json_encode($fields); ?>
$fields = array
(
// ID/name label/placeholder type regex field copied from
array( "saatjanimi", "Teie täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", ""),
array( "meiliaadress", "Teie meiliaadress", FIELD_TEXT, "^([\pL-.\d]+)#([\pL-.\d]+)((\.(\pL){2,63})+)$", ""),
array( "isanimi", "Lapse isa täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", "saatjanimi")
);

Trying to delete items from a multidimensional array (html,javascript)

I have table that is created that shows each item added to the array. In the last row of each column is an action field that lets you either edit or delete from the row. I am not sure how I am supposed to accomplish this. What I have so far does not work properly.
function del(item) {
participantList.splice(item,1);
displayLIst();
}
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
if(fname !='' && lname !="" && email !='') {
participantList[count] = new Object();
participantList[count].Fname = fname;
participantList[count].Lname = lname;
participantList[count].Email = email;
participantList[count].Action = "<button onclick='del("+count+")'>Delete</button>" + "<button onclick='edit("+count+")'>Edit</button>";
count++;
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
}
I want to delete every object from the specified row in the array.
How are you getting the elements and putting them into the participant list?
Do you have references to the elements? Can you include the HTML as well and all the related code to what you want to do?
Below is how I would get all of the elements, and remove one.
You can remove an element by calling .remove() on it
Here is my example code: http://jsfiddle.net/gabs00/cxt170re/
var listItems = document.querySelectorAll('li');
var item = listItems[1];
item.remove();
querySelectorAll creates a live node list
I grab one of those elements (index 1) and delete it with Element.remove();
Check out the fiddle to see it in action.
Here is a current working version:
var participantList = [];
var edit = function(item) {};
var del = function(item) {
participantList.splice(item,1);
displayList();
};
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var count = participantList.length;
if(fname !='' && lname !="" && email !='') {
var item = {};
item.Fname = fname;
item.Lname = lname;
item.Email = email;
item.Action = "<button onclick='del("+count+")'>Delete</button><button onclick='edit("+count+")' disabled>Edit</button>";
participantList.push(item);
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
};
var displayList = function () {
// clean previous data
console.log(participantList);
document.getElementById("results").innerHTML = "";
var content = "";
for(var i = 0; i<participantList.length; i++) {
content += "<tr>";
content += "<td>" + participantList[i].Fname + "</td>";
content += "<td>" + participantList[i].Lname + "</td>";
content += "<td>" + participantList[i].Email + "</td>";
content += "<td>" + participantList[i].Action + "</td>";
content += "</tr>"
}
document.getElementById("results").innerHTML = "<table>" + content + " </table>";
};
With the following HTML Code:
<input type="text" id="fname" />
<input type="text" id="lname" />
<input type="text" id="email" />
<button onclick="addInfo()">
Add
</button>
<div id="results">
EDIT: Missing JSFiddle link: https://jsfiddle.net/d64314uk/

Javascript getting total sum from wrong checkbox trigger

Below are two different checkbox and the javascript below seems to be trigger by termsChkbx checkbox instead of chosen. How do I change this portion
var chosen = item.parentElement.querySelector('[type="checkbox"]'); ?
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id='selectChkbx' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
JS:
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("selectChkbx").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total;
}
createCheckbox();
You can try something like this:
JSFiddle
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
<div id="content"></div>
<p id="total">0</p>
Edit 1
I believe reason why you are not getting value is because of element structure. You have a span tag which holds price and another span tag holds checkbox. For such structure, you will have to navigate to that span and fetch its value. Following is depicted below.
Fetching Span's value
var price = chk[i].parentNode.previousSibling.textContent;
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<span>" + num + "</span>";
html += "<span><input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>Check</span><br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
var price = chk[i].parentNode.previousSibling.textContent;
total += parseFloat(price);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
.chk{
}
<div id="content"></div>
<p id="total">0</p>

Close and create a <tr> tag after every four <td> elements. Is it a loop?

I retrieved my list of users from my db and now I want to add them to my page. I am trying to display the users using a table and make sure that they appear four per row and then jump to the new row, but I am not certain how to do this. Here is my js file so far. Please let me know if there is anything else you need.
var space = new Array("username", "user_id","address","state","postal_code","phone","email");
$(document).ready( function() {
var obj = '';
$.getJSON( "obtainUsers.php", function(data) {
var num = 1;
var json = JSON.stringify(data);
obj = jQuery.parseJSON(json);
var html = "";
var tot_obj = obj.length ;
var upper = (num*10)-1;
var lower = (num*10)-10;
var max = ( upper < tot_obj ) ? upper : tot_obj ;
html += "<div><table width:'100%'><tr>";
for (var i = lower; i <= max-1 ; i++ )
{
var toggle = i % 2;
var list_items = "";
columns.forEach( function(col)
{
if ( obj[i][col] != null ) {
if ( obj[i][col] !== "" )
{
if ( obj[i].level == 'NEW' ) {
list_items += "<div class='new_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'RENEWAL' ) {
list_items += "<div class='renewing_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'CURRENT' ) {
list_items += "<div class='current_client';>";
list_items += obj[i][col] + "</div >";
//console.log(obj[i][col]);
}
}
}
} );
list_items += "</br >";
if ( toggle == 0 )
{
html += "<td><div class='table_styles'> ";
html += list_items ;
//console.log(list_items);
html += "</div></td>";
console.log(html);
}
else
{
html += "<td><div class='table_styles'> ";
html += list_items;
html += "</div></td>";
}
}
html += "</tr> </table></div>";
$('.runninglist').html(html);
});
});
var columns = ["username","user_id","address","state","postal_code","phone","email"];
var level_classes = {"NEW":"new_client", "RENEWAL":"renewing_client", "CURRENT":"current_client"};
$(document).ready( function() {
$.getJSON("obtainUsers.php", function(data) {
var $table = $('<table style="width: 100%;">');
var $tbody = $('<tbody>');
$table.append($tbody);
var $tr = null;
data.forEach(function(user, index){
if(index % 4 === 0) {
$tr = $('<tr>');
$tbody.append($tr);
}
$td = $('<td class="'+level_classes[user.level]+'">');
columns.forEach(function(col){
$td.append(user[col]);
$td.append($('<br>'));
});
$tr.append($td);
});
$('.runninglist').append($table);
});
});

Select checkbox is not working with javascript

I've a html checkbox which select all checkbox after click. But unfortunately it's not working. What's the problem in here ?
javascript Code:
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}</script>
Php code:
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact Name</b></td>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact
Number</b>";
echo '<input type="checkbox" onClick="toggle(this)" /> Toggle
All<br/>';
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
$gid = $row['gid'];
$contact_name = $row['contact_name'];
$contact_no = $row['contact_no'];
echo "<tr>";
echo "<td class='tdhead2' valign='top'>$contact_name</td>";
echo "<td class='tdhead2' ><input type='checkbox' value='$gid' name='contact_no[]''
/> $contact_no</td>";
echo "</tr>";
}
echo "</table>";
The name on each of your elements is: contact_no[] but in your JS code, you getElementsByName('contact_no') - add [] to the getElementsByName call.
for a safety, you should handle event object like code below
<script type="text/javascript">
function toggle(evt) {
evt = window.event || evt;
var source = evt.srcElement || evt.currentTarget
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<script language="JavaScript">
function toggle(source)
{
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++)
{
contact_no[i].checked = source.checked;
}
}
</script>
One another solution, you can add Id attribute on the main check box from which you want to perform select all action and make the same as class attribute of other check boxes.
E.g.
$(document).ready(function(){
$('.selectall').change(function({
var id = $(this).attr('id');
if ($(this)is(":checked")) {
$("." + id).attr('checked','checked');
} else {
$("." + id).attr('checked','');
}
}))
})
I hope this code helps you

Categories