Edit input name when chceckbox clicked - javascript

I try to edit name field for the specific input. I need this to get all the variables from this site and add them to my invoice script. I have two divs with client select and service select
HTML:
<div class="service-select">
<?php
$query = "SELECT id,service_name,quantity,net_price,gross_value FROM service";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<div class='single-service-<?php echo $row["id"]; ?>'>
<input type='checkbox' name=''>
<input type="text" name="service_name" class='name' value="<?php echo $row["service_name"]; ?>" placeholder='NAZWA USŁUGI' disabled/>
<label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
<label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
</div>
<?php
}
$result->free();
}
?>
</div>
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i=0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var div = this.parentNode;
var name_input = div.getElementsByClassName("name");
var name = name_input.name;
var parent_div = div.parentNode;
var x = div.childNodes;
console.log(name_input);
if (parent_div.className == 'service-select') {
if (name_input.name != 'service_chcecked[]') {
name_input.name = 'service_chcecked[]';
}
else {
name_input.name = 'service_name';
}
}
else {
if (name != 'client_chcecked[]') {
name_input.name = ['client_chcecked[]'];
}
else {
name_input.name = ['client_name'];
}
}
for(y=0; y < x.length; y++) {
if(x[y].type === "number" || x[y].type === "text") {
x[y].disabled = !x[y].disabled;
}
}
}, false);
};
My problem is that currently the given name is added to the div :/

Related

Uncaught TypeError Cannot read property "checked" of null

I have 2 php files. action.php and main.php
main.php is included in action.php
In action.php i have button and input.
<input type="text" class="form-control" name="multip" id="multip" value="" placeholder="MULTIPLY"/>
<button type="button" class="btn btn-primary" name="distribute" onclick="multiply()">Submit</button>
In main.php
$i = 1;
$sum1=0;
$distrib = array();
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$count = $row["count"];
$price = floor($row["currency"]*$row["buyPrice"]);
$iid = $row["iid"];
$distrib[]=$count;
$sum1 += $row["count"]*$row["buyPrice"];
echo '';
echo '<tr><td><input type="checkbox" name="check[]" id="checked_'.($i-1)
.'" value="'.$row["count"].'"> </td>
<th scope="row">'.$i++.'</th>
<td>'.$row["insert_version"].'</td>
<td>'.$row["code"].'</td></tr>';
}
$result->free();
}
$mysqli->close();
and script part of main.php
<script>
let dist = <?php echo json_encode($distrib); ?>;
let mult;
let count = <?php echo json_encode($count); ?>;
let i = +"<?php echo $i; ?>";
function multiply(){
let bashxel = parseInt(document.getElementById("multip").value);
mult = 0;
for (let k = 0; k<i; k++) {
let checkBox = document.getElementById("checked_"+k);
if (checkBox.checked === true) {
mult+=parseInt(dist[k]);
console.log(mult); //this works
}}
console.log(mult+100); //this doesn't work
//Error from here
};
</script>
I don't know why this problem shows. I searched about it but couldn't found solution.
Help me to solve this problem.
Better code
const mult = [...document.querySelectorAll('[name^=check]:checked')]
.map((_,k) => +dist[k])
.reduce((a,b) => a+b)
but answering your question
You error is likely that you count from 1 here $i = 1;
Change $i = 1; to $i = 0;
Change <th scope="row">'.$i++.'</th> to <th scope="row">'.($i+1).'</th>
move $i++; to the end of the loop
Alternatively change
let i = +"<?php echo $i; ?>";
to
let i = document.querySelectorAll('[name^=check]:checked').length

autosave checkboxes on click

I have my forms in a loop gerating many forms with checkboxes.The choices are submitted via a hidden iframe that runs my php.Can i make this checkboxes autosave to the database ?
<form action='http://www.toppromomkt.com/wp-content/themes/toppromo/insert_wallet.php' method='post' class="my-form" target='hidden-form'>
<input class="styled" type='checkbox' name='pago' value='yes' <?php if ($che=='yes') {echo "checked='yes'"; } else if ($cccc='') {} else {} ; ?> > <br> </div><div class='tb1 tb1_small sc' >
<input class="styled" type='checkbox' name='recibo' value='yes' <?php if ($rec=='yes') {echo "checked='yes'";} else{}; ?> > <br></div><div class='tb1 tb3_md sc '>
<input class="styled" type="hidden" name="contador" readonly value="<?php echo $id_postt1."linha_".$events[0]; ?>">
<input class="styled" type="hidden" name="id_p" readonly value="<?php echo $events[2];?>">
<input type='Submit' class="button white small" value='Salvar' onclick='saved(<?php echo $fid ?>)' />
</form>
You can create a setInterval which will be initialized on click of checkbox and will make an ajax request to save it to DB.
Following is a sample code:
Code
JSFiddle
var formCount = 1;
var saveInterval = null;
var data = []; // Used to mimic DB
function createForm() {
var html = "<form id='frm_" + formCount + "' >"
for (var i = 0; i < 5;) {
html += "<input type='text' name='input_" + ++i + "' /> <br/>";
}
document.getElementById("content").innerHTML += html;
formCount++;
}
function autoSaveInit(el) {
if (el.checked) {
if (!saveInterval) {
saveInterval = setInterval(function() {
saveData();
}, 3000);
}
} else {
window.clearInterval(saveInterval);
saveInterval = null;
}
}
function saveData() {
var forms = document.getElementsByTagName("form");
var _tempObj = {};
// Reset Data for Demo purpose.
data = [];
for (var i = 0; i < forms.length; i++) {
_tempObj = new Object();
_tempObj.formID = forms[i].id;
_tempObj.data = [];
var inputs = forms[i].getElementsByTagName("input");
for (var j = 0; j < inputs.length; j++) {
var name = inputs[j].name;
_tempObj.data.push({
"name": name,
"value": inputs[j].value
});
}
data.push(_tempObj);
}
console.log("Save Completed: ", data);
}
Following is a sample for generating form with auto-save;
<div id="content"></div>
<button onclick="createForm()">Create Form</button>
<input type="checkbox" id="chkAutoSave" onclick="autoSaveInit(this)">
<label for="chkAutoSave">Auto save forms?</label>

AJAX Delete multiple records with checkboxes

I'm performing multiple delete records operation using jQuery and php currently i'm able to delete single / multiple records by clicking on checkbox its working fine as of now but my page gets refreshed every time i delete record because im not using ajax.
I'm a beginner in ajax I want to perform this same operation using JQUERY/AJAX which will not make my page reload every time i delete my record so i want to use ajax for the same code so that i can handle my page reload.
Somebody help me out in achieving it Thanks!!
HTML/PHP
<form method="post" name="data_table">
<table id="table_data">
<tr>
<td>Name</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `products`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['product_title']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
}
?>
</table>
<br />
<input name="submit" type="submit" value="Delete" id="submit">
</form>
JQuery
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
PHP delete code
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `products` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
Please do the changes jquery as
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
Delete.php as
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `test` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
<tr>
<td>ID</td>
<td>TITLE</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `test`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<?php echo $row['name']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
} unset($row);
}

I want to pass a hidden input when a checkbox is checked. I have make my code for this.But it does not work perfectly

<?php
$courses_array = array(
'course_no' => array('E1','E2','E3'),
'course_title' => array('A', 'B', 'C'),
'course_credit' => array('1','2','3')
);
if( !empty($courses_array) ) {
echo "<input type='checkbox' name='select_all' id='select_all' onClick='select_all_courses(this); check_course_registration_level_complete();' /> Select all <span id='error'> Please Select Courses </span> <br />";
}
else {
echo '<b style="color:green;">There is no courses found for you. <br /> If this problem is not desired please contact with your Course Teacher.</b>';
}
foreach( $courses_array['course_no'] as $course ) {
?>
<input type='checkbox' name='course[course_no][]' id='course[course_no][]' onClick='check_course_registration_level_complete(); change_hidden_input(this);' value='<?php echo $course; ?>' /> <?php echo $course; ?>
<input type='hidden' name='course[course_title][]' disabled id='course[course_title][]' value='<?php echo $courses_array['course_title'][ array_search( $course, $courses_array['course_no'] ) ]; ?>'/>
<input type='hidden' name='course[course_credit][]' disabled id='course[course_credit][]' value='<?php echo $courses_array['course_credit'][ array_search( $course, $courses_array['course_no'] ) ]; ?>'/>
<input type='hidden' name='course[course_type][]' disabled id='course[course_type][]' value='<?php echo $courses_array['course_type'][ array_search( $course, $courses_array['course_no'] ) ]; ?>'/>
<?php
}
if( !empty($courses_array) ){
echo "<br /><br /><input type='submit' name='course_registration_complete' value='Submit'>";
}
?>
<script>
function select_all_courses(source){
var checkboxes = document.getElementsByName('course[course_no][]');
for(var i=0, n=checkboxes.length; i<n;i++) {
checkboxes[i].checked = source.checked;
document.getElementById('course[course_title][]').disabled = !(source.checked);
document.getElementById('course[course_credit][]').disabled = !(source.checked);
document.getElementById('course[course_type][]').disabled = !(source.checked);
}
}
</script>
<script>
function change_hidden_input(course){
if(course.checked){
document.getElementById('course[course_title][]').disabled = false;
document.getElementById('course[course_credit][]').disabled = false;
document.getElementById('course[course_type][]').disabled = false;
}else{
document.getElementById('course[course_title][]').disabled = true;
document.getElementById('course[course_credit][]').disabled = true;
document.getElementById('course[course_type][]').disabled = true;
}
}
</script>
<script>
function check_course_registration_level_complete(){
var checkboxes = document.getElementsByName('course[course_no][]');
var ok = false;
count = 0;
for(var i=0, n=checkboxes.length;i<n;i++) {
if( checkboxes[i].checked ) {
ok = true;
count++;
document.getElementById('error').style.display = 'none';
}
}
if( count == checkboxes.length ){
document.getElementById('select_all').checked = true;
}
else{
document.getElementById('select_all').checked = false;
}
if(!ok){
document.getElementById('error').style.display = 'block';
return false;
}
}
</script>

javascript for loop in codeigniter

Here's my view :
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
var batas = $('#bts'+i).val();console.log(batas);
}
});
<input type="hidden" id="<?php echo 'edge'.$items['id']?>" value="<?php echo $items['options']['jum']?>"/>
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i< $length; $i++) {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
?>
$items['options']['jum'] contains = 2.
$stok['stokbagus'] contains = 30 and 21.
It'll display the first one (30). How to display all $stok['stokbagus'] in javascript?
Because i want to compare $(".qty").val() with all of $stok['stokbagus']
Okay. Here is what you should do.
If your $stok['stokbagus'] variable is array, then you should select the first and the second variable like this:
$first = $stok['stokbagus'][0];
$second = $stok['stokbagus'][1];
Else if, your $stok['stokbagus'] variable is a string and has 30,21 like this;
$vars = explode(",", $stok['stokbagus']);
$first = $vars[0];
$second = $vars[0];
You are saying that $stok['stokbagus'] variable has 30 and 21 values then it must be an array.
To show all values in your $stok['stokbagus'];
implode(', ', $stok['stokbagus']; // or just use $er.
Full:
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.implode(', ', $er).'"/>';
Update:
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i < $length; $i++) {
if(is_array($er)) {
foreach($er as $key => $value) {
echo '<input type="text" rel="'.$items['rowid'].'" class="bts" data-id="'.$i.'" value="'.$value.'"/>';
}
} else {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
}
Js:
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
// I don't know what do you want to do with batas variable...
if($('.bts').length > 1) {
$('.bts').each(function(){
console.log($(this).val());
});
} else {
var batas = $('#bts'+i).val();console.log(batas);
}
}
});

Categories