Same Value in the Dynamic jQuery Form - javascript

Hello to all users of the site, my intent was to create a dynamic form for a multiple association of multiple products to the same customer, and I had the idea to implement it with the help of jquery being able to create a dynamic form, so looking on the internet I came across an example on jsFiddle, which works perfectly. The only thing that I need would be not to have an empty input where you can write but an input that has a fixed value. For example, the word "TEST", and every time a new input is generated, the input generated always has the value = "TEST".
How can I do it?
Code (you can copy and paste in your test.html it works!):
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('').focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>
How to put into.val() <?php echo $row['impianto_id'] ;?>
I have this:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM impianti";
$impianti = mysqli_query($connessione, $query_string);
?>
<h4>IMPIANTO ID CAMPAGNA</h4>
<select name="impianto_id_campagna">
<?php
while ($row = mysqli_fetch_assoc($impianti)) { ?>
<option value="<?php echo $row['impianto_id']; ?>">
<?php echo $row['concessionaria']; ?>
</option>
<?php } ?>
</select>
I want to echo this in .val()
But it does not work...
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
var impianto_id = '<?php $row[' impianto_id ']; ?> ';
console.log (impianto_id);
</script>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val(impianto_id).focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>

$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function() {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function(e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('TEST').focus();});// here the test
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function() {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
All you had to do is just add 'test' into the .val() of the input that you created.

Related

Fill html input from sql query using button in PHP

I have 2 inputs with name and surname, from a database I bring all the values ​​and when pressing a button on the form I would like the inputs to be completed with the data. When there is no data left to show, it should throw a warning. I leave the code of what I have done so far.
<?php
function customersData(){
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store= 1150";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $customers;
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
$data=customersData();
?>
<html>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="ficha">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="ficha">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
var btnData = document.getElementById("btnData");
btnData.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>
You probably want to use Ajax, I added JQuery to simplify it.
Try it, and manage your id_store variable.
<?php
function customersData($id) {
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
if (!empty($_GET["get_data"])) {
$data = customersData(intval($_GET["get_data"]));
echo json_encode($data);
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
</head>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="lastname">
</div>
</div>
<button type="button" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
$("#btnData").click(function (ev) {
$.get(window.location.href, {
"get_data": 1150
}, function (result) {
let obj = JSON.parse(result);
$("#name").val(obj.CTE_NAME);
$("#lastname").val(obj.CTE_LASTNAME);
});
});
</script>
</body>
</html>

Is there a way where I can disable my button "Insert" when error appears?

Newbie here. Hello, my target is when error shows up (Not enough balance), the INSERT button will be disabled. I have a input type number whose value must be less than equal to the current wallet, If it's greater than, then error will appear. I have provided the snippet below.
SCRIPT:
$( document ).ready(function() {
$("#box").keyup( function(){
var betAmount = $("#box").val();
var walletAmount = 500; // your session data goes here
var remainingAmount = walletAmount - betAmount;
$("#betAmountResult").text(remainingAmount >=0 ? remainingAmount : 'Error, not enough balance');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a></p>
<input type="submit" name="insert" value="Insert">
</div>
</form>
$(document).ready(function() {
$("#box").keyup(function() {
var betAmount = $("#box").val();
var walletAmount = 500; // your session data goes here
var remainingAmount = walletAmount - betAmount;
if (remainingAmount >= 0) {
$("#betAmountResult").text(remainingAmount);
$("#insert").attr('disabled', false);
} else {
$("#insert").attr('disabled', true);
$("#betAmountResult").text('Error, not enough balance');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a>
</p>
<input type="submit" id="insert" name="insert" value="Insert">
</div>
</form>
Like this
.prop("disabled",not enough)
.prop() vs .attr()
or to remove
.toggle(enough)
I added an ID to the button to access it directly
I also use .on("input" which is more generic (handles paste for example)
$(function() {
$("#box").on("input",function() {
const betAmount = $("#box").val(),
walletAmount = 500, // your session data goes here
remainingAmount = walletAmount - betAmount,
enough = remainingAmount >= 0;
$("#betAmountResult").text(enough ? remainingAmount : 'Error, not enough balance');
$("#insert").prop("disabled",!enough); // disable
// $("#insert").toggle(enough); // remove
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<form method="POST" action="<?php echo base_url();?>auth/form_validation">
<input type="number" placeholder="Enter Amount" name="bet" class="form-control" id="box" required>
<!-- change id's name to betAmount -->
<p>CURRENT WALLET: <a style="color:blue;">500</a></p>
<p class="remaining">REMAINING BALANCE:
<a class="p-1" id="betAmountResult"></a>
</p>
<input type="submit" name="insert" id="insert" value="Insert">
</div>
</form>

How can I make a form displayed only under its parent?

I'm creating a comment-reply function where I would like the reply-form to show up under its parent when users presses the "Reply"-button.
Right now my code makes the form show up under every comment and not only the specific "parent-comment-reply-button". How can I avoid the form on other comments?
My code looks like this:
HTML
<head>
<?php
include ('headCont.php');?>
</head>
<body>
<?php
include('navBar.php');?>
<div class="container">
<div class="row">
<div class="box">
<div>
<!------------container------->
<form action="" method ="POST">
Namn: <br>
<input type="text" name ="name"><br>
Kommentar: <br>
<textarea name="comment" placeholder="Ställ en fråga" rows="10" cols="20"></textarea><br>
<input type ="submit" name ="submit" value="Skicka">
</form><br>
</div>
<div>
<?php
include ('commentBox/storeComments.php');
include ('commentBox/getComments.php');?>
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer>
<?php
include ('footer.php');
?>
</footer>
<!-- jQuery -->
<script src="jsOld/jquery.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
$("#show").click(function(){
$(".reply-form").show();
});
$("#hide").click(function(){
$(".reply-form").hide();
});
});
</script>
getComments
<?php
include ('connectDB.php');
if($connect){
mysqli_select_db($connect, "comments");
$query2 = "SELECT * FROM data ORDER BY `id` DESC";
$result = mysqli_query($connect, $query2);
$comments = array();
while($row = mysqli_fetch_array($result)){
$name = $row['name'];
$comment = $row['comment'];
$date = $row['date'];
echo "
<div style='width:60%' class='col-lg-12'>
<div class='panel panel-default'>
<div class='panel-heading'>
<strong> $name </strong><span style='float:right'class='text-muted'>$date</span>
</div>
<div class='panel-body'>$comment
<button id='show' style='float:right'>Reply</button>
</div>
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->";
echo " <div class='col-lg-12 padd'>
<form method='POST' action='' class='reply-form'>
Namn:<br>
<input name='_method' type='text'</input><br>
Kommentar:<br>
<textarea name='reply_comment' cols='50' rows='10'></textarea>
<div class='button-group'>
<input type='submit' name='submit_reply' value='Skicka'></input>
<button id='hide' type='submit' name='close' value='Stäng'>Stäng</input>
</div>
</form>
</div>";
}
}
?>
Output
You need to create the form inside the parent DOM. Which means, the following like should be at the end of the your send echo statement. And the .reply-form should be hidden initially using css.
</div><!-- /col-sm-5 -->";
The HTML IDs show and hide can appear multiple times in your DOM, keep in mind that HTML ids should be unique. So it would be best to change it to classes.
Now to the answer your question you could try to add a counter, this basically connects the form to the show button, example:
<button id='show' style='float:right' data-counter="0">Reply</button>
<form method='POST' action='' class='reply-form reply-form-0'>
$("#show").click(function(){
var counter = $(this).data("counter");
$(".reply-form-"+counter).show();
});

Change image according to id in mysql

Good Day, I am working on a simple project so that I could get used to php,mysql,
Here is my code
PHP
if(isset($_POST["edit"]))
{
$update_data = array(
'crit_1' => mysqli_real_escape_string($data->con, $_POST['crit_1']),
'crit_2' => mysqli_real_escape_string($data->con, $_POST['crit_2']),
'crit_3' => mysqli_real_escape_string($data->con, $_POST['crit_3']) ,
);
$where_condition = array(
'id' => $_POST["id"]
);
if($data->update("tbl_tabulation", $update_data, $where_condition))
{
header("location:index.php?updated=1");
}
}
if(isset($_GET["updated"]))
{
$success_message = 'Post Updated';
}
?>
And my HTML:
<div id="pagewrap">
<section id="content">
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "img/new.jpg";
}
function pic2()
{
document.getElementById("img").src ="img/new2.gif";
} </script>
<div class="table-responsive">
<div class="list-group">
cand1
cand2s
</table>
</div>
</section>
<section id="middle">
<img src="" id="img">
<img src="" id="img">
</section>
<aside id="sidebar">
<form method="post">
<?php
if(isset($_GET["edit"]))
{
if(isset($_GET["id"]))
{
$where = array(
'id' => $_GET["id"]
);
$single_data = $data->select_where("tbl_tabulation", $where);
foreach($single_data as $post)
{
?>
<label width="20%"><?php echo $post["cand_name"]; ?></label>
<br />
<!--CRITERIA -->
<label>Poise & Bearing</label>
<input type="text" name="crit_1" value="<?php echo $post["crit_1"]; ?>" class="form-control" width="20%" />
<br />
<label>Modeling</label>
<input type="text" name="crit_2" value="<?php echo $post["crit_2"]; ?>" class="form-control" width="20%"/>
<br />
<label>Overall Impact</label>
<input type="text" name="crit_3" value="<?php echo $post["crit_3"]; ?>" class="form-control" width="20%"/>
<br />
<input type="hidden" name="id" value="<?php echo $post["id"]; ?>" />
<input type="submit" name="edit" class="btn btn-info" value="Edit" />
<?php
}
}
}
else
{
}
?>
<span class="text-success">
<?php
if(isset($success_message))
{
echo $success_message;
}
?>
</span>
</form>
</aside>
<footer>
<h4>Footer</h4>
<p>Footer text</p>
</footer>
</div>
Problem is When I click cand1 or cand2the image will show only for a second. And the middle will be empty again as soon as the URL changes.
Is there any work around for this? any help would be appreciated.
Change this:-
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "img/new.jpg";
}
function pic2()
{
document.getElementById("img1").src ="img/new2.gif";
} </script>
<section id="middle">
<img src="" id="img">
<img src="" id="img1">
</section>
The id shouldn't be the same, id should be unique
Because you are using below code for immediate update and redirect page to updated=1 if you don't want to redirect then use ajax
if($data->update("tbl_tabulation", $update_data, $where_condition))
{
header("location:index.php?updated=1");
}
You need to prevent the default action of the link if you want just the image to change:
cand1
cand2s
If that isn't what you want, then you need to change the image by index.php when it loads the news page. Other options are to use event.preventDefault():

After selecting the value from dropdown list then it shows no any value next time

Not working :- After selecting the value from dropdown list then after submitting it shows no any value next time.
Working :- But the last selected value is saved in session. If page is refreshed the session value shown as selected in dropdown list.
Working :- After any keyword is submited the value in dropdown must show.
Please give me solution to make first one work. I have done it using POST.
Here is my code:-
<?php
session_start();
$selected='';
$offer_type_selected='';
function get_options($select)
{
$incent_type=array('All'=>'none','Incent'=>'Incent','Non-Incent'=>'Non-Incent');
$options='';
while(list($k,$v)=each($incent_type))
{
if($select==$v)
{
$options.='<option value="'.$v.'" selected>'.$k.'</option>';
}
else
{
$options.='<option value="'.$v.'">'.$k.'</option>';
}
}
return $options;
}
if(isset($_POST['incent_type']))
{
$selected=$_POST['incent_type'];
echo $selected;
$_SESSION['incent_type']=$selected;
}
?>
<body link="white">
<div class="container">
<div class="content" >
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<div class="label_div">Type a keyword :</div>
<div class="input_container">
<input type="text" name="subquery" id="name_id" onkeyup="autocomplet()">
<ul id="name_list_id"></ul>
</div>
<div class="lable_div" >
<input type="submit" class="submit_query" name="submit_id" value="Submit Query" >
Select Incent Type :<select class="custom-dropdown" name="incent_type" onchange="this.form.submit();">
<?php
$flag=0;
if(isset($_POST['subquery']))
{
if(strcmp("",$_POST['subquery'])!=0)
{
unset($_SESSION['incent_type']);
unset($_SESSION['offers_type']);
echo get_options('none');
$flag=1;
}
}
else if(isset($_SESSION['incent_type']) && $flag==0)
echo get_options($_SESSION['incent_type']);
else if($flag==0)
echo get_options('none');
?>
</select>
</div>
</form>
</div>
</div>
You have problem with checking $_POST['subquery'], you all time getting true this - if(isset($_POST['subquery'])), try change to if(!empty($_POST['subquery']))
Also you can remove session and some if:
<?php
function get_options($select=null)
{
$incent_type=array('All'=>'none','Incent'=>'Incent','Non-Incent'=>'Non-Incent');
$options='';
foreach($incent_type as $k=>$v){
$options.='<option value="'.$v.'" '.(!empty($select) && $select==$v?"selected":"").'>'.$k.'</option>';
}
return $options;
}
?>
<body link="white">
<div class="container">
<div class="content" >
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<div class="label_div">Type a keyword :</div>
<div class="input_container">
<input type="text" name="subquery" id="name_id" onkeyup="autocomplet()">
<ul id="name_list_id"></ul>
</div>
<div class="lable_div" >
<input type="submit" class="submit_query" name="submit_id" value="Submit Query" >
Select Incent Type :<select class="custom-dropdown" name="incent_type" onchange="this.form.submit();">
<?php
echo get_options(empty($_POST['subquery'])?$_POST['incent_type']:null);
?>
</select>
</div>
</form>
</div>
</div>

Categories

Resources