form dropdown required codeigniter - javascript

i have code like this
<div class="col-sm-9">
<?php $attributes = 'class = "form-control" id = "actype"';
echo form_dropdown('actype',$actype,set_value('actype',$detail[0]>activity_type),$attributes);?>
</div>
my model:
function get_actype()
{
$type_id = array('-SELECT-');
$type_name = array('-SELECT-');
for ($i = 0; $i < count($result); $i++)
{
array_push($type_id, $result[$i]->activity_type_id);
array_push($type_name, $result[$i]->activity_type_name);
}
return $actype_result = array_combine($type_id, $type_name);
}
how to create validate dropdown required

Related

Have two variables in one foreach bad insert

Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired
I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}

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

How to change star rating color on mouseenter, on mouseout, and on onclick

I need fa fa-star class's mouseenter, mouseout, and onclick function work for each specific 'list' class/li tag(like list class[0, 1, 2, etc]). What I have now is working for every 'list' class. When I mouseenter on a star from different list class the 1st list class's star is changing.
If I mouseenter on a star from 1st list class/li tag the mouseenter function should work for that list class/li tag not for other 'list' class/li tag. if 2nd 'list' class then it should work for that 'list' class/li tag not for others. and for 3rd, 4th etc.
in rateclick function I can send the rating to server but can't fetch it. Can you look into it also?
Here is the code:
index.php and style.css
.fa{
font-size:25px;
}
li{
list-style:none;
padding-left:40px;
padding-bottom:40px;
border-bottom:2px solid #ccc;
width:800px;
}
li:last-child{
border-bottom:none;
}
<?php
require "conx.php";
$sql = "SELECT * FROM customers ORDER BY id ASC";
$query = $conx -> query($sql);
$numrows = $query -> num_rows;
?>
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<script src="jquery.min.js"></script>
<body>
<div class="Insert-Into">
<ul>
<?php if($numrows > 0): ?>
<?php while($row = $query -> fetch_assoc()): ?>
<?php $rating = $row["rating"]; ?>
<?php $customerid = $row["id"]; ?>
<li data-rating=<?php echo "$rating"; ?> data-customerid=<?php echo $customerid; ?> class="list">
<br/>
<br/>
<span class="username"><?php echo $row["username"]; ?></span>
<br/>
<br/>
<?php
$i;
$color;
for($i = 1; $i <= 5; $i++){
if($i <= $rating){
$color = "color:orange";
}
else{
$color = "color:#ccc";
}
echo "<i class='fa fa-star' style='$color;' data-rating='$i' onmouseenter='mouseenterrating($i)' onmouseout='clearstar($rating)' onclick='rateclick($customerid, $i)'></i>";
}
?>
<br/>
<br/>
<b>Description</b>
<br/>
<br/>
<div class="desc"><?php echo $row["description"]; ?></div>
</li>
<?php endwhile; ?>
<?php endif; ?>
</ul>
</div>
<script>
function mouseenterrating(count){
var j;
var fa = document.getElementsByClassName("fa");
for(j = 0; j < fa.length; j++){
if(j < count){
fa[j].style.color = "orange";
}
else{
fa[j].style.color = "#ccc";
}
}
}
function clearstar(rating){
var fa = document.getElementsByClassName("fa");
var k;
for(k = 0; k < fa.length; k++){
if(k < rating){
fa[k].style.color = "orange";
}
else{
fa[k].style.color = "#ccc";
}
}
}
function rateclick(customerid, count){
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "rating.php?id="+customerid+"&rate="+count);
xhttp.send();
fetch(customerid);
}
function fetch(e){
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "fetch.php");
xhttp.send();
}
</script>
</body>
</html>
rating.php
<?php
require "conx.php";
if(isset($_GET['id']) && isset($_GET['rate'])){
$customerid = $_GET['id'];
$rate = $_GET['rate'];
$sql = "UPDATE customers SET rating = '$rate' WHERE id = '$customerid'";
$result = $conx -> query($sql);
}
?>
fetch.php
<?php
require "conx.php";
$sql = "SELECT * FROM customers WHERE id = '".customerid."'";
$result = $conx -> query($sql);
$fetch = $result -> fetch_assoc();
?>
conx.php
<?php
$conx = mysqli_connect("localhost", "root", "");
if(!$conx){
echo "Not connected with localhost";
}
$sql = "CREATE DATABASE rating";
$query = $conx -> query($sql);
$dbselect = $conx -> select_db("rating");
if(!$dbselect){
echo "No database selected";
}
$sql = "CREATE TABLE customers(id INT(255) NOT NULL AUTO_INCREMENT UNIQUE KEY, username VARCHAR(200) NOT NULL, description VARCHAR(1000) NOT NULL, email VARCHAR(200) NOT NULL PRIMARY KEY, rating INT(5) NOT NULL)";
$query = $conx -> query($sql);
?>
Building on your initial attempt I have this solution for you:
function onMouseEnter(index){
var fa = document.getElementsByClassName("fa");
var j;
for(j = 0; j < fa.length; j++){
if(j < index){
fa[j].style.color = "orange";
}
else{
fa[j].style.color = "#ccc";
}
}
}
function onMouseOut(){
var fa = document.getElementsByClassName("fa");
var k;
for(k = 0; k < fa.length; k++){
fa[k].style.color = "#ccc";
}
}
Demo

Edit input name when chceckbox clicked

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 :/

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