Fault with appending item to drop down (local storage) - javascript

I have the following code, which works well.
<div style="padding:2px;">
<form action='test.php' name ='gen' method='post'>
<input type='text' name='pass' placeholder="Insert website" size="10"> <input type='submit' value='Open'>
</form>
</div>
<?php
$random = 'specificsaltcode'; // specific salt
$pass2 = $_POST['pass'] . $random; // add it to user input
$pass = md5($pass2); // md5() both
$url = 'http://www.website'.$_POST['pass'].'random'.$pass.'randomurlcontinued'; // the url you need
echo '<iframe id="iframe1" name="iframe1" scrolling="yes" src="' . $url . '" style="position: absolute; left: 0px; top: 26px;" width="99%" height="88%" border="0"></iframe>';
?>
This hashes a user input string and sends the original input string, along with the hashed number to an iframe as a url. This works well for me.
However, rather than send the url to an iframe, I need to send this to a drop down list and store it using local storage.
I have the following code for my drop down.
<style>
#choice option { color: black; }
.empty { color: gray; }
</style>
<script>
var VM = function () {
this.annotationList = ko.observable();
this.area = ko.observableArray();
this.append = function () {
this.area.push(this.annotationList());
localStorage.setItem('labelObject',this.annotationList());
localStorage.setItem('labelObjectList',this.area());
};
};
var existAnnotationmodel = new VM();
ko.applyBindings(existAnnotationmodel);
</script>
<script>
$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});
$("#choice").change();
</script>
<form >
<span class="btn-group">
<select name="select" data-bind="options: area" id="choice">
<option value="0" selected="selected">Choose website</option>
</select>
<input id="editExistannotation" data-bind="value: annotationList" type="text" placeholder="Enter website"/>
</span>
<button id="buttonSave" type="submit" data-bind="click:append" >Save</button>
</form>
<div id="labelList" class="btn-group" ></div>
However, this drop down method does NOT store these appends. Infact, it doesn't even add any items to the menu at all. I'd like it to add an item to the drop down, and save it using local storage, so when the user refreshes the page, the appends are still there.
So two issues, how to pass the url to the drop down, and how to make the drop down save appended items.
Also, I am not concerned over security issues at the moment.

Related

Calling PHP file from a slider page, how do I return to the active slide?

I have a simple home-grown slider whose input is pulled from a MySQL database using PHP that echos the HTML for the slider page to build it. I am developing functionality to "add a comment" to the slider pictures which pulls up a hidden form when you click on the "Add a Comment" button. Once filling in that form and doing a Submit, I call an "updateComment.php" file that pulls the form posted values and does a CONCAT_WS to the Comments field for that picture in the slider sequence in the database.
I use a header('Location: ' .$_SERVER['HTTP_REFERER']); call at the end of the "updateComment.php" file to return to the slider page whose form submit called it. When it returns, it returns to the first slide page instead of the active slide page. It makes sense to me why that happens using that redirect method, but I am at a loss to figure out how to get it to return to the active slide page. I've been reading up on PHP redirects, but can't find anything that will work. Any sage words of advice or a clue how to do this?
Doing a Page Source of the slider page and stripping out all the detailed database field info built on that page, here is the code around the form's call to "updateComment.php".
<div style="text-align: center;">
<button class="commentbutton" onclick="showForm('formElementTimothyTopp')">Add a memory or story of Tim</button>
</div>
<div>
<form id="formElementTimothyTopp" style="display: none;" action="updateComment.php" method="post" autocomplete="off">
<input type="hidden" value="Timothy" id="fname" name="fname">
<input type="hidden" value="Topp" id="lname" name="lname">
<div class="formitemname">Name:</div>
<input class="formitem shortentry" type="text" maxlength="40" value="" id="commentor" name="commentor" placeholder="Your Name">
<div class="formitemnamelonger">Your Memory or Story of Tim:</div>
<textarea class="formitem longentry" type="text" maxlength="2000" value="" id="memory-story" name="memory-story" placeholder="Add your memory or story here" rows="5"></textarea>
<button style="text-align: center; margin: 10px 0 10px 240px;" type="submit" name="submit" id="submit">Submit</button>
</form>
<div>
Here is the actual "updateComments.php" code
<?php
$conn = mysqli_connect("localhost", "root", "", "classmateinfo");
if ($conn-> connect_error) {
die("Connection failed:". $conn-> connect_error);
}
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$memory = !empty($_POST['memory-story'])?$_POST['memory-story']:'';
$name = !empty($_POST['commentor'])?$_POST['commentor']:'';
$toappend = $memory . "<br>-- " . $name . "<br><div><img src=images/spacer10.gif></div>";
$sql = "UPDATE rip SET Comments = CONCAT_WS('',Comments,'$toappend') WHERE (ClassmateNameFirst = '$firstname' AND ClassmateNameLast = '$lastname')";
$result = $conn-> query($sql);
header('Location: ' .$_SERVER['HTTP_REFERER']);
?>
Slider functional code is:
<script>
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
if (n > slides.length) {slideIndex = 1};
if (n < 1) {slideIndex = slides.length};
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
</script>
The rest of the info on the slider page besides the active image displayed includes the Comments field and that page is built using an HTML table. Each slider page is its own table, dozens of images with a table entry for each, all built by the database pulls using PHP code to render the page.
My idea is to submit current_slide along with the form. Then server knows to redirect back to page with extra param "$page?current_slide=" . $current_slide;. This param would then be analyzed when initializing the slider, to start from the correct slide.
Some code:
function update_current() {
var current_slide = 12; // get from slider
document.getElementById("current_slide").value = current_slide;
}
<form id="formElementTimothyTopp" style="display: none;" onsubmit="update_current()" action="updateComment.php" method="post" autocomplete="off">
<input type="hidden" value="Timothy" id="fname" name="fname">
<input type="hidden" value="Topp" id="lname" name="lname">
<input type="hidden" value="" id="current_slide" name="current_slide">
<div class="formitemname">Name:</div>
<input class="formitem shortentry" type="text" maxlength="40" value="" id="commentor" name="commentor" placeholder="Your Name">
<div class="formitemnamelonger">Your Memory or Story of Tim:</div>
<textarea class="formitem longentry" type="text" maxlength="2000" value="" id="memory-story" name="memory-story" placeholder="Add your memory or story here" rows="5"></textarea>
<button style="text-align: center; margin: 10px 0 10px 240px;" type="submit" name="submit" id="submit">Submit</button>
</form>
Then on server:
// TODO: append query string parameter in a better way
header('Location: ' .$_SERVER['HTTP_REFERER'] . "?current_slide=" . $_POST["current_slide"]);
Then back on load of client:
const urlParams = new URLSearchParams(window.location.search);
const current_slide = urlParams.get('current_slide');
// TODO: goto slide current_slide
UPDATE:
another idea would be using the localStorage to store the state of the slider right before submitting it. Then, when loading all you need is getItem from localStorage and check it.
// when submitting
function update_current() {
var current_slide = 12; // get from slider
localStorage.setItem("current_slide", current_slide);
}
// when loading the page call:
function load_current() {
var current_slide = localStorage.getItem("current_slide")
if (current_slide) {
// set slider slide to be current_slide
}
}

Keep input value after refresh page

I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]

Control image upload size in textarea of HTML Form

I'm using the following WIZWIG editor "http://js.nicedit.com/nicEdit-latest.js" posting into the below HTML form. I want to control the size of images that are uploaded. Image size should be something like 200px height, 300px width. I've tried CSS, HTML & JavaScript to no avail. Can't figure this out...
<style>
.nicEdit-main{
background-color: white;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit- latest.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas({buttonList : ['bold','italic','underline','strikeThrough','html','forecolor','link','upload','unlink','removeformat']}) });
</script>
<form name="comments" action="<?php echo $_SERVER['PHP_SELF']; ?>"method="post" onsubmit="return checkForm();">
<?php if ($isGuest) { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4">disabled for guest account</textarea>
</div>
<input type="submit" name="action" disabled value="Add Comment" />
<?php } else { ?>
Comment:<br><br>
<div style="background: #fff;">
<textarea style="width: 100%;" name="comment" cols="111px" rows="4"></textarea>
</div>
<input type="submit" name="action" value="Add Comment" />
<?php //header("Location: test.php");
} ?>
</form>
Although this was not possible few years ago(you had to send the file to the server side to be able to process file information) now it is do possible with the FileReader() object and pure JS.
You use the .files[0] to get the file then create a temporary img object on the DOM(to be able to do the process) and then assign the file to that DOM object(with the help of FileReader())and then you just compare the file width or height. This is an example how you can do it:
imgfile.onchange = function(e) {
var oFile = document.getElementById("imgfile").files[0]; //Get the selected file by the user
var img = document.getElementById("imgdom"); //get the reserve image element on the dom to be able do all our processing with this object type
document.getElementById("imgdom").style.display = "none";//This is optional if you want to show or not the image to the user
var reader = new FileReader(); //This is the magic object that allows you to process a file on the client side
reader.onload = function (e) {
console.log(e.total); // file size
img.src = e.target.result; // putting file in dom without server upload.
alert(img.width);
//Do what ever condition you want here
//if img.width > 200 do this, else do that
};
reader.readAsDataURL(oFile );
//return false;
};
<form method="post" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="imgfile" id="imgfile">
</form>
<div>
<img id="imgdom" src="" />
This issue has been resolved with the following CSS Code:
.nicEdit-main img {
width: 350px;
}
img[src*="http://somedomain.com"] {
width: 350px;
}
Thanks to all who commented...

Get selected option ID with Javascript

I have a tabs with select option in each tab and I want it to be submitted in a specific URL assigned to them when I hit submit button. I'm doing this in javascipt. I'm really a newbie in javascript that's why I need your generous help.
I divided my select option according to their category using tabs, so my code is like this:
HTML
<ul class="ut-nav-tabs clearfix">
<li class="active">Corporate Services
</li>
<li class="">
Digital Marketing
</li>
</ul>
<div id="t1Tab" class="tab-pane clearfix active">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_corporateservices">
<option value="Can a foreign investors open his own company in the Philippines?">Can a foreign investors open his own company in the Philippines?</option>
<option value="What are the business regulations currently used in the Philippines?">What are the business regulations currently used in the Philippines?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
<div id="t2Tab" class="">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_digitalservices">
<option value="Should I add online video to my web sites?">Should I add online video to my web sites?</option>
<option value="What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
JAVASCRIPT
<script type="text/javascript">
function redirect() {
var filename_corporate = document.getElementById('id_corporateservices').value;
var filename_digital = document.getElementById('id_digitalservices').value;
var url ='';
if (filename_digital == 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(filename_corporate == 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
Why is that when I selected any in the option and then submitted it always direct to the first url condition http://localhost/testsite/digital-page?
Because you are always referring to the one element with id "id_digitalservices" that never changes? It does not matter if you change tabs visibility it still remains in DOM.
You can get the actually changed option value by using the following code:
<script type="text/javascript">
function selectmenuOnchange(selectMenuId) {
//Get the selectmenu element by Id
var selectmenuID = document.getElementById(selectMenuId);
//Get selected options value
var optionValue = selectmenuID.options[selectmenuID.selectedIndex].value;
//this should return the selectmenu's id
alert(this.id);
redirect(optionValue);
}
function redirect(optionValue) {
var url ='';
if (optionValue === 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(optionValue === 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
You need to edit both of your selectmenus to include my onchange function like this:
HTML
<select onchange="selectmenuOnchange(this.id);">

how to move the selected item in a list box into a text box?

i want to move the selected item of a select tag (list box) into a text box after clicking a button. i am using the below code
<html>
<head>
<script type="text/javascript">
function copy()
{
var sel = document.getElementById('lb').value;
document.getElementById('FileName').value = sel;
}
</script>
</head>
<body>
<form name="frm1" id="frm1">
<select id="lb" name="lb" size="5">
<option value="abc.txt">abc.txt</option>
<option value="def.txt">def.txt</option>
</select>
<input type="button" value=">>" name="btn_move" id="btn_move" onclick="copy()">
<input type="text" name="FileName" id="FileName">
</form>
</body>
</html>
the above code works properly in google chrome browser but it does not work when i run the page in IE. can anyone tell me whats the problem in the code and kindly suggest a javascript or any other code which is compatible ith both google chrome and IE.
above code works after i allow the pop up that comes but
actually the below code is not working.
<html>
<head>
<title>FILE</title>
<style>
body{background-color:#b0c4de;}
#OutBound{text-align:center;}
#btn_sbmt{position:absolute;top:150px;left:700px;}
#div_text_label{position:absolute;top:50px;left:200px;}
#lbl2{position:absolute;top:80px;left:200px;}
#selected_list{position:absolute;width:300px;top:80px;left:335px;}
#btn_move{position:absolute;top:100px;left:650px;}
#FileName{position:absolute;width:300px;top:100px;left:700px;}
</style>
<script type="text/javascript">
function load_list()
{
document.getElementById('div_main_select').style.display="none";
var textbox = document.getElementById('pattern');
var listbox = document.getElementById('selected_list');
var mainListbox = document.getElementById('lb');
listbox.innerHTML = '';
for (var childIndex = 0; childIndex < mainListbox.children.length; childIndex++)
{
var child = mainListbox.children[childIndex];
option = document.createElement('option');
option.innerHTML = child.innerHTML;
listbox.appendChild(option);
}
alert (load_list_1);
}
function get_list()
{
var textbox = document.getElementById('pattern');
var listbox = document.getElementById('selected_list');
var mainListbox = document.getElementById('lb');
listbox.innerHTML = '';
for (var childIndex = 0; childIndex < mainListbox.children.length; childIndex++)
{
var child = mainListbox.children[childIndex];
if (child.innerHTML.search(textbox.value) != -1)
{
option = document.createElement('option');
option.innerHTML = child.innerHTML;
listbox.appendChild(option);
}
}
alert (get_list_1);
}
function copy()
{
var sel = document.getElementById('selected_list').value;
document.getElementById('FileName').value = sel;
alert (copy_1);
}
</script>
</head>
<body style="color: black; background-color: rgb(255, 255, 255); background-image: url(background-1204x927.jpg);" BGCOLOR="#ffffff" text="black" link="#B03060" vlink="#B03060" onload="load_list()">
<hr>
<form id="OutBound" name="OutBound" action="" method="GET">
<div style="text-align:center;" id="div_text_label" name="div_text_label">
<label id="lbl1" name="lbl1">search :</label>
<input type="text" name="pattern" id="pattern" onKeyUp="get_list()">
</div>
<div style="text-align:center;" id="div_main_select" name="div_main_select">
<select id="lb" name="lb" size="5">
<option value="abc.txt">abc.txt</option>
<option value="def.txt">def.txt</option>
</select>
</div>
<label id="lbl2" name="lbl2">File List:</label>
<select id="selected_list" name="selected_list" size="5">
</select><br>
<input type="button" value=">>" name="btn_move" id="btn_move" onclick="copy()">
<input type="text" name="FileName" id="FileName">
<input type="submit" name="btn_sbmt" id="btn_sbmt" value="MOVE FILES">
</form>
</body>
</html>
the page works like this..
1) there is a list box (lb) populated with some items.
2) there is 1 more empty list box (selected_list).
3) when the page form is loaded load_list() function is called which loads the empty list box (selected_list) with the contents of the original list box (lb).
4) when someone enters a word or a letter in the search text box then get_list() function is called which filters the files according to the words entered.
5) when a filename is selected in the selected_list and >> button is pressed, the copy() function is called and the filename is copied to the FILENAME text box.
but this all is not working in IE but it works in google chrome. can anyone fix the code so that it works with IE also.
Try this:
function copy() {
var sel = document.getElementById('lb');
document.getElementById('FileName').value = sel.options[sel.selectedIndex].text;
}
The code works fine (see fiddle in IE)
If you are opening the file from local file system, the IE may ask your permission to run script. You should click "Allow Blocked Content" for it to work
See image below
Try this using jQuery (1.10.1)
function copy()
{
$("#FileName").val($("#lb").val());
}
http://jsfiddle.net/7Axu8/
Update
http://jsbin.com/onayow/1

Categories