Using rel attribute in document on change function? - javascript

I use below code for dynamic textbox. When I will change ID=iuname1 it has to show result in FffinalResult1. Then when I will change ID=iuname2 it has to show result in FffinalResult2. but it don't.
<script type="text/javascript">
var counter = 0;
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
});
function GetDynamicTextBox() {
counter++;
return 'Item Code : <select name="iuname" id="iuname" rel="' + counter + '" class="iuname" >'+
<?php foreach($tItem as $row) : ?>
'<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>'+
<?php endforeach;?>
'</select>'+
' Batch : <input id="buname" name="buname" rel="' + counter + '" class="buname">'+
</div>');
'<div rel="' + counter + '" class="FffinalResult" id=FFinalResult" ></div>'+
'<br/>'
}
</script>
And document on change function is below.
<script>
$(document).on('change', $(".iuname[rel='"+ counter + "']"), function(){
var val = $(this).val();
var text = $(this).find('option:selected').text();
$(".FFffinalResultt[rel='"+ counter + "']").text(val);
});
</script>
How it will works?

Your code will always give values for last inserted elements as counter will be increasing each time you add elements! So I would suggest to use class here instead of id!
var counter = 0;// You can keep this to generate unique `id` but bind events to class
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
});
function GetDynamicTextBox() {
counter++;
return
'Item Code : <select name="iuname" id="iuname_'+counter+'" rel="' + counter + '" class="iuname" >'+
<?php foreach($tItem as $row) : ?>
'<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>'+
<?php endforeach;?>
' </select>'+
' Batch : <input id="buname_'+counter+'" name="buname" rel="' + counter + '" class="buname">'+
'<div rel="' + counter + '" class="FffinalResult" id="FFinalResult_'+counter+'" ></div>'+
'<br/>';
}
And event binding to class
$(document).on('change', ".iuname", function(){
var val = $(this).val();
var text = $(this).find('option:selected').text();
$(this).siblings(".FffinalResultt").text(val); //get its sibling element
});

Related

Getting php array dynamically in javascript

With the following code I try to add a new div-element with jQuery.
$(document).ready(function () {
var languages = <?php echo json_encode($languages); ?>;
var div = '';
$.each(languages, function (key, value) {
div = '<div class="main bg_notice" style="padding:3px; line-height:20px;">';
div += ' <img src="/lang/' + value['directory'] + '/admin/images/' + value['image'] + '" alt="' + value['name'] + '" title="' + value['name'] + '" style="border:0;">';
div += ' <b><?php echo TEXT_MASK_ALIAS; ?></b>';
div += ' <input type="text" name="mask_alias[' + value['id'] + ']" value="" style="width:80%" maxlength="255">';
div += '</div>';
$('[name="categories_name[' + value['id'] + ']').closest('div').after(div);
});
});
The value for the input field is created dynamically in PHP
echo (isset($mask_alias[$languages[$i]['id']]) ? stripslashes($mask_alias[$languages[$i]['id']]) : $categories_desc_fields['mask_alias']);
How do I get this into javascript writing style.
$languages[$i]['id']
is equivalent to
+ value['id'] +
in javascript.
The result should look like this non working code
div += ' <input type="text" name="mask_alias[' + value['id'] + ']" value="<?php echo (isset($mask_alias[$languages[$i]['id']]) ? stripslashes($mask_alias[$languages[$i]['id']]) : $categories_desc_fields['mask_alias']); ?>" style="width:80%" maxlength="255">';
var languages = JSON.parse(<?php echo json_encode($languages); ?>)'
You should do part of this in php and part of this in javascript.
I suggest that in PHP, you create a new array based on languages that will be handed to javascript, where all the php-level calculations have been already done.
For example
// php code
// you already have $languages defined
$jsLanguages = array_map(function ($key, $lang) {
$lang['mask'] = isset($mask_alias[$lang['id']]) ? stripslashes($mask_alias[$lang['id']]) : $categories_desc_fields['mask_alias'];
$lang['imageURL'] = "/lang/{$lang['directory']}/admin/images/{$lang['image']}";
return $lang;
}, $languages);
then
$(document).ready(function () {
var languages = <?php echo json_encode($jsLanguages); ?>;
var div = '';
$.each(languages, function (key, lang) {
div = '<div class="main bg_notice" style="padding:3px; line-height:20px;">';
div += ' <img src="' + lang.imageURL + '" title="' + lang.name + '" style="border:0;">';
div += ' <b><?php echo TEXT_MASK_ALIAS; ?></b>';
div += ' <input type="text" name="mask_alias[' + lang.id + ']" value="' + lang.mask + '" style="width:80%" maxlength="255">';
div += '</div>';
$('[name="categories_name[' + lang.id + ']"').closest('div').after(div);
});
});
I suspect languages is a string in json format rather than an actual object.
Try using JSON.parse to convert the string to an object.
var languages = JSON.parse(<?php echo json_encode($languages); ?>);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

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!

Bind event for dynamic added elements in Jquery not working

I have added Address,city and locality using jQuery in a dynamic added div element where the binding event is not working as expected:
I have below jQuery code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var elems = '<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
//('#addressDiv').append(elems);
$('#addressDiv').append(elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$('#city_name' + counter).html(html);
}
});
$(document).on('change', '#city_name' + counter, function (ev) {
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + counter).html(html);
}
});
});
//counter++;
return false;
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
</script>
My PHP Code for adding city in dropdown
city_load.php:
<?php
include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {
echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
locality_load.php
<?php
include("db.php");
$city_id = $_POST['city_id'];
$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";
$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {
$locality_id = $rows['locality_id'];
$locality_name = $rows['locality_name'];
echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";
//echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.
Please have a look on screenshot:
save the counter value as a data-attr
eg
var elems = '<div class="col-lg-5 Address" data-id="' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
'<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" data-id="' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
use a class for each element , bind events on class .
like
$(document).on('change','.city_name', function (ev) {
counter_id = $(this).attr('data-id');
}
so you will get the counter value and hope it will work for every div you created. (code not tested )
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var $elems = $('<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');
//('#addressDiv').append(elems);
$('#addressDiv').append($elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$elelms.find('select').html(html);
}
});
counter++;
return false;
});
$(document).on('change', 'select', function (ev) {
var cc = $(this).attr('data-index');
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + cc).html(html);
}
});
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
There are maybe some problem!

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

Ajax Webpage Not Displaying Most Update to Date Content After Redirect

I have page that displays images from different directories and can change the file names of files in a folder, based on their order in a jQuery sortable list.
So far everything is working except that after I Save the new file names and the Save page redirects to the Edit page I have to do a "Empty Cache and Hard Reload" in order for the new file order to be displayed.
Edit Page
<!DOCTYPE html>
<?php
session_start();
if (!$_SESSION['username']) {
echo "<script>window.location = './index.php'</script>";
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<link rel="stylesheet" href="../js/jquery/jquery-ui-1.11.4/jquery-ui.css">
<script src="../js/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/jquery/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
$(window).load(function() {
$(document).ready(function() {
$("#btnRefresh").click(function() {
window.location.reload(true);
});
$.ajax({
url: 'getPics.php',
success: function(resultOfAjaxCall) {
xmlDoc = $.parseXML(resultOfAjaxCall);
$xml = $(xmlDoc);
html = "";
$xml.find('Folder').each(function(index) {
//console.log($(this).attr('Name'));
city = $(this).attr('Name');
html += "<h3 class='accordion-header'>" + city + "</h3>";
html += "<div class='accordion-section'>";
html += "<button id='" + city + "_Save'>Save " + city + "</button>";
html += " ";
//Upload Form
html += '<form enctype="multipart/form-data" action="uploader.php" method="POST">';
html += '<input type="hidden" name="MAX_FILE_SIZE" value="100000" />';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += 'Choose a file to upload: <input name="userfile" type="file" /><br />';
html += '<input type="submit" value="Upload File" />';
html += '</form>';
//Save Form
html += '<form enctype="multipart/form-data" action="save.php" method="POST" id="' + city + '_Save_Form">';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += '</form>';
html += "<ul class='" + city + "-sortable-list'>";
$(this).find('File').each(function(index) {
//console.log($(this).text()
fileName = $(this).find('File_Name').text();
filePath = $(this).find('File_Path').text();
fileRealPath = $(this).find('File_Real_Path').text();
//console.log(fileName);
//console.log(filePath);
html += '<form enctype="multipart/form-data" action="delete.php" method="POST" id="' + fileName + '_Delete_Form">';
html += '<input type="hidden" name="Delete_Path" value="' + filePath + '" />';
html += '</form>'
html += "<li id='" + fileName + "' class='ui-state-default' value='" + fileRealPath + "'>" + fileName + " ";
html += "<button id='" + fileName + "_Delete'>Delete</button>";
html += "<br>"
html += "<img src='" + filePath + "' style='width:150px;'/>";
html += "<br></li>";
})
html += "</ul>";
html += "</div>";
//window.location.reload(true);
});
$("#accordion").append(html);
var $accordion = $("#accordion").accordion({
collapsible: true,
heightStyle: "content",
active: false
});
$("[class$=-sortable-list]").sortable({
update: function(event, ui) {
console.log(ui);
var order = [];
$("[class$=-sortable-list] li").each(function(e) {
order.push($(this).attr("id") + "=" + ($(this).index() + 1));
});
var positions = order.join();
// alert(positions);
},
stop: function(event, ui) {
console.log("an item was moved");
$accordion.find("#tmp").remove();
},
start: function(event, ui) {
$accordion.append("<ul id='tmp'></ul>");
$accordion.find("#tmp").append(ui.item);
}
}).disableSelection();
//Save Click
$("[id$=_Save_Form]").submit(function(event) {
folder = event.target.id.replace("_Save_Form", "");
$("." + folder + "-sortable-list li").each(function(e) {
//alert(folder);
//alert($(this).index());
//alert($(this).attr("value"));
$("<input />").attr("type", "hidden")
.attr("name", "path[" + $(this).index() + "]")
.attr("value", $(this).attr("value"))
.appendTo("#" + event.target.id);
});
});
$("[id$=_Save]").click(function(event) {
$("#" + event.target.id + "_Form").submit();
});
}
});
});
});
</script>
<title>Edit Slider</title>
</head>
<body>
<?php ?>
<p>You are logged in as <?= $_SESSION['username'] ?> (Logout)</p>
<p><button id="btnRefresh">Refresh</button></p>
<div id="accordion">
</div>
</body>
</html>
Save Page
<?php
$root = filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
require $root . '/CC_Library/CC_Folder.php';
require $root . '/CC_Library/CC_String.php';
$folder = filter_input(INPUT_POST, "City_Folder", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
$dir = "";
$i = 0;
$s = new CC_String;
$tmp = $s->generate_rand(5);
foreach ($_POST['path'] as $value) {
$CC = new CC_File($value);
$dir = $CC->get_File_Dir();
echo "Changing " . $CC->get_Full_File_Name() . " to " . $tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension() . "<br>";
$CC->Rename($tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension());
$i++;
}
$j = 0;
//echo $dir;
$F = new CC_Folder($dir);
$Files = $F->get_Folder_Files();
foreach ($Files as $value) {
echo "Changing " . $value->get_Full_File_Name() . " to " . $folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension() . "<br>";
$value->Rename($folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension());
$j++;
}
echo "<script>window.location.replace('Edit_Slider.php')</script>";
I dont want to read all of that notorious code. Your problem is client sided, not server sided so your code is irreverent.
Your webbrowser is caching and not updating your images. A fix for this would be to extend the current image source with a timestamp like so:
<img src="image.jpg?lastmod=12345678"
//javascript
function(img_src){
var timestamp = (new Date()).getTime();
img_src += "lastmod?" + timestamp;
}
how to clear or replace a cached image
The reason this works is because the source URL is different each time because of the timestamp will always be different & web browsers remember content relative to the URL.

Categories

Resources