Here i am creating table rows with two dropdowns
`
counter = 0;// Global Variable
function addNewRow(){
counter++;
$('#purchase_order').append('<tr id='+counter+'>' +
'<td>' +
'<select name="code'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id="code'+counter+'">' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM product_packing_relation WHERE sub_cat_id !=0000";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . "PT_".$row['product_type_id']."_".$row['id'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td>' +
'<select name="product'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id=product'+ counter +'>' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM vw_product_packing_relation";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . $row['product_name'].'_'.$row['item_size'].$row['item_unit'].'_'.$row['bundle_type'].'_'.$row['pack_size'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td><input class="form-control" type="test" name=uom'+ counter +' id=uom'+ counter +' /></td>' +
'</tr>');
$("#code"+counter).select2();
$("#product"+counter).select2();
}`
Now i try to do that if user change any dropdown the selected key change the other dropdown here is the code.
`function getItemNamesByTypeID(counter){
event.preventDefault();
var product_packing_id=0;
product_packing_id = $("#code" + counter + " option:selected").val();
if(product_packing_id == 0)
{
product_packing_id = $("#product" + counter + " option:selected").val();
}
alert(product_packing_id);
debugger;
$("#code"+counter).val(product_packing_id);
$("#code"+counter).change();
$("#product" + counter).val(product_packing_id);
$("#product" + counter).change();
return false;
}`
Now the problem is if i change any dropdown it starts calling onchange function infinite times.
Related
enter image description here
Please help me..
auto fill works for the first field
but I have problem in the second row and next row too. When I change the select option on second row, the previous field changed (not same row as what I have changed):
enter image description here
var Nomor = $('#TabelTambahBarang tbody tr').length + 1;
var Baris = "<tr>";
Baris += "<td class='txt-center'>"+Nomor+"</td>"var Baris = "<tr>";
Baris += "<td class='txt-center'>"+Nomor+"</td>";
Baris += "<td>";
Baris += "<select placeholder='Items Name' class='form-control input-sm select2' name='nama_barang[]' id='nama_barang" + Nomor + "' data-Nomor='" + Nomor + "'>";
Baris += "<option disabled value='' name='nama_barang[]' id='nama_barang" + Nomor + "' data-Nomor='" + Nomor + "' selected hidden>-- Silahkan Nama Barang --</option>";;enter code here
<?php
if (!empty($dataBarang)) {
foreach ($dataBarang as $k) { ?>
Baris += "<option value='<?php echo $k->nama_barang; ?>'><?php echo $k->nama_barang; ?></option>";
<?php }
}
?>
Baris += "</select>";
Baris += "</td>";
Baris += "<td class='txt-center'><input class='form-control input-sm' id='harga_barang' placeholder='Harga Barang' name='harga_barang'/></td>";
Baris += "<td align='center'><a id='HapusBaris'>Delete</a></td>";
Baris += "</tr>";
$('#TabelTambahBarang tbody').append(Baris);
Nomor++;
select2();
}
$(document).on("change", ".select2", function(e) {
var select = $(this);
var nama_barang = select.val();
$.ajax({
type : "POST",
url : "<?php echo base_url('get_barang')?>",
dataType : "json",
data : {nama_barang: nama_barang},
cache:false,
success: function(data){
$.each(data,function(harga_barang){
$('[id="harga_barang"]').val(data.harga_barang);
});
}
});
});
function select2(){
$('.select2').select2()
}
Controller
public function get_barang(){
$nama_barang = $this->input->post('nama_barang');
$data = $this->m_testing->get_barang($nama_barang);
echo json_encode($data);
}
Model
function get_barang($nama_barang){
$hsl = $this->db->query("SELECT * FROM tabel_barang WHERE nama_barang='$nama_barang'");
if($hsl->num_rows()>0){
foreach ($hsl->result() as $data) {
$hasil=array(
'nama_barang' => $data->nama_barang,
'harga_barang' => $data->harga_barang,
);
}
}
return $hasil;
}
I have a small javascript which add form-fields dynamically.
My javascript snippet without any php codes works fine.
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />' );
});
});
</script>
But in this script i need an array that read entries from a database for a select option field (dropdown).
I do it like this:
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]' + '">
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
</select><br />'
);
});
});
</script>
It doesn't work. I get the following error
Uncaught SyntaxError: Unexpected token ILLEGAL
What's wrong? Iam very glad for any help.
Regards,
Stefan
You can try this :
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]">' +
+ '<?php $abfrage = "SELECT * FROM artikel"; mysql_query("SET NAMES SET 'utf8'"); $ergebnis = mysql_query($abfrage); while($row = mysql_fetch_object($ergebnis)){?>'
+ '<option value="' + '<?php echo $row->id ?>' + '">' + '<?php echo $row->name ?>' + '</option>'
+ '<?php }?></select></br>'
);
});
});
</script>
I think the error is here
+ '<select name="dynfields3[]' + '">
maybe you intend
+ '<select name="dynfields3[]" >' +
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
+ '</select><br />';
I am wanting output of data from my database to display in a numbered list. Say I have four names in the database. John, suzy, Tom, Linda. I then do a shuffle mix of those names and display them. They appear on my page like this...
undefined John
undefined Suzy
undefined Tom
undefined Linda
I want them to appear as
1 John
2 Suzy
3 Tom
4 Linda
I then want those numbers to send to my database in the order they were in and affiliated with the name they were next to. Right now when they send to my database, each record shows 4, so it is only counting the outputted rows.
I modified my existing script to enable my page to count as a list. However, the count output is not displaying on the page. It shows as undefined, but it is sending as the number 4 to my database.
Why is this not working?
I modified this JS
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
To
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
Full Code
$count = 0;
foreach ($array as $result) :
$count++;
$shuffle_count = $count;
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<input type="hidden" name="count[]" value="<?php echo $shuffle_count; ?>">
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
endforeach;
// only show this button if we have done a shuffle
if ( isset($_POST['shuffle'] ) ) :
echo '<input type="submit" value="Finalize Draft Order" name="insert">';
endif;
?>
</form>
<?php
if (isset($_POST['insert'])) {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$draft_stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, drafted_order, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?, ?)");
if ( false===$draft_stmt1|| false===$draft_stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$draft_stmt2->bind_param('iissss', $shuffle_id, $shuffle_count, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$draft_stmt2->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($draft_stmt2->error));
}
JS
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form[name="form"]').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End test shuffle
$(document).ready(function () {
I've got a form that displays user data in php. Then I've got an input field where the qty should be inputted. Then the JS that executes calculates the total and updates the total input element.
The problem is the referencing to the relevant id element of the input. The JS I have is only referencing to the last element in the php array. So eg the id name is id="qty" . $userid, so for example the id name will be qtyuser001, qtyuser002, qtyuser003, etc, but JS only refers to qtyuser003.
I've been struggling with this for more than a day trying different methods, I can't get it to work. Is there an alternative method I should be approaching to solve this problem?
The php code
$get2 = mysqli_query($con,"SELECT * FROM table WHERE ...");
echo '<form method="post" action="">';
while($row2 = mysqli_fetch_array($get2)) {
$userID = $row2['userID'];
$fn = $row2['FirstName'];
$ln = $row2['LastName'];
echo '<tr>';
echo '<td><input readonly name="userID[]" id="userID ' . $userID . '" value="' . $userID . '"></td>';
echo '<td>' . $fn . ' ' . $ln . '</td>';
echo '<td><input type="text" size="5" name="nrOfQ[]" id="nrOfQ' . $userID . '" onchange="calc()"></td>';
echo '<td><input readonly type="text" size="5" name="total" id="total' . $userID . '"></td>';
echo '</tr>';
}
echo '</table>';
The JS code
<script>
function calc() {
var userid = <?php echo json_encode($userID); ?>;
var myrate = <?php echo json_encode($FieldInterviewerRate); ?>;
var myqty = document.getElementById('nrOfQ' + userid).value;
myResult = myqty * myrate;
var elem = document.getElementById('total' + userid);
elem.value = myResult;
}
</script>
I don't now Javascript that well
your problem that you are not init the JS function each time and you shouldt. The JS code shouldn't depend of PHP and mast be dynamic.
Please Try this
php
$get2 = mysqli_query($con,"SELECT * FROM table WHERE ...");
echo '<form method="post" action="">';
while($row2 = mysqli_fetch_array($get2)) {
$userID = $row2['userID'];
$fn = $row2['FirstName'];
$ln = $row2['LastName'];
echo '<tr>';
echo '<td><input readonly name="userID[]" id="userID ' . $userID . '" value="' . $userID . '">
<input type="hidden" id="myRate' . $userID . '"></td>';
echo '<td>' . $fn . ' ' . $ln . '</td>';
echo '<td><input type="text" size="5" name="nrOfQ[]" id="nrOfQ' . $userID . '" onchange="calc(this)"></td>';
echo '<td><input readonly type="text" size="5" name="total" id="total' . $userID . '"></td>';
echo '</tr>';
}
echo '</table>';
<script>
function calc(obj) {
var id = obj.id;
var userId = id.substr(5);
var myrate = document.getElementById('myRate' + userId).value;
var myqty = document.getElementById('nrOfQ' + userId).value;
myResult = myqty * myrate;
var elem = document.getElementById('total' + userId);
elem.value = myResult;
}
</script>
This is my code:
Category:
<select name='category'>
<?php
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo "<option name={$row[0]} value={$row[1]}>{$row[1]}</option>";
}} ?>
</select> <br><br>
Quantity:
<input type='text' name='quantity' onkeypress="return isNumberKey(event)"><br><br>
Price:
<input type='text' name='price' onkeypress="return isNumberKey(event)"><br><br>
Insert another item
<input type='submit' value='Submit'>
When user clicks on Insert another item, I want to again add Category, Quantity and Price as seen above using Javascript.
Please help.
Just a quick solution without the need of an AJAX request.
<?php
$categories = array();
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
$categories[$row[0]] = $row[1];
}
}
?>
<div id="groups"></div>
Insert another item
<script>
var categories = <?= json_encode($categories) ?>,
groupId = 0;
$(function() {
insertGroup();
$('#insert-another-item').on('click', function() {
insertGroup();
return false;
});
});
function insertGroup() {
group = '<div class="group">'
+ '<select name="groups[' + groupId + '][category]"></select>'
+ '<input type="text" name="groups[' + groupId + '][quantity]">'
+ '<input type="text" name="groups[' + groupId + '][price]">'
+ '</div>';
$('#groups').append(group);
$.each(categories, function(key, value) {
$('select[name="groups[' + groupId + '][category]"]').append('<option value="' + key + '">' + value + '</option>');
});
groupId++;
}