Select text and add to localstorage - javascript

Iv been using a simple html5 note taking application and would like to expand it.
I would like to be able to select some text on a page and add that as a note . Im not sure if I would create a new function or amend one that already exists .
I have included the code below that I think adds the item to localstorage .
I have also included a link to the github page where the html code is : https://github.com/oxhey/Notes-Manager
if(newItem){ // don't push when generating from localStorage
allTitles.push(listTitle);
allLists.push({'title': listTitle, 'note': listNote});
localStorage.setItem('allLists',JSON.stringify(allLists));
localStorage.setItem('allTitles',allTitles);
}
return listContainer;
};
HTML :
<form class="form-horizontal" onsubmit="return false;" role="form" id="newListForm">
<div class="form-group">
<label for="newListInput" class="col-sm-2 control-label">Title<span>*</span></label>
<div class="col-sm-5">
<input type="text" required="true" class="form-control" name="newListTitle" id="newListInput" placeholder="List Title" onblur=' this.value=this.value.replace(/(^\s*)/g, "") ; '>
</div>
</div>
<div class="form-group">
<label for="newNoteInput" class="col-sm-2 control-label">Note<span>*</span></label>
<div class="col-sm-5">
<textarea required class="form-control" name="newListNote" id="newListNote" placeholder="Write Note" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<button type="submit" id="submitButton" class="btn btn-primary">Save</button>
</div>
</div>
</form>

You can do that in Javascript. Use the following code:
if(window.getSelection){
selectedText = window.getSelection();
}else if(document.getSelection){
selectedText = document.getSelection();
}else if(document.selection){
selectedText = document.selection.createRange().text;
}
Selection | MDN
EDIT:
Try using the following JS code along with your HTML:
function submitForm(){
var listTitle = document.getElementById("newListInput").value;
var listNote = document.getElementById("newListNote").value;
console.log(listNote);
// not sure why you have the following 2 lines
//if(newItem){ // don't push when generating from localStorage
//allTitles.push(listTitle);
var allLists = [];
allLists.push({'title': listTitle, 'note': listNote});
localStorage.setItem('allLists',JSON.stringify(allLists));
localStorage.setItem('allTitles',allTitles);
// }
}
//return listContainer;
//};

Related

javascript function sets the value of a form input field, but then the value disappeared

I'm trying to do a live database search using ajax with a form input field.
The whole thing runs so far that i can select a text from the proposed list.
The corresponding event "livesearchSelect" is also addressed, the value of the input field is set. Unfortunately the set value is missing in the form.
I have no clue what is going on, someone can throw some hints at me pls ?
screenshot
html:
<form name="demoform" id="demoform" action="" method="post" >
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-4">
<input type="text" name="name" id="name" value="a value" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-4">
<input type="text" name="email" id="email" value="" class="form-control" >
</div>
</div>
<div class="form-group row">
<label for="search" class="col-sm-2 col-form-label">Live Search</label>
<div class="col-sm-4">
<input type="search" name="search" id="search" value="" class="form-control" oninput="livesearchResults(this, '/livesearch/Album');">
<ul class="list-group" id="search-results" style="display:none">
<li class="list-group-item">?</li>
</ul>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-4">
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-primary" />
</div>
</div>
</form>
javascript:
function livesearchResults(src, dest){
var results = document.getElementById(src.id + '-results');
var searchVal = src.value;
if(searchVal.length < 1){
results.style.display='none';
return;
}
var xhr = new XMLHttpRequest();
var url = dest + '/' + searchVal;
// open function
xhr.open('GET', url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var text = xhr.responseText;
results.style.display='inline';
results.innerHTML = text;
console.log('response from searchresults.php : ' + xhr.responseText);
}
}
xhr.send();
}
function livesearchSelect(src) {
var input_element = document.getElementById(src.parentElement.id.split("-")[0]);
input_element.defaultValue = src.text;
input_element.value = src.text;
}
php controller:
<?php
namespace controller;
use database\DBTable;
class livesearch extends BaseController {
public function index() {
echo "nothing here";
}
public function Album($input) {
$table = new DBTable('Album');
$results = $table->where('Title',$input.'%', 'like')->findColumnAll('Title', '', 6);
foreach ($results as $key => $value)
echo ''.$value.'';
}
}
Clicking an anchor element with an href attribute, even when blank, will load the linked page, which is what you see happening here.
One solution would be to prevent the default action for the link (by e.g. returning false in the handler or calling Event.preventDefault), but a better design would be to replace the <a> elements (which aren't actually links) with something more semantically appropriate. Given that the consumer expects a sequence of <li>, the simplest solution is to replace the <a> in the PHP controller with <li>. The result would still have a higher degree of coupling than is desirable; the HTML classes and click handler couple the results tightly to the specific search form, rather than representing the resource as its own thing.
Not that text is not a DOM-standard property of HTML elements; you should be using textContent or innerText instead.

How to make jquery.dynamiclist run with newer version of jquery?

I would like to use jquery.dynamiclist library in my procject.
In the demo page that's running smoothly there is a jquery library in version 1.8.2.
In my project I use version 1.11.1 and this makes dynamiclist plugin doesn't work.
With newer version when I process form I get data with names of inputs but without values (I get 'undefined').
Here is the code from demo.
What I have to change to make it run with newer version of jquery?
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://github.com/ikelin/jquery.dynamiclist/blob/master/jquery.dynamiclist.min.js"></script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.attr("value");
data += "; "
}
});
alert(data);
location.reload(true);
});
});
})(jQuery);
</script>
Simply change element.attr("value"); to element.val();.
Sorry I had to include the plugin code manually because apparently you cannot include the src directly from github. Also commented the reload for the snippet.
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
/* jQuery Dynamic List v 2.0.1 / Copyright 2012 Ike Lin / http://www.apache.org/licenses/LICENSE-2.0.txt */
(function(a){a.fn.dynamiclist=function(d){if(this.length>1){this.each(function(){a(this).dynamiclist(d)});return this}var g=a.extend({itemClass:"list-item",addClass:"list-add",removeClass:"list-remove",minSize:1,maxSize:10,withEvents:false,addCallbackFn:null,removeCallbackFn:null},d);var f=function(o,n,j){var m=o.find("."+j.itemClass).length;if(m<j.maxSize){var l=o.find("."+j.itemClass+":first").clone(j.withEvents);l.find("."+j.removeClass).show().click(function(p){e(o,a(this),p,j)});b(l,m);i(l);var k=o.find("."+j.itemClass+":last");k.after(l);if(j.addCallbackFn!=null){j.addCallbackFn(l)}}if(n!=null){n.preventDefault()}};var e=function(o,k,n,j){var m=o.find("."+j.itemClass).length;var l=k.parents("."+j.itemClass+":first");if(m==j.minSize){i(l)}else{l.remove()}c(o,j);if(j.removeCallbackFn!=null){j.removeCallbackFn(l)}n.preventDefault()};var b=function(j,k){j.find("label, input, select, textarea").each(function(){var m=["class","name","id","for"];for(var n=0;n<m.length;n++){var l=a(this).attr(m[n]);if(l){l=l.replace(/\d+\./,k+".");l=l.replace(/\[\d+\]\./,"["+k+"].")}a(this).attr(m[n],l)}})};var c=function(k,j){k.find("."+j.itemClass).each(function(){var l=k.find("."+j.itemClass).index(this);b(a(this),l)})};var i=function(j){j.find("input[type=text], textarea").val("");j.find("input[type=radio]").attr({checked:false});j.find("input[type=checkbox]").attr({checked:false})};var h=function(k){k.find("."+g.itemClass+":first ."+g.removeClass).hide();var j=k.find("."+g.itemClass).length;while(g.minSize>j){f(k,null,g);j++}k.find("."+g.addClass).click(function(l){f(k,l,g)});k.find("."+g.removeClass).click(function(l){e(k,a(this),l,g)});return k};return h(this)}})(jQuery);
</script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.val();
data += "; "
}
});
alert(data);
//location.reload(true);
});
});
})(jQuery);
</script>

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

RSA Encryption using PHP and Javascript

I am new to JavaScript and wanted to know how to display to text-box from the below code. I am having a hard time to transferring the variable encrypted info to a text-box using JavaScript. If that's not possible then how can I display the information from $('#feedback').html(data); to the textbox.
<script>
function encrypt() {
var publickey = "<?=publicKeyToHex($privatekey)?>";
var rsakey = new RSAKey();
rsakey.setPublic(publickey, "10001");
var enc = rsakey.encrypt($('#plaintext').val());
$.get('index.php?encrypted='+enc, function(data) {
var encryptedinfo = $('#feedback').html(data);
encryptedinfo.value;
});
return;
}
</script>
<div class="row-fluid">
<div class="span4">
<form class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">Plaintext</label>
<div class="controls">
<input type="text" name="plaintext" id="plaintext" placeholder="enter something">
</div>
</div>
</form>
</div>
<div class="span4">
<button type="button" class="btn btn-primary" onclick="encrypt()">Encrypt</button>
</div>
<br/>
Assuming you have the encrypted value in the data, you can simply use $("#plaintext").val(data).

JavaScript - Bootstrap Validator

I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>

Categories

Resources