Select2 Not active - javascript

<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.

There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +

Related

onchange function calling infinity times

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.

Count like and unlike php

I written a simple script where users can post without sign up or log in, something like conffesion website, people can post and get like and unlike on their posts. I want to count like then sort by most popular and most newest and show it on a main page, and I tried literally everything but nothing seems to work, heres my code:
comment-like-unlike.php
?php
require_once ("db.php");
$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}
$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (! empty($row))
{
$query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
$query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-add.php
<?php
require_once ("db.php");
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
get-like-unlike.php
<?php
require_once ("db.php");
$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
And my index.php code for posts and likes:
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId"
placeholder="Name" /> <input class="input-field"
type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment"
id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<font color="white"><input type="button" class="btn-submit" id="submitButton"
value="Publish" /></font>
</div>
</form>
</div>
<div id="output"></div>
<script>
var totalLikes = 0;
var totalUnlikes = 0;
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
parent = data[i]['parent_comment_id'];
var obj = getLikesUnlikes(commentId);
if (parent == "0")
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a>\
</div>\
<div class='post-action'>\ " + like_icon + " \
<span id='likes_" + commentId + "'> " + totalLikes + " likes </span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$("#output").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
var obj = getLikesUnlikes(data[i].comment_id);
if (commentId == data[i].parent_comment_id)
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
var comments = "\
<div class='comment-row'>\
<div class='comment-info'>\
<span class='commet-row-label'>from</span>\
<span class='posted-by'>" + data[i]['comment_sender_name'] + "</span>\
<span class='commet-row-label'>at</span> \
<span class='posted-at'>" + data[i]['date'] + "</span>\
</div>\
<div class='comment-text'>" + data[i]['comment'] + "</div>\
<div>\
<a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a>\
</div>\
<div class='post-action'> " + like_icon + " \
<span id='likes_" + data[i]['comment_id'] + "'> " + totalLikes + " likes </span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
function getLikesUnlikes(commentId)
{
$.ajax({
type: 'POST',
async: false,
url: 'get-like-unlike.php',
data: {comment_id: commentId},
success: function (data)
{
totalLikes = data;
}
});
}
function likeOrDislike(comment_id,like_unlike)
{
$.ajax({
url: 'comment-like-unlike.php',
async: false,
type: 'post',
data: {comment_id:comment_id,like_unlike:like_unlike},
dataType: 'json',
success: function (data) {
$("#likes_"+comment_id).text(data + " likes");
if (like_unlike == 1) {
$("#like_" + comment_id).css("display", "none");
$("#unlike_" + comment_id).show();
}
if (like_unlike == -1) {
$("#unlike_" + comment_id).css("display", "none");
$("#like_" + comment_id).show();
}
},
error: function (data) {
alert("error : " + JSON.stringify(data));
}
});
}
</script>
comment-list.php
<?php
require_once ("db.php");
$memberId = 1;
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
?>
Im really looking forward for some help, ive been working on this script for a while and this is the last thing I need before launching, thanks in advice!
Here's a picture of a website, just to see how its working
You should write your query in comment-list.php like this
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY tbl_like_unlike.like_unlike DESC, tbl_comment.date DESC";
This will automatically sort your data to have comment with most likes on top and then sort by the newest date. So if a comment has the same amount of likes of another comment, the newest will show up on top.
COMMENT RESPONSE
You can do it in javascript like this:
for (var i = 0; i < data.length; i++) {
if(i == 0) {
//put comment at top of page
} else {
// Put comment in normal place
}
}

Jquery Append on Click doesn't work. It instantly remove appended item

I have two select tags. When I click a link, I want the chosen option get appended to the other select, but after it appends it remove it instantly. Heres my code.
<select id="senroll" multiple="multiple" name="esubject">
</select><br /><br />
<label for="lsubject">Subject List</label></br>
<select id="slist" multiple="multiple" name="lsubject">
<?php foreach($slist as $subject): ?>
<?php echo "<option value='" . $subject['s_id'] . "'>" .
$subject['sname'] . "</option>"; ?>
<?php endforeach; ?>
</select><br /><br />
Enroll
Remove
Here my jquery Code:
$(document).ready(function(){
$('#enroll').on('click', function(){
var id = $('#slist').val();
var snames = '#slist option[value="' + id + '"]';
var sname = $(snames).text();
var app = '<option value="' + id + '">' + sname + '</option>';
$('#senroll').append(app);
});
});
Something like this?
JSFiddle Demo
$(document).ready(function(){
$('#enroll').on('click', function(){
var id = $('#slist').val()[0];
if(id){
var snames = '#slist option[value="' + id + '"]';
var sname = $(snames).text();
var app = '<option value="' + id + '">' + sname + '</option>';
$('#senroll').append(app);
}
});
});
$(document).ready(function() {
$("#senroll").append($("<option></option>").val(1).html("One"));
$("#senroll").append($("<option></option>").val(2).html("Two"));
$("#senroll").append($("<option></option>").val(3).html("Three"));
$('#senroll').on('click', function() {
alert("I am clicked");
var id = $('#slist').val()[0];
var snames = '#slist option[value="' + id + '"]';
console.log(id, snames);
var sname = $(snames).text();
console.log(sname);
var app = '<option value="' + id + '">' + sname + '</option>';
$('#enroll').append(app);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="senroll" multiple="multiple" name="esubject">
</select><br /><br />
<label for="lsubject">Subject List</label></br>
<select id="slist" multiple="multiple" name="lsubject">
<?php foreach($slist as $subject): ?>
<?php echo "<option value='" . $subject['s_id'] . "'>" .
$subject['sname'] . "</option>"; ?>
<?php endforeach; ?>
</select><br /><br />
I don't know more about PHP for each but this will work in your js Code
Hope this helps!

dynamic form fields with javascript an php: It doesn't work

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 />';

how to insert correctly in javascript and php

Hello. I have a function to add row. I just added a second input but I don't know how to insert it correctly.
My JS code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfieldstest[]' + '" type="text" /><br />'
);
});
});
</script>
How I insert:
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
// HERE WHERE IT'S DOEST WORK //
foreach (array_combine( $_POST['dynfields,dynfieldstest'] as $key=>$value, $key=>$value1 )) {
$values = mysql_real_escape_string($value);
$values1 = mysql_real_escape_string($value1);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Thanks for help!
I'm guessing that you're looking for a solution that will scale as more and more inputs are added to the form. Here's a simpler way. It assumes that for each dynfields there will be a corresponding dynfieldstest, and we can count the number of dynfields in order to control the loop.
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
$post_count = count($_POST['dynfields']);
for ($i=0;$i<$post_count;$i++) {
$values = mysql_real_escape_string($_POST['dynfields'][$i]);
$values1 = mysql_real_escape_string($_POST['dynfieldstest'][$i]);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL only, or if you switch to PDO you can interface with MySQL and lots of other database types (MSSQL, Oracle, PostgreSQL, SQLite, etc...).
You should insert all new rows at once.
And use mysqli or PDO in the future, not the old mysql_* functions.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
);
});
});
</script>
PHP:
if (isset($_POST['submit_val'])) {
if (is_array($_POST['dynfields'])) {
foreach($_POST['dynfields'] as $key=>$value)
{
$hobbies = mysql_real_escape_string($value);
$client = mysql_real_escape_string($key);
$queryStr[] = "('$hobbies', '$client')";
}
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ".implode(',',$queryStr), $connection );
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
To add new input simply add
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
to the js

Categories

Resources