Yes, I know that data sanitation and validation must be done server-side, but please stay with me.
Using the following script, stackoverflow.com will fail validation since a protocol is not given. If a URL is inputted without a protocol, I wish to add a default protocol (http://) to the input value prior to client-side validation. I don't wish to relax the validation method to silently accept URLs without a protocol as the user should be aware that a protocol was added.
How is this best accomplished?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var validator=$("#myForm").validate({
rules: {
url: {url:true,}
},
});
//Added per Monax's suggestion.
$('#url').blur(function(){this.value=this.value.substring(0,4)=='http'?this.value:(this.value?'http://'+this.value:'');});;
});
</script>
</head>
<body>
<form id="myForm" method="post">
<input name="url" id="url" value="">
<input type="submit" />
</form>
<?php echo('<pre>'.print_r($_POST,1).'</pre>');?>
</body>
</html>
You don't want to write a custom rule and you insist on manipulating the data before validation. Your options are limited since the plugin is automatically capturing all the validation triggering events. This is my suggested workaround.
Create two input fields...
one visible for the user (no validation)
one hidden for validation. (validation message presented though)
Upon entering any data into visible field, you would programmatically copy and modify the data as needed into the hidden field.
Then programmatically trigger validation on the hidden field.
Something like this.
HTML:
<input type="text" id="url" />
<input type="hidden" name="url" />
jQuery:
$('#url').on('blur keyup', function() {
var myurl = $(this).val(); // entered value
// manipulate and sanitize the value as desired
$('[name="url"]').val() = newvalue; // copy the new value into the hidden field.
$('[name="url"]').valid(); // trigger validation on the hidden field
});
NOTES:
You'll have to enable validation on hidden fields by properly setting the ignore option to something that allows it. [] will enable validation on all hidden fields.
You might have to use the errorPlacement option to tweak the placement of the error message for this hidden field. You can do this conditionally.
Related
I want to retain entered value in text box after navigation. I am explaining my code here.
**main.php**
<html>
<head></head>
<body>
<input type="text" id="myname" value="">
Next
</body>
</html>
**next.php**
Back
I don't want to use 'button' field here. On link navigation I want to retain the entered value in text box field. I am using php, html
you should save it in a cookie/session.
Or you can use localStorage too. Here's a link to read more
<form id="myform" name="myform" method="POST" action="next.php">
<input type="text" name="query" id="query">
Submit
</form>
<script type="text/javascript">
function submitform(){
// alert('form submit');
document.forms["myform"].submit();
} </script>
And in next.php
$_SESSION['last_search_term'] = $_REQUEST['query'];
echo $_SESSION['last_search_term'];
This will work . I have check it
I would use cookies. Note sessions and Opera back button do not work well together.
However if you want a cookieless solution you can use "window.name" string which is persistent i.e. its value is retained on navigation between pages. No need for a button as you required.
Just add this code before the closing </body> tag.
<script>
// on navigation to, or back: load users input from previous page (if any)
document.getElementById("myname").value = window.name;
// save value on navigation out
window.onbeforeunload = function() {
window.name = document.getElementById("myname").value;
return;
}
</script>
Assuming you give your text field the same id you can use the same js without modification on both/all pages.
The basic example code above should work with all modern browsers and most old browsers (even Opera since 2013). Modify it to use an event listener sanitize/check for empty values etc as required
I'm trying to set a default focus for all the pages of my site but without changing the focus on page reload.
I mean:
User opens a page.
Focus is automatically set on the 1st input.
User changes focus to the 3rd input.
User refreshes the page.
Focus must not change to the 1st input again. (This is the requirement I fail to accomplish).
My current code is as follows:
$(document).ready(function() {
if($(':focus').length === 0) {
$(':input:not([type="hidden"]):first').focus();
}
});
The condition is true every time!
$(document).ready({
window.onload=function(){
if(session.Storage.getItem("text3")){//if key= text3 is set,then change the focus to 3rd text box.
$('#your3rdTextID').focus();
}
$('#your3rdTextID').focus(function(){
session.Storaage.setItem("text3","selected")//here you set the key as text3 and value as selected for later use.
});
});
You can provide with your own custom conditions.This is just a small example.Hope it helped you.Good luck with your project.
LINK-->HTML5 Local storage vs. Session storage
LINK-->http://www.w3schools.com/html/html5_webstorage.asp
This will work (tested in latest Chrome, IE7 and IE10). Sets a cookie on focus remembering the last focused element, if not, it defaults to the first. It relies on jquery.cookie.js (usage explained in this SO answer). Here is the full HTML+JS source of a minimal working example. Consider changing the cookie name and the input selector (currently 'input'):
<!doctype html>
<html>
<head>
<title>focus test</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $input = $('input'), // get all the inputs
cookieName = 'lastInputFocusIndex', // for consistency
lastIndex = $.cookie(cookieName) || 0; // get the last known index, otherwise default to zero
$input.on('focus',function(){ // when any of the selected inputs are focused
if ( $(this).attr('type') !== 'submit' ) {
$.cookie(cookieName,$input.index(this)); // get their index in the $input list and store it
}
});
$input.eq(lastIndex).focus(); // when the page loads, auto focus on the last known index (or the default of 0)
});
</script>
</head>
<body>
<form method="get" action="">
<p><input type="text" name="first" /></p>
<p><input type="text" name="second" /></p>
<p><input type="text" name="third" /></p>
<p><input type="submit" value="Go" /></p>
</form>
</body>
</html>
Alternatively, you could write your own raw cookies instead of using the cookie helper jQuery plugin; I used it to simplify things.
I can update an HTML form using Javascript, when the user hits enter when on something on the form or when he triggers the onclick event on the "submit" button, but I want the form to be updated while the user is typing something.
I know that I can do Infinity loop, yet it is not a good idea; or I can check after intervals but it will cause unnecessary checking, which I don't want.
Use keyUp event handler with the input field contained within your form.
References: Javascript,
jQuery
[UPDATE]
You missed round brackets at function definition, check the updated fiddle
I had the same question and based on this post and sohel's answer I managed to get it working. Now I would like to share my solution in form of a short working example: If you type your name in the first field it will suggest an email address in the second one.
<!DOCTYPE html>
<html>
<head>
<script>
function nameModify(emailElement, nameElement) {
emailElement.value = nameElement.value + '#stackoverflow.com';
}
</script>
</head>
<body>
<form name="aform" action="#">
<input type="text" name="name" onkeyup="nameModify(this.form.elements['email'], this);" >
<input type="text" name="email" >
</form>
</body>
</html>
You are looking for Autocomplete
I am not a Javascript Guru. But I found myself in a very tricky situation while writing a Jquery for one of Application.
Situation:
I have a form with different field. One of the field containing multiple values, say phone numbers. I am filling those numbers in a pop up - lightbox. Now, the problem I am facing is that I want to click the form button to submit my form but My numbers are coming from popup box. Ok let me try to describe the whole flow in points:-
Form has mutiple fields. For One field - number, I am showing the popup box.
I click a button on the popup box which sends me to the form. But I am not able to find those numbers in the form.
Final click is on the form button which sends all the information to the server side.
But I am not getting those value of numbers here on the form. So, Can any one suggest me the best way to resolve this issue?
Note: - I tried my best to put my question in a clear way. But If you guys could not find my words very clear, Sorry!
I'm not entirely sure I understand but I'll take a stab:
Option 1) Write all the values from the lightbox from back to the first form using $(selector).val();
Option 2) Copy the entire lightbox form into a hidden div inside the first form.
The popup box element is probably being added outside your form, so any input elements in the popup won't be submitted when you submit the form. To check this use a DOM Inspector (i.e. firebug in firefox or the dev tools in ie8 or chrome) to see where the element containing the lightbox is (it's usually at the end of the page).
To solve this you might be able to configure the lightbox to add it's div within the form, or else just use a bit of javascript to grab the value of the input element on the popup and populate a hidden input that's actually within the form before submitting.
Hi does this help
. It creates a popup there you can edit data then populate back into the main page which is referenced by opener just before closing the popup.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript">
<!--
function fn() {
var popupwin = window.open("","","width=500,height=300");
popupwin.document.open();
popupwin.document.write("<html><head><script>function onOk(){opener.parent.document.getElementById('txtnumberfield').value=document.getElementById('txtpopup').value; window.close();}</script></head><body>Here are some popup values <input type='text' value='value from popup' name=txtpopup id=txtpopup />"+
"<input type=button onclick='onOk()' value='Done editing' /></body></html>");
popupwin.document.close();
}
//-->
</script>
<BODY>
<form action="#">
Number <input type="text" id="txtnumberfield" /> <input type="button" value="open popup" onclick="fn();" /><br/>
<input type="submit" />
</form>
</BODY>
</HTML>
If I understand your question correctly, one solution would be to set the control that closes your popup/lightbox to first populate some hidden fields on the underlying form. Grab the values from the form elements within the lightbox window:
$('#the_lightbox').find('.multiple_phone_fields')
.each( function(i,e){ // for each field
$('<input name=' + $(this).attr('name') + 'type="hidden"/>') // new, hidden
.val(this.value) // set hidden field value from this field
.appendTo('#the_main_form'); // and add to the underlying form
});
When you then submit #the_main_form, those hidden fields and values will come along. Obviously, you'll need to adjust the selectors for the specifics of your popup window or lightbox.
I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.
Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.
The form is implemented in the HTML as follows:
<FORM action="thought_post.php" method="post" name="thought">
<INPUT onfocus="this.select(); this.value=''"
type="text" value="Thought..."
size="72" />
<div class="megamenu" style="position: absolute; ;left: 478px; top: 11px;">
<ul>
<li class="downservices">Publish...</li>
<div class="servicesdropped">
<ul class="right">
<input type="hidden" name="privacy">
<li>Private</li>
<li>Friends only</li>
<li>Public</li>
</ul>
</div>
</ul>
</div>
</FORM>
and the javascript in the header of the same page is as follows:
<link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
</script>
<script language="JavaScript" type="text/javascript">
<!--
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
-->
</script>
If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!
Try assigning a name to your "thought" input. name is required for a form control to be valid for submission:
<INPUT onfocus="this.select(); this.value=''" type="text" value="Thought..." size="72" name="thought" />
As a side note, make sure your other input is valid markup as well, input tags should be self closing:
<input type="hidden" name="privacy" />
After making these changes and inspecting the form post with FireBug, I could see the correct value for "thought" go through.
Additionally, as the other answer mentions, you should separate your JavaScript and HTML and maybe accomplish this completely with jQuery.
Hope that helps!
Try setting an id for the privacy field (like, say, id="privacy") and selecting it with this:
getElementById("privacy").value = selectedtype;
By the way, you can put all the javascript in one <script> block:
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
</script>
You could also very easily handle the focus event on your input with jQuery so the scripting isn't down in your HTML.