Making Html Form Input field to remain unchange on submission - javascript

Making Html Form Input field to remain unchange on submission.
When i submit the form, the form inputs for ball and comments gets reset to empty.
Now what i want is when i submit the form, the values in the inputs select field for ball remains unreset while comments fields values will reset
as usual. any help below is the working code
$('body').on("click",".addComment",function(){
var element = $(this);
var id = element.attr("id");
$('#commentBox'+id).slideToggle(200);
$('#comment'+id).focus();
$('#comment'+id).val('');
$('#comment'+id).attr("placeholder", "Write a message..");
});
$('body').on("click",".comBtn",function(){
var element = $(this);
var cid = element.attr("id");
var ball=$('#ball').val();
var comment=$('#comment').val();
var datasend = 'com='+ comment + '&pid=' + cid +'&ball='+ball;
if(comment==""){
$('#comment'+cid).focus();
$('#comment'+cid).attr("placeholder", "Enter the comment..");
}else{
$.ajax({
type:"POST",
url:"comment.php",
data:datasend,
cache:false,
success:function(html){
$('#loadcomment'+cid).append(html);
$('#comment').val('');
$('#ball').val('');
}
});
}
return false;
});
<form action="" method="post">
<select name="ball" id="ball">
<option>none</option>
<option value="left">left</option>
<option value="right">right</option>
</select>
<input name="comment" id="comment" type="text">
<input id="comBtn" type="submit"/>
</form>

I am simply moving this to an answer because I put it in as a comment thinking there might be more ...
On the success of your $.ajax call, remove the $('#ball').val('') line so that it doesn't change.
Basically, the val statement has two purposes.
As .val("123"): this will change the value of the element to 123, an assignment.
As .val(): this will obtain the value from the element without changing it.
As you wrote it, the $('#ball').val('') code resets ball's value to an empty string.

The short answer to this will be:
You can resetting the select dropdown using $('#ball').val(0);
I can see few issues in the code, first of all you need to wrap the entire block with
$(function() {
// your code goes here
});
Second thing take advantage of HTML5 by adding the necessary attributes like required="required" and placholder on your inputs and adding novalidate on the form like the following:
<form method="post" novalidate>
<input type="text"
required="required"
placeholder="Your placeholder goes here"/>
Use e.preventDefault(); to prevent the form from being submitted cause you are posting using ajax.and use only submit event
$('form').on("submit", function(e) {
e.preventDefault();
// your other functions
});
Put the action on the form attribute instead of the js variable, html is cheaper to manage.
<form action="comment.php">
Then in the js
url: $('form').attr('action'),
Of course better save it in a variable then pass it but this is just an example
Use $('form').serialize(); instead of constructing the data your self
`data:datasend, // bad
`data: $('form').serialize() // good
Form serialize jquery api

Related

Form tag and AJAX request

I made a simple page with a couple of radio buttons and a textfield as an exercise:
<html>
...
Student list: <input type="radio" name="list" value="students">
Lession list: <input type="radio" name="list" value="lessons">
<h2>Type the course code:</h2>
Code: <input type="text" name="code" id="code">
<input type="submit" id="submit">
</html>
And I added a listener to the button through Javascript.
Now via Javascript I collect the data from the various input fields, and pack them in a request:
function prepareRequest(req) {
var radios = document.getElementsByName("list");
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
value = radios[i].value;
}
}
var code = document.getElementById("code").value;
var url = "../AjaxServlet?value="+value+"&code="+code;
req.open("GET", url, true);
req.send();
}
I call my servlet through Javascript, GET my data, and then handle the response.
If I wanted to do this with "pure" HTML, I'd enclose those inputs in a FORM tag, like this:
<form action="../AjaxServlet" method="get">
...
<input type="submit" id="submit">
</form>
Now when I hit submit, the servlet is called "through" the form, which sends all the data it collected automatically. Of course this is synchronous and the page has to reload/redirect.
What I'm wondering is, with AJAX, is there any need for the form tag? What I did seemed intuitive enough, get the input elements from the DOM, extract the data and then pack them in a request manually. Is this right or wrong? Is there a standard or better way to do this?
This answer assumes jQuery use (which your question is not, kudos).
One of the benefits of using the form tag is the serialization of the form. Allowing for a cleaner approach of passing form data to your processing page.
It's also a bit cleaner (IMO) for form validation. Obviously there are many ways to validate form input but you can easily pass the form object and search for required elements having a valid value.
Adapted from Ajax and Forms on Learn.jQuery.com.
Although I would agree with celerno do what you need to do, but keep it at a minimum.
if you use form tag then your current web page will be change form tag page
example
in blabla.html
<form action=/api/send_hi method="POST">
<button name="ID" value="hi">
</form>
click button then current web page will be blabla/api/send_hi.html and result is
{ID: 'hi'}
if you use ajax then your current web page will not be change form tag page
in blabla.html
blabla ~~~
<script type="text/javascript">
function hi(){
$.ajax({
url: '/api/send_hi',
method: 'POST',
dataType: 'JSON',
data: {'ID': 'hi'},
async: false
}).done(function(data)){ // do if ajax communication success}
</script>
<body>
<button onclick=hi()>
</body>
this result is same as form tag result but current web page is not changed
still blabla.html not /api/send_hi.html

submitting a form with link

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.

Clearing my form inputs after submission

I've tried it a few different ways based on searches I've done on the subject and for some reason I can't get it to work. I just want my text inputs and textarea to clear after I hit the submit button.
Here's the code.
<div id="sidebar-info">
<form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
<h1>By Phone</h1>
<p id="by-phone">XXX-XXX-XXXX</p>
<h1>By Email</h1>
<p id="form-row">Name</p>
<input name="name" id="name" type="text" class="user-input" value="">
<p id="form-row">Email</p>
<input name="email" id="email" type="text" class="user-input" value="">
<p id="form-row">Message</p>
<textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
<p>*Please fill out every field</p>
<input type="submit" value="Submit" id="submit" onclick="submitForm()">
<script>
function submitForm() {
document.contact-form.submit();
document.contact-form.reset();
}
</script>
</form>
</div>
Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.
Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.
You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.
Try the following
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
since you are using jquery library, i would advise you utilize the reset() method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
You can use HTMLFormElement.prototype.reset according to MDN
document.getElementById("myForm").reset();
You can try this:
function submitForm() {
$('form[name="contact-form"]').submit();
$('input[type="text"], textarea').val('');
}
This script needs jquery to be added on the page.
The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with
$('#element-id').val('')
For all input elements in the form this may work (i've never tried it)
$('#form-id').children('input').val('')
Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.
There may be a better way however this should work for you.
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
btnSave.addEventListener("click", () => {
inputs.forEach((input) => (input.value = ""));
});
**Use the button you want to clear the inputs after clicking on it instead of the btnSave **
Just include this line at the end of function:
document.getElementById("btnsubmit").value = "";
I used the following with jQuery:
$("#submitForm").val("");
where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:
function extractValue() {
var value = $("#submitForm").val().trim();
console.log(value);
};
Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

Manually submitting a form using JavaScript doesn't send the submit button

I have a form that has two submit buttons. I want to submit the form manually using JavaScript and have the input button used to submit the form posted along with the other form elements, as it would be if the form was submitted automatically. There's quite a lot of chatter on this subject, but I can't find an answer.
<form method="post" action="echoToScreenAndLog.jsp" id="form1">
<input id="field1" name="field1"/>
<input type="text" size="20" id="field2" name="field2"/>
<input type="submit" value="Do One" name="sub1_name" id="sub1_id"/>
<input type="submit" value="Do Two" name="sub2_name" id="sub2_id"/>
</form>
When the form is submitted above using the "Do One" button, the posted parameters are field1="xxx", field2="yyy", sub1_name="Do One".
But I want to submit the form manually...
<form method="post" action="echoToScreenAndLog.jsp" id="form1">
<input id="field1" name="field1"/>
<input type="text" size="20" id="field2" name="field2"/>
<input type="submit" value="Do One" name="sub1_name" id="sub1_id"/>
<input type="submit" value="Do Two" name="sub2_name" id="sub2_id"/>
</form>
<script type="text/javascript">
var btn = document.getElementById('sub1_id');
btn.onclick=function() {
return mySubmit(document.getElementById('form1'), ...);
}
</script>
but doing a manual submission of the form in the mySubmit function does not post the sub1_name parameter. I can understand that - I've bypassed the submission so the form is not being submitted using the buttons and therefore it makes no sense to post a parameter representing the button used to submit the form.
When I look at the elements of the form in the onclick handler, I can see both buttons. I'm not overly surprised by that either, they are elements on the form after all, but what I don't get is that if I add an element inside my onclick handler then the element I add IS posted and the two original submit buttons are not posted. Just to complete the picture, here's the code that adds the element:
<script type="text/javascript">
var btn = document.getElementById('sub1_id');
btn.onclick=function() {
var f = document.getElementById('form1');
var s = document.createElement("input");
s.type="hidden"; s.name="xsubmit_name"; s.value="Bob"; s.id="xsubmit_id";
f.appendChild(s);
// s gets posted
return mySubmit(f, ...);
}
</script>
Adding the input element could work for me, but I'm confused how the browser knows to post my added element and not the original two input elements.
Thank you.
The specification says that the first step for form submission is:
Step one: Identify the successful controls
"Successful controls" are defined as:
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
However:
...
If a form contains more than one submit button, only the activated submit button is successful.
Since none of the submit buttons are activated, none are sent. Hidden input elements, on the other hand, are valid and will just be submitted along. Note that you add the hidden elements before calling mySubmit(), so at the time the above steps are executed (i.e. during submit), the hidden element is just another successful control part of the form, and thus sent.
may use
var btn = document.getElementById('sub1_id');
btn.onsubmit=function() {
return false;
}
btn.onclick=function() {
var f = document.getElementById('form1');
var s = document.createElement("input");
s.type="hidden"; s.name="xsubmit_name"; s.value="Bob"; s.id="xsubmit_id";
f.appendChild(s);
f.submit()
}

jQuery/JavaScript - Displaying value from text-input in <span>-placeholders

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).

Categories