I FORMULATED MY SELF VERY BADLY!
I will start over :) I appreciate your good answers, and if you can, try answering this: ( I will try to be more specific this time)
What I want is, that a <form>element onsubmit, onclick of a button or whatever takes the value of an <input type="text" value="Default value"> and inserts it in a couple of <span>elements, I like to call "placeholders". This sample might explain it a little better:
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("input[type=button]").click(function //click the button
{ do_the_magic_thing() //make the value from id="txt_inp" appear in class="placeholder"
});
});
</script>
</head>
<body>
<form method="POST" action="" id="theForm"> //could also be get, I don't care
<input type="text" id="txt_inp" value="Default Value" onfocus="if (this.value == Default Value) this.value=''"> //this SHOULD make the Default Value dissapear on focus
<input type="button"> //could also be a submit
<span class="placeholder"></span> //$("#txt_inp").value; goes here
<span class="placeholder"></span> //$("#txt_inp").value; goes here
</body>
Now, is it really as simple as this?:
var do_the_magic_thing = function() {
$(".placeholder").html = $("#txt_inp").value;
};
I'm going to bed now - it's late in Denmark :) I will answer your comments tomorrow :)
OLD POST:
I am very new to this jQuery thing, but I do understand the basics and all. Let's simplify and say I have a form which looks like this:
<form method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
I've tried with $.post, but I just cannot get it right; it's not working for me.
Now, I would like to cancel the submit (can't that be done by just adding a return false; in the function returning the value, if a such is present?), but this is not crucial.
I think I typed in something like
$.post("test.php", function(data) {
alert("This is the data submitted (and cancelled):" + data);
}); //I have also tried without the "test.php", that's not it
Can you tell me, what I'm doing wrong please? :)
NOTE
It is not necessary, that the submit is cancelled, but I would like that
Nor is it necessary, that POST is the method used, but once again, this is what I prefer
Change the id of your form to "myform" or whatever and the name of your text input to "myinput", and try something like this...
$(document).ready(function() {
$('#myform').submit(submitMyForm);
})
function submitMyForm(e) {
var data = new Object();
data.whatever = $('#myinput').val();
var post = new Object();
//here I use a jquery json extension...you can use anything you like
post.data = $.toJSON(data);
$.post("test.php", post, function(returnval) {
alert(returnval);
}, "text");
//this is to stop the normal form submit action
return false;
}
Then in your test.php you can access it by calling $_POST['data'] (we specified this when we created the property of the "post" object called "data" like this: post.data = 'whatever'.
To answer the revised version of your question, yes, it really is that simple, although the correct syntax for your "do the magic thing" function is the following:
var do_the_magic_thing = function() {
$('.placeholder').html($('#txt_inp').val());
};
P.S. Don't worry too much about not expressing yourself, your English is much better than my Danish.
I think what you want to do is something like this:
<fieldset id="myData">
<legend>My Data</legend>
</fieldset>
<form id="myForm" method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
$(function() {
$('#myForm').submit(function() {
//do whatever you want here.
//this will take place after the form is submitted, but before your ajax request
$('input[type=text]').each(function() {
$('#myData').append('<div class="placeholder">' + $(this).val() + '</div>');
});
//serialize your form data
var toSubmit = $('input[type=text]').serialize();
//do ajax here
$.post('test.php', toSubmit, function(data) {
alert('Your AJAX POST request returned: ' + data);
}, 'text');
//this will prevent the form from submitting normally
return false;
});
});
Here's a demo of this in action: http://jsfiddle.net/SA3XY/
Also see my comment on your question.
Well for the form submit you need to add the following to the form to cancel the default submit event:
<form onsubmit="return functioncall();">
Then when you return false from the function it will cancel the default form action.
EDIT: If you would like to see all the data that is to be submitted you can serialize the form using jquery serialize() method or serializeArray() method.
If you're trying to accomplish validation, there's a much easier way, just use a validation plugin like this one:
http://docs.jquery.com/Plugins/Validation
Makes it much easier and takes the headache out of developing your own code. Jquery makes it easy to develop powerful javascript applications...but sometimes it's just easier to use stuff that's already been written and debugged (for the most part at least).
Related
I have tried using methods that may work for one scenario or another in AJAX, Javascript, JQuery and PHP, but I have not found a way to achieve the correct results for my scenarios.
I have a search box text input field as :
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
There are three scenarios in which different actions need to occur:
On page load, send the input to search-api.php as POST every 5 seconds in the background, and get results back from the action and set the response equal to $url. (Must not only show response for first submit, but also for all changes in input when updated every 5 seconds).
When enter button is pressed, send the input as GET to https://externalaction.com/search in foreground.
When button <input class="button default" name="BtnX" type="submit" value="Search"> is pressed, send the input as GET to https://externalaction.com/search in foreground.
I know this is complicated but I have yet to find a solution that works for all three scenarios without interfering with each other, and no one online seems to have any information or questions quite like this situation.
Thank you to anyone who has any help, tips, or answers / code!
This doesn't seem too complicated, although I'm not sure why you'd want to send search queries every 5 seconds instead of on keypress? In any case it should just be using $.post() and setTimeout.
<form action="https://externalaction.com/search" method="get">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
<div id="results"></div>
<script>
$(function() {
search();
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
setTimeout(search, 5000);
}
</script>
If you're interested in using keypress instead of every 5 seconds, it would be something like this for the JS:
<script>
$(function() {
$('#field').on('keyup change', 'search');
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
}
</script>
Although in this case you don't need a named function, you could just make the search() function the keypress callback.
You also mentioned wanting to set the AJAX response to $url, however that looks like a PHP variable, so you wouldn't be able to modify that if it's in the page with the form unless you reloaded it. That's easy enough to do if you wanted to programmatically do a redirect, but would get pretty tricky and into weird loops. So it would be better to know what $url is being used for in the page, and then use JS to replace it with the value from the callback the same way I'm replacing the HTML of the results div in my current example.
The search form field will submit automatically on an 'enter' keypress as long as it has focus (i.e. after someone is finished typing in it and hits 'enter'), but if you want to send results whenever enter is pressed regardless of which input has focus this answer will help.
As an aside, typically you don't want to recursively keep searching with a timeout without some kind of end condition which clears the timeout, as in some cases it can lead to memory issues.
first of all you should search input is a form and need form tag even if it's only one input. lets consider it like this:
as you set set button type to submit. the 2 and 3 options would work.
<form id="search-form" action="https://externalaction.com/search" method="GET">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
second of all in case if in some situations (really rare) some browsers didn't work properly with type="submit" for enter button you should use jQuery like this one:
$(function() {
$("#search-form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#search-form button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
for autocomplete search you can use many exist libraries or write it yourself I recommend to read this article for an example:
http://ianlunn.co.uk/articles/ajax-search-suggest-wearehunted/
actually if you use a standard form element the only thing you are looking for is just a autocomplete search input which i believe users used to see result by typing each word instead every 5 second. but its up to you.
Edited according to your last comment:
if you have a single action for search you should at least use two different view.
to use autocomplete feature you should use ajax and if you want to have only one action or page just send an extra parameter and make a partial-view which echo result back in Json instead of a complete view which contains header and footer and ...
Function searchData() handle the AJAX request. setInterval(function(){searchData()}, 5000) section handle request search content every 5 second. If click on Enter key, then that request handle on keydown event, finally click function handle the request come through the search button.
search.php
<!--- Search field and button -->
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input type="button" name="search" id="search" value="Search"/>
<!--- Display result -->
<span id="res"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
// function used for AJAX call
function searchData(){
var txt = $("#field").val();
$.get("searchData.php", {search: txt}, function(result){
$("#res").html(result);
});
}
// search every 5 second
setInterval(function(){searchData()}, 5000);
// if press enter button search
$('#field').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
searchData();
}
});
// if search button press
$("#search").click(function(){
searchData();
});
});
</script>
searchData.php - Page used to handle the request
<?php
// testing purpose
echo $_GET['search'];
?>
I'm using jQuery v1.7.1 in my project.
I've following HTML form:
<div class="alert-danger">
</div>
<form action="index.php" class="navbar-form pull-right" id="formzip" method="post">
<input type="hidden" class="form-control" name="op" id="op" value="zip_code">
<input type="hidden" class="form-control" name="form_submitted" id="form_submitted" value="yes">
<input style="width: 115px;" type="text" placeholder="Enter the zip code" name="zip" id="zip" value=""> <i class="icon-zip" style="margin-top:3px;" onclick='$("#formzip").submit();'></i>
</form>
Now here I want to validate the form with id="formzip" using jQuery. Following validations need to apply:
If the input field having id zip doesn't contain any value at the submission of a form.
If the input field having id zip contains invalid US zip code value or any value which is not a valid US zip code.
I want to show relevant error messages in a <div class="alert-danger"></div> and want to prevent the form from submission. That is the page currently displaying should remain as it is.
The necessary regular expression string to validate US zip code is as follows :
"/^([0-9]{5})(-[0-9]{4})?$/i"
Can someone please help me in achieving this functionality?
It will be of immense help to me if someone could help me.
thanks for spending some of your valuable time in understanding my issue. If you want any further information regarding my issue please feel free to ask me.
Waiting for your precious replies.
Thanks in advance.
you can do something like this:-
$(function(){
$('#formzip').on('submit',function(){
if($('#zip').val()=='')
{
$('.alert-danger').html('zipcode is empty');
return false;
}else if(!isValidZip($('#zip').val()))
{
$('.alert-danger').html('zipcode is invalid');
return false;
}
});
});
function isValidZip(zip) {
var pattern = new RegExp(/^([0-9]{5})(-[0-9]{4})?$/i);
return pattern.test(zip);
};
or if you want to show same message you can do this:-
$('#formzip').on('submit',function(){
if(!isValidZip($('#zip').val()))
{
$('.alert-danger').html('zipcode is invalid');
return false;
}
});
Demo
You do not need to use any custom validation library for this.
First stop the submit event and let your validation rules run.
Remove your onClick event for i elem.
Just some thoughts. Another person might have different approach.
$(document).ready(function(){
$(".icon-zip").click(function(){
$(".alert-danger").html("");
var zip = $("#zip").val();
//run validations
var regex = /^([0-9]{5})(-[0-9]{4})?$/i;
if(!regex.test(zip)){
$(".alert-danger").html("Invalid zip");
return;
}
//if all ok
//do ajax request to server with your data
//Handle server response in ajax callback functios
$.ajax(function(){
url:"index.php",
type:"post",
dataType: 'json',
data: $("formzip").serialize(),
success:function(data){
if(data.status == "ok"){
// show success msg
}
},
error:function(data){
// show error msg
}
});
});
});
I hope bellow content and reference can help you
http://jqueryvalidation.org/
and view Demo from
http://jqueryvalidation.org/files/demo/
I have following form structure
<form action="{Basket-Addproduct}" method="post" id="items-form">
<button class="button-text button-gray-custom" type="submit" value="Submit" name="{dynamically generated name}"><span>Submit</span></button>
</form>
here "dynamically generated name" is the key field which tells which element or product to submit..
I want it to convert it into link,
I have tried following
Add This
Its getting submitted but not able to add the product...
Its expecting the name parameter also to be passed so it knows which product to add...
Stuck....:(
Any solution appreciated...
you should have <input type="submit".
There is no need to do JavaScript.
Just remove JS and then have as many <input type="submit" buttons as you want.
The GET/POST should have the key/value you look for.
E.g.
<input type="submit" name="item1" value="submit" />
when you click it, the recipient receives (sorry PHP used here):
$_GET['item1'] = submit
and other submits do not have value.
You can use jQuery to do this clean and easy.
So, here's your link:
<a id="form-submit-btn" href="#" name="{dynamically generated name}">Add This</a>
And your form:
<form action="{Basket-Addproduct}" method="post" id="items-form">
<!-- form contents -->
</form>
Now write a JavaScript which submits your form data on a button click:
$('#form-submit-btn').click(function(e) {
e.preventDefault();
var $form = $('#items-form');
$.post($form.attr('action'), $form.serialize(), function(data){
// do something with the data
});
});
Your code should work, I have created an example for you to test, here it is: http://jsfiddle.net/afzaal_ahmad_zeeshan/yFWzE/
<form id="form">
<input type="text" name="something" id="something" />
</form>
Submit
By using this you will submit the form using the id of it. And other user told you to use jQuery, which I am afraid you don't want to. In jQuery you use .preventDefault but if you want to stick to the simple JS then you will be using href="#" which will automatically prevent any anchor tag execution.
And the result of the request can be checked, which sadly is an error. But it makes sure that the request has been sent to the server.
Then you can test the methods and other type of executions by having some if else blocks as
if(condition == true) {
// if post
} else {
// if get
}
The parameter might be mis handled on the server side, because when the form is submitted you need to take out the data from the QueryString (the request is GET). So, you need to check that, or if that's not the issue then make sure you're pointing the element well. Otherwise if there is no such element, nothing will be sent.
I am not sure, which language you're using but here is the code for ASP.NET
var value = Request.QueryString["something"];
PHP version is already present above. That all depends on the parameters you send with the request. You are more likely to convert the code to a function. Such as
Submit
And the function
function submit() {
// create variable
var value = document.getElementById("something").value;\
// now submit the form and all that other bla bla, which
// you want to be process,
}
If you find this one tricky, using jQuery as
var values = $('form').serialize();
will be easy. This will create a string of the form and will send it with the request.
Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.
I'm trying to create a form which submits a string to another page only with the parameter name removed from the URL.
i.e. submitting the following form with "foo"
<form action="search.asp" method="get">
<input type="text" name="keyword" id="keyword">
<input type="submit" value="Go">
</form>
will go to search.asp?foo NOT search.asp?keyword=foo
Can this be done with pure html?
I guess this can be done with javascript and/or jquery but I'm not certain exactly how.
Can anybody help?
I'm a bit of a noob so a copy and paste solution would be great for me.
Update:
Thanks for the answers so far but they don't seem to be working. Perhaps a better way to do this is to get JQuery to construct the URL and load that URL? Any more suggestions would be great.
or maybe...?
$('input[type="text"]').blur(function() {
$('form').attr('action', 'search.asp?' + $('input').val());
});
Let's give the form and the submit button a classname for convenience and assume we have jQuery on the page.
<form action="search.asp" method="get" class="search_form">
<input type="text" name="keyword" id="keyword">
<input type="submit" value="Go" class="search_button">
</form>
<script type="text/javascript">
$(function(){
var $form = $(".search_form");
// save the default action, because we are going to mess with it.
$form.data("original-action", $form.attr("action"));
// listen to the click on the button, update the form action and submit the form manually
$(".search_button").click(function(){
$form.attr("action", $form.data("original-action") + "?" + $("#keyword").val());
$form.submit();
return false;
});
});
</script>
Not tested, but should work. Let me know.
Btw, saving the default action is maybe not needed. But just in case that you ever want to submit it with ajax without reloading the page.
Try this:
<form action="search.asp?foo">
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(){
var keywordVal = $("#keyword").val();
window.location.href = "search.asp?" + keywordVal;
});
});
</script>
<input id="keyword" type="text" name="keyword">
<button id="btnSubmit">Submit</button>