How to add dynamic ids to text boxes? - javascript

I'm trying to assign id's to some text fields that's getting created dynamically in a loop.
The div which is in the loop that consists of the text fields.
<!-- DATA ENTERED IN THIS TEXT BOX WILL BE REFLECTED IN ALL THE TEXT BOXES CREATED IN THE LOOP-->
<div class="col-sm">
<h5><span class="badge badge-dark">Add Quantity:</span></h5>
<input class="form-control" type="text" name="add0" id="add0" onkeyup="sync()">
</div>
<!-- SCRIPT FOR REFLECTING DATA -->
function sync()
{
var add0 = document.getElementById('add0');
var add1 = document.getElementById('add1');
var add2 = document.getElementById('add2');
var add3 = document.getElementById('add3');
var add4 = document.getElementById('add4');
var add5 = document.getElementById('add5');
var add6 = document.getElementById('add6');
var add7 = document.getElementById('add7');
var add8 = document.getElementById('add8');
add8.value = add7.value = add6.value = add5.value = add4.value = add3.value = add2.value = add1.value = add0.value;
}
<?php
<!-- GETS AN ARRAY OF DATA SCANNED IN THE PREVIOUS PAGE -->
$strings = explode(PHP_EOL,($_SESSION['grid']));
$sa = [];
foreach ($strings as $s) {
array_push($sa, "'".$s."'");
}
$d=implode(',', $sa);
<!-- SQL QUERY -->
$sql = "select distinct size from items where main_group IN(select distinct main_group from items where addl_item_code_barcode IN ($d)) ORDER BY size";
$result = pg_query($db, $sql);
?>
<div class="row">
<!-- THIS LOOP WILL CREATE 8 DIV'S BECAUSE THERE ARE 8 SIZES 36-50 -->
<?php while($res = pg_fetch_assoc($result)){ ?>
<div class="col-md-2 show-hide">
<input type="text" value="<?php echo $res['size']; ?> " readonly
style="background-color: #F5F5F5;" class="form-control"/>
<!-- // OUTPUT WILL BE GENERATED HERE -->
<div id="addition"></div>
<select class="form-control">
<option>25%</option>
<option>50%</option>
<option>100%</option>
</select><br>
</div>
</div>
<br>
<br>
<button type="submit" value="submit" class="btn btn-primary"><i class="fas fa-paint-brush"></i>Apply</button>
</form>
<?php }?>
<!-- The script that I tried for assigning unique id's -->
$(document).ready(function() {
for( var i=1; i<9; i++) //i<9 because that's the maximum number of
// text fields to be created is 8.
{
$('#addition')
.append('<input class="form-control" type="text" name="add" id="add'+i+'" />');
}
The problem is that this script creates a series of text boxes only in the first iteration of the while loop.
Here's how it looks.
Here this output is creating all the 8 text boxes below the 'size' field i.e, '36'. How do I get the 2nd text box below 38 and the 3rd below 42 and so on...
Is there a way only create the id's dynamically and append it in the input area, instead of putting the input itself in the loop like I have done?

var text = "";
for(var i=0;i<11;i++)
{
text += '<input class="form-control" type="text" name="add" id="add_'+i+'" /></br>';
}
$("#addition").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addition"></div>

You can set the id within the while-loop, but you have to set an unique id. Maybe you should include the loop-iterator in the id. Try following example:
<?php while($res = pg_fetch_assoc($result)){ ?>
<div class="col-md-2 show-hide">
<input type="text" id="field<?php echo $res['size']; ?>" value="<?php echo $res['size']; ?> " readonly
style="background-color: #F5F5F5;" class="form-control"/>
<div id="addition"></div> // OUTPUT WILL BE GENERATED HERE
<select class="form-control">
<option>25%</option>
<option>50%</option>
<option>100%</option>
</select><br>
</div><?php }?>

Related

Javascript value not visible in input field value

I have two forms on my page, and I want to pass the data from one input field to another input field using javascript. If the radio input is checked in the first form, the input value should get this value.
My forms:
<form name="news-form" action="p" method="post">
<section id="section-list" style="">
<hr class="solid">
<?php
$text = "";
$headline = "";
$shortdescription = "";
$description = "";
$linktext = "";
$link = "";
$newsID = "";
$xml=simplexml_load_file($xmlurl)or die("Kann keine Verbindung zu $xmlurl aufbauen");
foreach($xml->children() as $news):
$newsID = $news->ID;
?>
<div name="idsection" title ="<?php echo $newsID; ?>">
<section>
<div class="divID">
<label class="label-idnumber">Eintrag Nummer: <?php echo $news->ID; ?> </label>
<input id="NewsID" type="radio" name="NewsID" value="<?php echo $newsID; ?>"></input>
</div>
</section>
.
.
.
.
.
</form>
<form name="newsEntryBea-form" action="" method="post">
<section id="section-bea" style="">
<hr class="solid">
<section>
<div style="float:left;">
<label for="idnumberBea" class="label-header">Eintrag Nummer</label>
<input id="idnumberBea" name="idnumberBea" type="text" value="" readonly> </input>
</div>
</section>
.
.
.
.
.
</form>
My script code:
<script>
function inputToggle(e) {
var sectionnumbers = document.getElementsByName('idsection');
var sectionnumber;
var idnumbers = document.getElementsByName('NewsID');
var idnumber;
for(var i = 0; i < idnumbers.length; i++){
if(idnumbers[i].checked){
idnumber = idnumbers[i].value;
for(var i = 0; i < sectionnumbers.length; i++){
sectionnumber = sectionnumbers[i].title;
if(sectionnumber === idnumber){
document.getElementsByName('idnumberBea').value = idnumber;
console.log("Mein Text im Feld idnumberBea: " + document.getElementsByName('idnumberBea').value);
}
}
console.log("Meine NewsID Nummer: " + idnumber);
}
}
}
</script>
So in the console I get all my values correctly shown, but in the HTML form the value is not displayed.
Can anybody tell what is wrong here?
when you use getElementsByName it get element as an array so you should select the element you want in array like below code document.getElementsByName('idnumberBea')[0].value
var idnumber="hello world"
document.getElementsByName('idnumberBea')[0].value = idnumber;
<input type="text" name="idnumberBea">
You have built a loop inside a loop. in the inner loop you declare variable i again. give here another variable name. then i would think it is better to use let instead of var. To prevent a scope problem in such a case.
First of all, you should check you HTML structures of forms, like closing well the objects and check the input tags and how to use them, couse you are closing them when you should not.
Here is what i got with static values, you have to change the values fields with your php variables:
var radioInput_form1 = document.getElementById('NewsID')
var inputText_form2 = document.getElementById('idnumberBea')
radioInput_form1.addEventListener('click', function(){
inputText_form2.value = radioInput_form1.value
})
<form name="news-form" action="p" method="post">
<section id="section-list" style="">
<hr class="solid">
<div name="idsection" title ="The Title"></div>
<section>
<div class="divID">
<label class="label-idnumber">Eintrag Nummer: 15 </label>
<input id="NewsID" type="radio" name="NewsID" value="15">
</div>
</section>
.
.
.
.
.
</section>
</form>
<form name="newsEntryBea-form" action="" method="post">
<section id="section-bea" style="">
<hr class="solid">
<section>
<div style="float:left;">
<label for="idnumberBea" class="label-header">Eintrag Nummer</label>
<input id="idnumberBea" name="idnumberBea" type="text" value="" readonly>
</div>
</section>
</section>
</form>

Jquery autocomplete combo box/selectbox using codeigniter

I want to ask, has someone ever created autocomplete using combo box / select box with code igniter?
I've tried but only managed to use autocomplete for 2 input text but I have another idea to create autocomplete with text combined with combo box. I've do created that but I have trouble my autocomplete in the text is successful but in the combo box does not work only show empty option. can someone help me? this is my source code
My Table : i probably using 2 table for autocomplete : 1. tb_produk and 2. tb_kategori_produk
https://imgur.com/a/xpysI | 2. https://imgur.com/a/DVgUl
My Controller : user.php
public function request_produk(){ //used for calling view
$data["kateprod"] = $this->db->where("f_status_kategori_produk","1")
->get("tb_kategori_produk")->result_array();
$this->theme->panel('user/v_request',$data);
}
public function mesin() //user for jquery called data
{
$keyword = $this->uri->segment(3);
$data = $this->db->from('tb_produk')->join('tb_kategori_produk','tb_kategori_produk.f_id_kategori_produk=tb_produk.f_kategori_produk')->like('f_nama_produk',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->f_nama_produk,
'idpro' =>$row->f_id_produk,
'idkate' =>$row->f_id_kategori_produk,
'kategori'=>$row->f_nama_kategori_produk
);
}
echo json_encode($arr);
}
My Controller : v_request.php
<div id="content">
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function() {
$(".autocomplete").autocomplete({
serviceUrl: site+"/user/mesin",
onSelect: function (suggestion) {
$("#v_idproduk").val(""+suggestion.idpro);
$("#v_kategori").val(""+suggestion.kategori);
$("#v_idkategori").val(""+suggestion.idkate);
}
});
});
</script>
<?php $id = $this->session->userdata('f_id_user');
<input type="hidden" name="dt[f_id_user]" value="<?php echo $this->session->userdata('f_id_user'); ?>">
<input type="hidden" id="v_idproduk" name="dt[f_id_produk]">
<input type="hidden" id="v_idkategori" name="dt[f_kategori_produk]">
<div class="form-group br-form"> <!-- This form group i used to autocomplete text -->
<div class="col-md-2">
<label class="control-label">Nama Mesin</label>
</div>
<div class="col-md-10">
<input type="search" class="autocomplete form-control" id="autocomplete1" name="nama_mesin" required/>
</div>
</div><br><br>
<div class="form-group br-form"> <!-- This form group i used to autocomplete combo box-->
<div class="col-md-2">
<label class="control-label">Kategori Mesin</label>
</div>
<div class="col-md-10">
<select id="v_kategori" name="dt[f_kategori_produk]" class="form-control" required>
<option value="">---Harap Pilih---</option>
<?php foreach ($kateprod as $key) { ?>
<option value="<?=$key['f_id_kategori_produk']?>" id="v_kategori"><?php echo $key["f_nama_kategori_produk"];?></option>
<?php } ?>
</select>
</div>
</div><br>
This is my demo
https://streamable.com/wvn25

Issue posting form via AJAX

I have the following form which I then send upon submit via AJAX to insert to a MySQL DB through Ajax. All inputbox in form have their own Id and I get them all in my .php process file except the ones "cas" and "dat" that do not seem to go through the AJAX posting process.
The form:
<form id="form">
<div class="form-group">
<label class="lab" for="nm">id</label>
<input disabled type="text" id="id" name="id" class="form-control" placeholder="Id">
</div>
<div class="form-group">
<input type="text" class="form-control" name="cas" id="cas" value="2">
<input type="text" class="form-control" name="dat" id="dat" value="2017-11-30">
</div>
<div class="form-group">
<label class="lab" for="nm">Product</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM product_family order by product_type_id ASC","form-control","nm","nm","Select Product", "product_family", "product_family");?>
</div>
<div class="form-group">
<label class="lab" for="em">Win</label>
<input type="text" id="em" name="em" class="form-control allow_decimal" placeholder="Win">
</div>
<div class="form-group">
<label class="lab" for="hp">Drop</label>
<input type="text" id="hp" name="hp" class="form-control allow_decimal" placeholder="Drop">
</div>
<div class="form-group">
<label class="lab" for="ad">Currency</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM currency order by id ASC","form-control","ad","ad","Select Currency", "currency", "currency");?>
</div>
<button type="button" id="save" class="btn btn-success" onclick="saveData()">Save</button>
<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
</form>
I then have the following JavaScript code triggering the Insert upon "save data" click in order to post the different inputbox values to my .php processing file:
function saveData(){
var id = $('#id').val();
var name = $('#nm').val();
var email = $('#em').val();
var phone = $('#hp').val();
var address = $('#ad').val();
var casino = $("#cas").val()
var date = $("#dat").val();
$.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address, cas:casino, dat:date}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function viewData(){
$.get('server.php', function(data){
$('tbody').html(data)
})
}
Then I try to read my "$_post" values on the PHP side:
if($page=='add'){
try{
$id = $_POST['id'];
$nm = $_POST['nm'];
$em = $_POST['em'];
$hp = $_POST['hp'];
$ad = $_POST['ad'];
$casino_id = $_POST['cas'];
$date = $_POST['dat'];
}
I perfectly get all variables except the dat and cas posts that do no appear in the $_post list. Listing all $_Post the following way:
$myfile = fopen("LOGPOST.txt", "w") or die("Unable to open file!");
foreach ($_POST as $key => $value){
$txt= $txt."{$key} = {$value}//";
gives the following output: id = //nm = F&B Sales//em = 1000//hp = 500//ad = EUR//
What am I doing wrong?

JS function to create a dropdown filled with names from a DB onclick?

I need help writing this small piece of code. I need a function that creates a dropdown menu that is filled with names from a Database when a button is clicked. The names in the dropdown list will eventually be submitted to a different table in the database, so I need to know how to set the names as "vales" in the dropdown list also. What would be the best way to go about implementing these issues? I've commented out where I think things should go.
Javascript:
var room = 1;
function ReviewForm() {
room++;
var objTo = document.getElementById('ReviewForm')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + room);
var rdiv = 'removeclass' + room;
divtest.innerHTML =
'<hr>' +
'<h2>Student:</h2>' +
'<select>' +
//Instead of these three names, I need to use the DB's info go generate the text and values
'<option value="Adam">Adam</option> ' +
'<option value="Bob">Bob</option> ' +
'<option value="Cat">Cat</option>' +
'</select></h2>' +
objTo.appendChild(divtest)
PHP:
<?php
$NumberOfStudents = "";
// $NumberOfStudents=$_GET['SelectedStudents'];
$hostname = "host";
$username = "user";
$password = "pass";
$databaseName = "_db";
$conn ;
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
/*if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} */
//BELOW IS THE QUERY FROM THE DB THAT I AM TRYING TO GET TO REPRINT EACH TIME THE FUNCTION IS CALLED
$query = "SELECT concat (FirstName,' ', LastName) as StudentNames FROM `Student`";
$result = mysqli_query($connect, $query);
?>
HTML:
<body>
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<div id="main">
<div class="inner">
<!-- Content -->
<section>
<!-- Form -->
<form method="post" action="#">
<div class="row uniform">
<!-- Break -->
<div class="12u$">
<div style="height:550px;border:1px solid #ccc;font:16px/26px Georgia, Garamond, Serif;overflow:auto;"><!-- container for reviews-->
<div id="ReviewForm">
<hr>
<h2>
Student:
<select>
<!-- It is hardcoded into the page here, which is fine, but I would rather it generate when the page is loaded, and then can
be called again each time a new dropdown is needed. -->
<?php while($row1 = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row1['StudentNames'];?>"><?php echo $row1['StudentNames'];?></option>
<?php endwhile;?>
</select>
</h2>
</div>
</div>
</form>
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1"></label>
<div class="controls" id="profs">
<form class="input-group-btn">
<div>
<!--Here is the button that calls the function for a new dropdown menu-->
<button class="btn btn-success" type="button" onclick="ReviewForm();">Add another student</button>
</div>
</form>
<br>
<br>
</div>
</div>
</section>
</div>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>

Using livesearch textbox twice in a same page

I have used the below code for Livesearch in my webpage and it works fine in the student form. But in the index page for second text box(Staff form), live search is not working. I hope this is due to the use of JQuery function using attribute ID which is same for both input text box. Is there anyway to make the live search work in second text box without changing the entire code?
Thanks in advance
livesearch.js
$('#college').keyup(function(e)
{
if ( key != 40 && key != 38 && key != 13 ) livesearch();
}
function livesearch() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $.trim($('#college').val());
if (keyword.length >= min_length) {
$.ajax({
url: 'livesearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#college_list').show();
$('#college_list').html(data);
}
});
} else {
$('#college_list').hide();
}
}
index.php
<div id="student">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
<!-- Another Division similar to previous one-->
<div id="staff">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
livesearch.php
$parts = explode(' ', $keyword);
$p = count($parts);
$sql = "SELECT * FROM colleges WHERE college_id is not null";
for($i = 0; $i < $p; $i++) {
$sql .= " AND college_name LIKE '%$parts[$i]%'";
}
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// Highlight the written text
$college_name = highlight($keyword,$rs['college_name']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'",
$rs['college_name']).'\')">'.$college_name.'</li>';
}
You're targeting elements with an id - in the first line:
$('#college').keyup(function(e) { ... }
If you switch that to a class, such as .live-search and add this class to your HTML element, the script should naturally work on multiple elements.
ID's in HTML should be unique, whereas classes can be applied to multiple elements.
Update: You might also need to switch this line:
var keyword = $.trim($('#college').val());
To reference this instead:
var keyword = $.trim($(this).val());
This will ensure that when you detect a keyup on that element, that the script acts upon that one particular element.

Categories

Resources