I'm trying to use the below search form and js to search my site. However, whenever you type a word in the form and click submit the form them takes the users browser to http://example.com/?s=searchterm , but I want it to take them instead to http://example.com/searchterm and totally leave out the characters ?s=
<script type="text/javascript">
function submitform()
{
document.forms["searchsite"].submit();
}
</script>
<form id="searchsite" action="/">
<input type='text' name='s' placeholder='search'>
Submit
</form>
Any positive advice? Btw, no, I don't believe I can use htaccess and mod_rewrite since I already have rules set.
You could set an onsubmit handler to intercept the form’s submission and replace the default action with setting the location href. This relies on JavaScript being enabled in the client side:
<form id="searchsite" action="/" onsubmit="javascript:location.href=this.action + encodeURIComponent(this.elements.namedItem('s').value); return false;">
This escapes the search term so that if the user enters something with ? or / in it, the server will interpret that as part of the path instead of thinking that the client is trying to send a querystring or access some subdirectory. The return false; states that the browser should stop its normal form submission procedure since the onsubmit handler has already updated location.href, which will cause the browser to start navigating as soon as the onsubmit handler returns.
However, you really should supplement this with server-side code. For something this simple, the JavaScript can be there to make your URIs pretty while skipping an HTTP redirect (so that the browser goes directly to the requested page slightly faster than otherwise). But you should really have a server-side redirect that gets triggered whenever the GET s parameter is sent.
Extra note: you should really replace your submission script with a <button/>, like:
<button type="submit">Submit</button>
and just drop your <a/> and <script/> tags completely. You get all of the functionality you need by overriding the form submission handler itself, no need to try to intercept button clicks, etc. With this change, your form should now work when the user presses ENTER instead of requiring the user to TAB to the <a/>. Use the intended HTML elements for their intended purposes and hook into the right events ;-).
I assume that your question is only about the client-side of the code and that you already have figured how to get your server-side code to read the value from the URI path. Figuring out how to read the value, if it is submitted this way, would take me some time to research and would require more information about your server-side setup.
Instead of submitting the form, build the URL and then set the location. You can add an ID to the search term (s in this case) and then simply build the URL:
var searchTerm = document.getElementById("s").value;
document.location = "http://example.com/" + searchTerm;
Related
I'm using a form that has 3 parts, login, forgot password and registration. The initial view is the login form, but can be changed to the forgot password or registration form, which replaces the initial view by using JS.
I'm looking to post back to the page if validation isn't met. This seems to be working fine, and the field repopulates itself. However I can't get the right form to load when posted back.
For example, if the user is filling out the forgot password form, and fills in an invalid email address, the message at the top of the form will be correct, however the form that will appear is the default login form. Once the user clicks on the forgot password button, JS kicks it over to the forgot password form, and has the users invalid email address re-populated. Each form has a unique "form_type" hidden variable to differentiate between the three, so I can use this to check then load the right one. Ideally I would like to keep this as 1 page and use JS to swap between the three if possible.
I don't know how to get it to load the right form once posted back. It's using the below code to change between the forms. How do I link to the right form when posting back.
<a href="javascript:;" id="forget-password">
<a href="javascript:;" id="register-btn">
I'm not good with JS at all, and I think this is the issue. The front end and JS is all created by a third party, it's "Metronic" theme. Let me know if I need to include any JS. If it makes a difference, although the logic should be the same, I'm using codeigniter too.
EDIT All the functionality to swap between the forms is there, I just need it to POST back to the right form. This is what I have so far, if you click on the forgot password and enter an email address that is longer than 5 characters, you'll see what I mean. I obviously didn't ask this very well...
Once the user submits, and the form is posted back with errors, I need right form to pop up, rather than the default for the page. The tags above are the links used to swap between the different forms.
May be you can try on posting back to view also bring one extra variable say 'show_form'
in that show_form have you form id and based on that do jquery hide/show method
like $('#' + show_form).show() and other 2 hide.
you can try this.
I'm not sure I understand exactly what you're asking.
Do you need to have 3 forms in the same page and swap between them with JS?
If so, give each of the forms a unique ID and have 2 forms with display: none. then all you have to do (assuming you do not want to use jQuery) is just to change the style.
HTML:
<form id="first_form" class="form-visible">
...
</form>
<form id="second_form" class="form-gone">
...
</form>
<form id="third_form" class="form-gone">
...
</form>
CSS:
.form-visible
{
display: inline;
}
.form-visible
{
display: none;
}
JS:
function swapForms(id)
{
Swap-between-forms
}
differentiate the form with some variable . for example after submission form you can post back errors in variable name like if the submitted form is forgot password means define the variable name is $forgot like that. in view file check if(isset($forgot)) then set it's style as display block .
How can we redirect to another page after checking password without clicking on any button? After entering password it should check and automatically redirect to next specified page.
Do I need to add any function in text-box input tag?
//This is my HTML code.
<div style="margin-top:27%;margin-left:40%;">
<b><i>Enter pin</i></b>
</div>
<input type="password" id="pwd" autofocus required>
//This is the javascript.
<script>
function login()
{
logged_in=false;
var pin=documemt.getElementById("pwd").value();
if(pin=="hotel")
{
logged_in=true;
window.open("screen3.html","_self");
}
else
alert("Please enter correct pin");
}
</script>
Maybe this isn't a fully technical answer, but it is worth to mention here.
NEVER store passwords in javascript manifestly. User can open this file and just read it. For Your question, there is an answer.
You must have a php file that can check the password (get from the post).
<?php if(isset($_POST['pass']) && $_POST['pass'] == 'hotel') echo "ok"; ?>
Then using for example Jquery and AJAX on every change in input send ajax request to this php file with posted password. Than compare downloaded file with "ok", and if OK, use javascript window.location.replace("new url");
This is one from milions of possible answers. But remember that You should set session and remember login person, and check it on every other site. In other case, someone can enter manually the same url, that You are redirecting, and password isn't needed.
Hope it helps
Jacek
PS. this php file should also be protected for multiple password comparison, in other case it is easy to break easy passwords with bruteforce, knowing the mechanism.
PS 2. Nevertheless, in my opinion, You are doing something wrong, and this approach should be rethinked... My proposed answer also is very, very, very general. Too general.
UPDATE
Maybe better answer is to make a standart php script for logging with server verification and submit button. Then, using Javascript, hide submit button, and on input change simulate clicking it. But in that case, if password is wrong, the page should remember what the user has entered... It isn't difficult to write in php:
$input_value = isset($_POST['password']) ? $_POST['password'] : '';
But I really vote for leaving the submit button as the mother nature learned us ;).
Thx for replies, best regards.
First off you need a way to connect your input element to a function, if you don't want to use a submit button you could use some sort of on-change/on-keyup handler to detect input.
Javascript bind keyup/down event
In this function I'd recommend a better way of validation, like Jacek said.
When you figured out how to do that, you might want to take a look at this question:
How can I make a redirect page in jQuery/JavaScript?
Use of onKeyUP Event of input text as below Example.
<input type="text" onKeyUP="login();" id="pwd">
<script>
function login()
{
logged_in=false;
var pin=documemt.getElementById("pwd").value();
if(pin=="hotel")
{
logged_in=true;
window.open("screen3.html","_self");
}
else
{
alert("Please enter correct pin");
}
}
</script>
Demo Of onkeyUp
.keyup()
I hope it will help you.
When document is loaded or ready you can do
$('#pwd').onkeypress = login();
to bind the login to the keypress handler of your pwd box.
When 'logged_in == true' You can do a 'window.location = "http://www.google.com"' to redirect to your target page.
I guess there should be some parameter (session id?) or similar to verify that the user not just used the url by hand.
After validating your login data, use Response.Redirect("YourPage.aspx", False). It will redirect you to the page you specified.
I'm relatively new to programming, but understand the basics of HTML, CSS, and Javascript (including jQuery). Due to my greenness, I'd appreciate it if answers contained both a simple solution and a reason as to why the solution works. Thanks!
So I've got a form, with a text input and a submit button:
<form>
<input type="text">
<button type="submit">Submit</button>
</form>
When the user types data into the text field and clicks submit, how do I gain access to this data? If a user inputs their name, how do I grab that information? I don't intend to store it or write it anywhere, just to hold onto it as a variable in javascript, which I'll assign to a jQuery cookie.
So how do I access the data that the user has submitted, preferably using only Javascript (with jQuery)? Thanks for the help!
You access the data on the server side (in PHP via $_POST['username'] for example). The form sends data to your sever for any named input, so you would probably have to change the input to:
<input type=text name=username>
If you want to access it on the client side (with JavaScript), you can do that too, but you have to prevent the form from submitting:
$("form").on('submit', function (e) {
$.cookie('username', $(this).find('[name=username]').val());
//stop form from submitting
e.preventDefault();
});
say you had an html input tag such as:
<input id="textfield" type="text">
using javascript, you can store the value of that field in a variable like this:
var inputvalue = $('#textfield').val();
of course, you'll need something to run the script.
the reason this works is that the the textfield is an object. you might think of it as a tree trunk with different branches coming out. one of these "branches" is the value contained inside of it. since you know jquery, you know that $('#textfield') gets the element by a selector. the period says we're getting one of the branches, and "value" says we want the branch that tells what's in the textfield.
hope this helps.
As a total newbie to web-based programming, I'm having trouble understanding why the pattern attribute field below fails to check the validity of the text field due to my javascript.
<form id="aForm">
<input type="text" pattern="^[ a-zA-Z0-9,#.-]+$" id="address" title="Standard address"/>
<input type="submit" id="open" value="Start"/>
</form>
The form contents are then sent to a javascript file which then sends it to the server via a websocket as in the code fragment below. However it ignores validating the form through the pattern attribute.
$(document).ready(function() {
$("#open").click(function(evt) {
evt.preventDefault();
var form = $('#aForm').serialize();
webSocket = new WebSocket("ws://localhost:9999/mh");
webSocket.onopen = function()
{
webSocket.send(form);
};
REST OF CODE....
It seems that for some reason this prevents the text from being checked before it's sent. I would like to know why and how to ensure that the form is validated by the pattern attribute.
Thanks
The HTML5 form validation is only performed when you're trying to actually submit the form, or when you explicitly use JavaScript to validate it1.
Since your JavaScript is bound to a different event (button click), form validation is not performed at that point. You can solve this by:
binding your submission to the form's submit event instead of button click, or
using the form validation API at the very beginning of your script.
I strongly recommend the first option. It makes more semantic sense and works right when the form is submitted though other methods (I don't remember if the button click will be simulated when someone presses Enter in the text field, and it definitely won't be triggered if JavaScript calls $('#aForm').submit() programmatically...).
1 At least, those are the only places I noticed - it's possible there are other events/circumstances when validation is done as well.
I have worked mostly with Python so far, so I'm a newbie when it comes to JavaScript. Now I need the latter to implement a form. I have some ideas and requirements in mind and would like you to tell me how to start and which frameworks or tools to use.
My requirements are:
The server-side logic will be implemented in Python and Django.
The entire form is located on a single webpage.
The overall design of the webpage should be done with Twitter Bootstrap.
When the page has been loaded, only the first field of the form is displayed.
When this field has been filled and validates correctly, display the second field of the form below the first field
When a new field gets displayed, its webpage should scroll down automatically if necessary, so that the new field gets centered in the browser. The scrolling should occur with some nice animation.
My form also includes some fields of type ChoiceField. Each choice has its own set of additional settings which will be implemented as form fields as well. Once a particular choice has been made, only the respective set of settings should be displayed but not all settings for all choice fields at the same time. (Can I probably do this with a simple if-else structure?)
When all fields have been displayed, filled and validated and the form has been submitted, the server does some computations. The results of these computations should be displayed below the entire form, once they are ready. The webpage should again scroll down automatically to the results. The best would be to scroll down the webpage to an extent where the form is not visible anymore but only the results. So this is probably dependent on the size of the currently opened browser window.
I know that all of this is possible and I've also seen forms like that from time to time but don't have a concrete example at the moment. I also know that all of this is possible with JavaScript. Can I implement all of the above with JQuery or do I need additional tools? It would be great if a JavaScript expert guided me a bit through this mess inside my mind. Thank you in advance!
Make it work
Before doing anything with javascript make a normal form that works. I.e. generate a form using whatever server side language you want, and when you submit the form it should do what you want it to do. If you have a form that works without javascript you have the confidence that it'll always work if the js breaks.
Make it work better/ Progressive Enhancement
There look to be 2 or 3 requirements for your js - treat them all individually:
1. The form should show only one input at a time
E.g. with markup like this:
<form id="myForm" method="post">
<legend>My Awesome Form</legend>
<div class="question">
<label for="x">X</label>
<input name="x" id="x">
</div>
<div class="question">
<label for="y">Y</label>
<input name="y" id="y">
</div>
<div class="question">
<label for="z">Z</label>
<input name="z" id="z">
</div>
<div class="submit"><input type="submit" value="Submit"></div>
</form>
Use some js like this:
$('.question', '#myForm').not(':first-child').hide();
$('input', '#myForm').change() {
var div, next;
div = $(this).parent();
next = div.next();
if ($(this).val() && next.length) {
parent.hide();
next.show();
}
});
Which would show only one of the question divs at a time, and show the next one (if there is a next one) when the input is filled.
2. Validate user input
To validate the user input, create a function that does that for you, returning true/false as appropriate and hook that into your js so that it doesn't continue if the input value is deemed invalid:
validate(field, input) {
var valid = false;
// implement your logic here to validate input
if (valid) {
return true
}
return false;
}
$('input', '#myForm').change() {
var div, next;
if (!validate($('this').attr('name'), $(this).val()) {
return;
}
div = $(this).parent();
next = div.next();
if ($(this).val() && next.length) {
parent.hide();
next.show();
}
});
That will prevent the user from moving onto the next input, if the current one has an invalid value.
3. Submitting the form by ajax
Clicking submit should send the form data to the server, in (almost) the same ways as submitting the form normally. the only difference should be that it response with either a json response that you parse, or a snippet of html that you dump at the end of the page:
$('#myForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data, textStatus, jqXHR) {
// handle success response
},
error: function(jqXHR, textStatus, errorThrown)) {
// show the user an error
}
});
});
All of the js written here is untested, it should give you some ideas about how to tackle each aspect of what you want to do - of course, for more information of any particular method refer to the docs.
All of this can be done with jQuery, you shouldn't need any additional JS tools.
Since you have a lot of functionality to build out, I'm not going to go into details. However, I can provide some insight into how to go about each step of your process.
1.) Thats fine.
2.) Thats fine too, you just need one html page to accomplish this.
3.) I would recommend having all forms created in HTML with a CSS of display none. Then as the user progresses through, you can use .show() to "show" the hidden elements.
4.) Probably going to want to have a "next" button of some kind outside of your form. Use .click() To trigger a function that does whatever form validation you require on the value of the input form field. You can use .next() to cycle through your form inputs.
5.) If you want a browser scroll use scrollTop or the jQuery ScrollTo Plugin. If your just looking to move things on the screen and not truely scroll, use .animate()
6.) You will have to set the value on the fly as a user progresses. So use .change() to do the detection.
7.) Before submitting, run your validator on all the fields again to ensure you have all correct data. You'll want to use .ajax() to make the request to your service and prevent default on the actual form submit. Take the response you get back from the service and format the information accordingly.
That should give you insight on how to accomplish your project. Good Luck!