This is my form:
<form id="search_form" method="get" action="" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="cerca nel negozio">
<input id="search_button" type="submit" value="" onClick="submit_f()">
</form>
This is "submit_f()":
function submit_f(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}
What I'm trying to do is to redirect the user to different pages based on what he enters:
- If he enters words he'll be redirected to "/search/?query=words".
- IF he enters an url (http://store.steampowered.com/app/202170/?asp=123) he'll be redirected (in this case) to "/app/202170".
But my code isn't working, any help?
You aren't returning anything from your event handler function:
onClick="submit_f()"
should be
onClick="return submit_f()"
You should give your form a
onsubmit="return false"
to avoid the default submitting behaviour. Also, your button could be type=button instead of type=submit, but that's not always enough (some browsers will still submit it), the sure way is onsubmit.
remove the onclick from your html
document.getElementById('search_button').onclick = function(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}
Related
I need to be able to create a query based off the users input of "Test" in an INPUT of Site A (SiteA.com) that will open Site B in the same window once submitted, passing along the query (SiteB.com/search.aspx?k=test).
Code on SiteA.com
var siteSearch = "SiteB.com/search.aspx";
$("#sitesubmitBtn").click(submitClick);
function submitClick() {
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
var k = $("#sitesearchInput").val();
window.location.href = q + "?k=" + k;
return false;
}
<input name="search" placeholder="Search" id="sitesearchInput" type="text">
<button id="sitesubmitBtn" type="submit"></button>
You are describing a simple HTML form. You don't need JavaScript/jQuery for that to happen.
<form method="GET" action="//SiteB.com/search.aspx">
<input type="text" name="k" placeholder="Search term" />
<button type="submit">Search</button>
</form>
change this line
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
to :
var q = $(location).attr('protocol') + "//" + siteSearch;
because you already define your hostname in this line:
var siteSearch = "SiteB.com/search.aspx";
The function receives the username and password of the user. If either are left empty, nothing happens and they won't be linked to google.ca if they click the "Go" button. If they filed in the required sections then they will be directed to google.ca. For some reason, if any of the text boxes are left unfilled and the Go button is pressed, it brings me to a 404 error page when I want it to just stay on that page until the user fills the textbox. What is causing this problem? This is the HTML file.
<form action="index.php" method="get" id="form" onsubmit="return go(document.getElementById('username'), document.getElementById('password'))">
<table>
<tr><td>Username: <input type="text" name="username" maxlength="16" id="username" onKeyUp="updateLength('username', 'usernameLength')" onblur="checkTextField(this);"/> <span id="usernameLength"></span></td></tr>
<tr><td>Password: <input type="password" name="password" maxlength="50" id="password" onKeyUp="updateLength('password', 'passwordLength')"> <span id="passwordLength" onblur="checkTextField(this);"></span></td></tr>
<tr><td><input type="submit" value="Go" id="goButton" onclick="go(username, password)"/></td></tr>
</table>
</form>
And here is the js file
function loginFunction() {
var url = "login.html";
window.open(url);
}
function createAccountFunction() {
var url2 = "createAccount.html";
window.open(url2);
}
function go(username, password) {
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
function updateLength(field, output) {
var curr_length = document.getElementById(field).value.length;
var field_mLen = document.getElementById(field).maxLength;
document.getElementById(output).innerHTML = curr_length + '/' + field_mLen;
}
function checkTextField(field) {
if (field.value == '')
alert("Field is empty");
}
You aren't stopping the default event of the onsubmit. You can do that by changing your go function to:
function go(username, password) {
return function(event) {
event.preventDefault();
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
}
You also don't need the return in the HTML. Just call the function.
I didn't understand your code logic, but maybe I can offer you a way to fix your code by yourself.
You have a form and a button. If you click on the button you execute the go() function. Because the button is a submit button, on the same click you execute one more time the go() function.
My advice is to create a new function, you may name it validate():
function validate() {
var username = document.get........
var password = document.get........
// more logic here, if need
if(!username || !password) {
return false;
}
return true
}
and now, your submit button looks like:
<input type="submit" value="Go" id="goButton" onclick="return validate()"/>
The form won't submit if the validate() function returns false.
Hope this helps.
I have some (more than thousand) users that insist on logging in just with their names, but a system that insists on having the full e-mail address (name + #my-mail.com) provided. Which is a smart solution to add a suffix to a field without bothering the user?
The Form:
<form id="login_form" action="processing.php" method="post" class="form">
<fieldset>
<ul class="input_block">
<li>
<input type="text" name="email" id="email" value="" />
</li>
<li>
<input type="password" name="passwort" id="password" />
</li>
</ul>
</fieldset>
I played around with the key up function for the field, but it didn't help much.
<script>
$('#email').keyup(function(e){
if(this.value.length > 12){
this.value = this.value + '#my-mail.com';
if( this.value.indexOf('#my-mail.com') <= 0 ){
this.value = String.fromCharCode(e.which) + '#my-mail.com';
}
});
</script>
I consider a solution that manipulates the field just right before the submission much more "proper" (sadly I don't have access to the PHP file that is receiving the submission). So I tried as well with the submit function, this didn't work either.
<script>
$( "#login_form" ).submit(function( event ) {
("#email").value = ("#email").value + '#my-mail.com';
});
</script>
Anybody some advise on how to solve it using the submit function or another idea that seems to be better?
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#my-mail.com') == -1)
$(this).val(val+'#my-mail.com');
});
http://jsfiddle.net/g4oLtfw7/
This will add the '#my-mail.com' suffix if it's not already part of the input value. If you want to allow other types of emails, but default to 'my-mail.com' otherwise, try this:
$('#email').change(function() {
var val = $(this).val();
if(val.indexOf('#') == -1)
$(this).val(val+'#my-mail.com');
});
Either:
$('#login_form').submit(function (e) {
var email = $('#email'),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
or
$('#email').change(function (e) {
var email = $(this),
user = email.val().split('#')[0],
domain = '#my-mail.com';
if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
email.val(user + domain);
}
});
is how I would approach this (obligatory fiddle: http://jsfiddle.net/e84v7nat/).
This approach ensures that your user has a domain specified and that the domain is correct. If the username is case-sensitive, remove the calls to .toLowerCase.
http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.
I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});
$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});