Search form, if no value go to site - html

I have a search form which searchers wikipedia.com. Nothing fancy, a form with an input.
If the input is empty, currently the user is redirected here: http://en.wikipedia.org/w/index.php?title=Special%3ASearch&redirs=1&search=&fulltext=Search&ns0=1 .
Id like to redirect the users here: www.wikipedia.com instead
How can I do this?
This is my search form:
<form method="get" action="http://en.wikipedia.org/w/index.php">
<input type="hidden" value="Special:Search" name="title"/>
<input type="hidden" value="1" name="redirs"/>
<input type="text" name="search">
<input type="hidden" value="Search" name="fulltext"/>
<input type="hidden" value="1" name="ns0"/>
</form>

It's not possible, I don't think, without using JavaScript; if, as you've indicated, you're willing to use jQuery:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).attr('action','http://www.wikipedia.com/');
}
else {
$(this).submit();
}
});
JS Fiddle demo.
In plain JavaScript, the following seems to work (tested in Chromium 12 and Firefox 7 on Ubuntu 11.04):
var formEl = document.getElementsByTagName('form')[0];
var inputs = formEl.getElementsByTagName('input');
var textInputEl = [];
for(i in inputs){
if (inputs[i].type == 'text'){
textInputEl.push(inputs[i]);
}
}
formEl.onsubmit = function(){
if (textInputEl.value === '' || textInputEl.value === null){
this.action = 'http://www.wikipedia.com/';
}
else {
formEl.submit;
}
};
JS Fiddle demo.
I'm trying to set this up so that, with an empty text-input, the form will remove any hidden elements and then set the action, or the document.location to be http://en.wikipedia.org/wiki/Special:Random. This does not, for some reason, seem to work. Almost as if Wikipedia's finding something wrong and then redirecting to a different page. Ungh. Anyways, this is what I tried:
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
$(this).attr('action','http://en.wikipedia.org/wiki/Special:Random');
}
else {
$(this).submit();
}
});
JS Fiddle demo;
$('form').submit(
function(){
if ($(this).find('input:text').val() == ''){
$(this).find('input:hidden').remove();
document.location.href = 'http://en.wikipedia.org/wiki/Special:Random';
/*
I also tried 'document.location','window.location'
and 'window.location.href' all of which, predictably,
failed in exactly the same way.
*/
}
else {
$(this).submit();
}
});
JS Fiddle demo;

Related

Multiple <form> tags in different locations with the same target iframe?

I have an iframe in the content area:
<iframe name="my_iframe" frameBorder="0" height="200" src="about:blank"></iframe>
I have a submit-button under it:
<form action="includes/action.php" method="post" target="my_iframe">
<input type="submit" value="Submit">
</form>
And I want some checkboxes in another area:
<form action="includes/action.php" method="post" target="my_iframe">
<input type="checkbox" name="option">
</form>
But it doesn't work, the submit-button works but it doesn't send the checkbox.
I can't put everything in one -tag because I want the checkbox in a sidepanel of the main-view and the submit-button on a page that is in another page. (Loaded per ajax? I'm using frameworks7 btw.)
Is it not possible with different form-tags or is it because of the ajax thingy?
EDIT1: I managed to build an example for easier understanding with plunker, it doesn't work with php and I don't have a webspace right now, but you get the idea.
http://plnkr.co/edit/dfqzCbeQWgg9hAyCpGpb
UPDATE 2
To get a cleaner result without the stale cache confusing tests I have updated it, please review newest update:
http://plnkr.co/edit/34KOyh9rIEGV3bXNsD9F?p=preview
UPDATE
Now that I was provided with a very complete and nicely coded demo, I have solved your problem.
http://plnkr.co/edit/Z2I1Q2swIXmFfynalaLB?p=preview
Note: I'm using a test server, so the cache may be stale. Just change the action by adding a number to the end.
Example
change:
http://www.hashemian.com/tools/form-post-tester.php/so_post_chk
to:
http://www.hashemian.com/tools/form-post-tester.php/so_post_chk1
When the checkbox is checked, your result should be cache=on
When the checkbox is not checked, your result should be cache=
You could assign one or more inputs (usually type="hidden") outside of the forms and collect whatever data from anywhere on the page regardless of which form it originated from.
http://plnkr.co/edit/er5RoJ049xSBwtR7gtTI?p=preview
This demo revolves around a simple JS function:
function toOutput(x) {
var str = x.toString();
var out4 = document.getElementById('out4');
out4.value += str;
}
Note the special condition for checkboxes:
if(this.checked) {
toOutput(this.value);
text1.value += this.value;
};
It's needed because when the click event is triggered on a checkbox, it is considered on every click checked and unchecked. I assume that the checkbox value is collected when it's actually checked.
I got option onsubmit form ...
Try it:
Create test.php file:
<form id="myForm" action="includes/action.php" method="post" target="my_iframe">
<input onclick="myFunction()" type="submit" value="Submit">
</form>
<form action="includes/action.php" method="post" target="my_iframe">
<input id="cbopt" type="checkbox" name="option" value="option" checked="checked">
</form>
<script>
function myFunction() {
var y = document.createElement("input");
y.setAttribute("type", "checkbox");
y.setAttribute("value", "option");
y.setAttribute("name", "option");
y.setAttribute("checked", "checked");
document.getElementById("myForm").appendChild(y);
var x = document.getElementById("cbopt").name;
document.getElementById("demo").innerHTML = x;
var z = document.forms.length;
document.getElementById("demo").innerHTML = z;
}
</script>
Code for includes/action.php :
<iframe name="my_iframe" frameBorder="0" height="150" width="555" src="about:blank">
<p id="demo"></p>
</iframe>
<?php
//$site = $_POST['doorde'];
//$url = $_POST['doordie1'];
$opt = $_POST['option'];
echo $opt;
?>
Try and comment me ...
Here's what you can do, copy the values from one form to the other before submitting, making sure you remove fields added previously when you submit again.
<form action="includes/action.php" method="post" target="my_iframe" id="myform">
<input type="submit" value="Submit">
</form>
<form action="includes/action.php" method="post" target="my_iframe" id="otherform">
<input type="checkbox" name="option">
</form>
<iframe name="my_iframe" frameBorder="0" height="200" src="about:blank"></iframe>
<script>
function copyFormFieldsIntoHiddenFields(from, to) {
var elementsAdded = [];
for (var i = 0; i < from.elements.length; i++) {
var nodeToCopy = from.elements[i];
// Unchecked checkboxes do not get sent to server
if (nodeToCopy.type != "checkbox" || nodeToCopy.checked) {
var hiddenField = document.createElement('input');
hiddenField.type = "hidden";
hiddenField.name = nodeToCopy.name;
hiddenField.value = nodeToCopy.value;
to.appendChild(hiddenField);
elementsAdded.push(hiddenField);
}
}
return elementsAdded;
}
var addedFields = [];
document.getElementById('myForm').addEventListener('submit', function() {
// Remove any fields that were previously added
for (var i = 0; i < addedFields.length; i++) {
this.removeChild(addedFields[i]);
}
// Add the new hidden fields
var copyFrom = document.getElementById('otherform');
addedFields = copyFormFieldsIntoHiddenFields(copyFrom, this);
});
</script>

How to keep a form from being submitted if not filled up using javascript?

(I copied the code below from a tutorial but it dose not work out, and I wonder if I should do something specific on the page receiving the submitted data. )
<script>
function stopsubmit()
{
document.getElementById("submit").addEventListener("click",function(event)
{
if(document.getElementById("name").value="")
{
event.preventDefault();document.getElementById("erroeMessage").innerHTML="Please write your name";return false;
}
else
{
return true;
}
}
)
}
</script>
You can use onsubmit and return false to prevent submitting. A form can only have one onsubmit function though.
<form onsubmit="return validate();">
<input id="aField" type="text">
<input type="submit">
</form>
<script>
function validate() {
if(document.getElementById("aField").value.length == 0) {
alert("Hold it right there, buddy!");
return false;
}
return true;
}
</script>
Your code snippet has syntax errors, e.g.
if(document.getElementById("name").value="")
Must double equality instead one.
Your sample is worked in this fiddle (with my sample html):
Jsfiddle link

HTML AutoFocus in a input field with value

first, if anyone has another more specific and better title for this question please tell me and I'll change. I've never been good at using Google so...
I'm currently using following code to create an input field
<input name="igname" type="text" maxlength="40" autofocus="autofocus" value="Hi">
It works fine, but there's just one problem -> the cursor is on the left, I want it to be on the right but I don't have any idea how to do so.
Thanks in advance
JoDev's answer does not seem to work with FF and could be simplified. el is the DOM element representing the input.
function moveCursorToEnd(el) {
'use strict';
var index=el.value.length;
el.focus();
el.setSelectionRange(index,index);
}
First idea
Use style='text-align:right' to change the text align.
PUT THE CURSOR TO THE END
To put the cursor to the end of editable element, use this : tested function | fiddle
For the fiddle, it works great on Chrome, but in FF, you have to give focus to the element because the IFRAME haven't got focus by default!
moveCursorToEnd = function(el, focused) {
console.log('go');
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
if(!focused)
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
if(!focused)
el.focus();
}
onbodyload = function() {
elem = document.getElementById('totheend');
moveCursorToEnd(elem);
}
<body onload='onbodyload()'>...
<input class='totheend' onfocus="if(typeof moveCursorToEnd != 'undefined') moveCursorToEnd(this, true)" name="igname" type="text" maxlength="40" autofocus="autofocus" value="Hi" >

jQuery Trigger onKeyup Event

I have a SELECT LIST MENU containing products and on this menu i use onChangeevent. when you select any product, it load company name of that product.Below is the function which i used,
function getcompany(element) {
var strURL="getcompany.php?product="+element.value;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
element.parentNode.parentNode.getElementsByClassName('companydiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
And my html code is,
<select name="product" onChange="getcompany(this)">
<option value="1" >Product1</option>
<option value="2" >Product2</option>
</select>
<div class="companydiv">Product result will be shown here</div>
The above code work but now i want to use jquery autocomplete instead of SELECT LIST MENU because my product list containing more then 1000 products.
My Autocomplete code is,but i dont know where i'm wrong
<input name="product" id="product" type="text" onkeyup="getcompany(this)" />
Some other answers i already checked but i'm not satisfied with anyone, some of them are below
jQuery AutoComplete Trigger Change Event
Jquery Autocomplete onChange event
http://forum.jquery.com/topic/autocomplete-and-change-event
I could not find your error here, however I could make what you are trying to do. I used jquery here. jsFiddle

How can I assign different actions for different submit buttons in same html form?

I am trying to assign different actions to same html form according to different submit buttons.
Can I do something like this ?
<FORM>
------
<INPUT type="submit" value="DoSomething" action="DoSomething.pl" method="POST">
<INPUT type="submit" value="DoSomethingElse" action="DoSomethingElse.pl" method="POST">
<FORM/>
Just in case someone else finds this post:
If you're using HTML5, this is now easier thanks to the formaction attribute. This attribute applies to input and button elements of type="submit" and forces the form to submit to the location specified in the formaction attribute of the clicked element.
Then only drawback of this attribute is that it's not supported by Internet Explorer 9 and lower, but this limitation can be easily overcome using a little JavaScript.
Example:
<form method="post" action="go_default">
<input type="submit" value="Go Left" formaction="go_left" />
<input type="submit" value="Go Right" formaction="go_right" />
</form>
For IE 9 and lower:
<script type="text/javascript">
$(function () {
var $submit = $('form [type="submit"][formaction]');
$submit.click(function() {
var $this = $(this),
action = $this.prop('formaction'),
$form = $this.closest('form');
$form.prop('action', action).submit();
});
});
</script>
No. A form has only one action (action being a property of the form, not the submit button).
The target of the action can do different things on the basis of the values in the form. So, you might want to start naming your submit buttons.
Learn HTML before you even think about writing and deploying a CGI script.
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="action" value="DoSomething">
<input type="submit" name="action" value="DoSomethingElse">
</form>
Note also that choosing an action based on the value of the submit button is a losing strategy if you wish to internationalize the application because the value of a submit button is what the UA displays to humans.
Therefore, script should decide what to do on the basis of some other input element's value.
For example, CGI::Application looks at a run_mode parameter.
Alternatively, you can use different names for your submit buttons as Alec suggests. In that case, you need to check which submit button was pressed by going through the names of the parameters passed to your script which, IMHO, makes the dispatch slightly more cumbersome. It also means it is possible for someone to pass values for all submit buttons to your script (not via the user interface, but via curl or wget or similar programs.
For example, given the HTML
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="submit_left" value="Go Left">
<input type="submit" name="submit_right" value="Go Right">
</form>
here is how your script may handle form submission:
#!/usr/bin/perl
use strict; use warnings;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my %dispatch = (
left => \&handle_left,
right => \&handle_right,
);
my #actions = grep s/^action_(right|left)\z/$1/, $cgi->param;
my $handler = \&handle_invalid_action;
if ( #actions == 1) {
my ($action) = #actions;
if ( exists $dispatch{ $action } ) {
$handler = $dispatch{ $action };
}
}
else {
$handler = \&handle_too_many_actions;
}
$handler->($cgi);
sub handle_left { }
sub handle_right { }
sub handle_invalid_action { }
# because it may indicate someone trying to abuse your script
sub handle_too_many_actions { }
You can also use Ajax for this, and every button has assigned an ajax function that calls it's own php script and you don't even need to refresh the page or redirect, like in this example that i have tried:
HTML:
<input type="submit" value="Make other thing" onclick="ajax_post1();"/>
<input type="submit" value="Make something" onclick="ajax_post2();"/>
<div id="script1Response"></div>
<div id="script2Response"></div>
Javascript functions:
//the first function
function ajax_post1(){
var hr = new XMLHttpRequest();
//take the values from the html input elements you want to use
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
//the script that will process the data
var url="php_script1.php";
//the variable that will contain the information for the php script
var dataVar="var1="+v1+"&var2="+v2;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script1Response").innerHTML = script_response;
}
}
// Send the data to php_script1.php
hr.send(dataVar); // Actually execute the request
document.getElementById("script1Response").innerHTML = "processing...";
}
//the second function
function ajax_post2(){
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
var url="php_script2.php";
var dataVar="var1="+v1+"&var2="+v2;
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script2Response").innerHTML = script_response;
}
}
hr.send(dataVar);
document.getElementById("script2Response").innerHTML = "processing...";
}
The php files will have to contain some variables that will store the values sent by dataVar parameter like this:
$var1_=$_POST['var1']; //the var1 from the dataVar parameter
$var2_=$_POST['var2']; //the var2 from the dataVar parameter
The example I used can be found here:
https://www.youtube.com/watch?v=woNQ2MA_0XU.