Send data without submit button (Javascript / jQuery) - javascript

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form1" id="form1" action="coillist" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<th>Coil #</th><th>Width</th><th>Gauge</th>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_11"></td>
<td><input type="text" size="7" name="width" value="120"></td>
<td><input type="text" size="5" name="gauge" value="130"></td>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_22"></td>
<td><input type="text" size="7" name="width" value="220"></td>
<td><input type="text" size="5" name="gauge" value="330"></td>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_33"></td>
<td><input type="text" size="7" name="width" value="320"></td>
<td><input type="text" size="5" name="gauge" value="330"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
I have a dynamic row adding table that could add row into the table.
I am showing it in 3 rows, it could be 1 row, or 4 rows, or n rows if a use wants to add data in.
My question is: How can I send data (coil_id) out without click submit button?
In this example, I want to send a coil_id (coil_id = ”coil_22” in this case) to the server without using submit button.
This is also something like: detect if user enter a coil in length of 7 char or digit (Ex: coil_22 or 2C12345), then it will submit the “coil_22” (not coilL_11 or coil_33) to server without click any submit / send button.
I have used JavaScript / jQuery a while, still feel lost sometimes.
Highly appreciate your help.

You can make it with a .keyup(), just add a class to each input for example
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_11">
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_22">
<script>
$('.coil_input').keydown(function() {
if($.trim($(this).val()).length == 7){
var now_input_value = $(this).val();
$.post('file.php', {now_input: now_input_value}, function(){ alert('Data sent'); }).fail(function(){ alert('An error has ocurred'); });
}
});
</script>
All the inputs has to have the same class
Remember to add jQuery to your document.

here is example of jquery ajax. serialize will create generate query string that will be sent to your url.
var datastring = $("#yourForm").serialize();
$.ajax({
type: "POST",
url: "your url",
data: datastring,
dataType: "json",
success: function(data) { alert('all ok');}
});

Related

Set focus to next input field in a table after maxlength reached

How to set focus to next input field in a table?
Firstly I worked with that JQuery code: But it only works if the input fields are not spread over different and fields. How could I improve it that code or maybe someone knows a JS code that will work for autofocus fields spread over td and tr fields following tabindex?
<script>
$(document).ready(function(){
$('input').keyup(function(){
if(this.value.length==$(this).attr("maxlength")){
$(this).next().focus();
}
});
});
</script>
My html:
<table>
<tr>
<td><input type="text" id="field1" tabindex="1" name="test1" maxlength = "1"></td>
<td><input type="text" id="field2" tabindex="2" name="test2" maxlength = "1">.</td>
</tr>
<tr><td><input type="text" id="field3" tabindex="3" name="test3" maxlength = "1"></td></tr>
</table>
To do what you require you can retrieve all input elements and get the index of the current one within that collection. To move to the next input, select it from the collection using eq() and the next incremental index value.
Also note that your HTML is invalid - you seem to be missing a <tr> around the final td. I've corrected that in the following example:
jQuery($ => {
let $inputs = $('input').on('input', e => {
let $input = $(e.target);
let index = $inputs.index($input);
if ($input.val().length === $input.prop('maxlength')) {
$inputs.eq(index + 1).focus();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" id="field1" tabindex="1" name="test1" maxlength="1"></td>
<td><input type="text" id="field2" tabindex="2" name="test2" maxlength="1">.</td>
</tr>
<tr>
<td><input type="text" id="field3" tabindex="3" name="test3" maxlength="1"></td>
</tr>
</table>
It's pretty gross, but would work lol
$(document).ready(function(){
$('table input').keyup(function(){
if(this.value.length==$(this).attr("maxlength")){
tableInputs = $('table').find('input');
$(tableInputs[tableInputs.index(this)+1]).focus();
}
});
});

how to get form field value and send to server as json using ajax jquery

I have search form with 6 fields and 1 search button. when user fill the form deatails and click on search button, i need to send the form field values as json to server using jquery ajax.
then the server will send the search values and returns the response, then i need to populate those valuse in ui. i need sample UI code for jquery ajax . please can anyone help on this?
below is my html form
<form name="NAME" id="customerDetailSearchForm" action="">
<fieldset>
<legend>Search Contact</legend>
<table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
<tr>
<td><label>Name :</label><input type="text" value="" /></td>
<td><label>City :</label><input type="text" value="" /></td>
<td><label>Phone :</label><input type="text" value="" /></td>
</tr>
<tr>
<td><label>Address :</label><input type="text" value="" /></td>
<td><label>State Prov :</label><input type="text" value="" /></td>
<td><label>Email :</label><input type="text" value="" /></td>
</tr>
</table>
</fieldset>
<button class="vzuui-btn-red-active closeedit" type="button" id="search">Search</button>
First of all you will need to change you HTML form code to include name attribute in the textfields like below
<form name="NAME" id="customerDetailSearchForm" action="">
<fieldset>
<legend>Search Contact</legend>
<table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
<tr>
<td><label>Name :</label><input type="text" value="" name="name" /></td>
<td><label>City :</label><input type="text" value="" name="city" /></td>
<td><label>Phone :</label><input type="text" value="" name="phone" /></td>
</tr>
<tr>
<td><label>Address :</label><input type="text" value="" name="address" /></td>
<td><label>State Prov :</label><input type="text" value="" name="state" /></td>
<td><label>Email :</label><input type="text" value="" name="email" /></td>
</tr>
</table>
</fieldset>
<button class="vzuui-btn-red-active closeedit" type="button" id="search">Search</button>
This is required because we will be using jQuery serializeArray() Method which creates an array of objects (name and value) by serializing form values.
Now the jQuery part to form the JSON data from your form and make the AJAX call.
<script type="text/javascript">
$(document).ready(function(){
$("#search").click(function(){
var frm = $("customerDetailSearchForm").serializeArray();
var obj = {};
for (var a = 0; a < frm.length; a++) {
obj[frm[a].name] = frm[a].value;
}
var jsonData = JSON.stringify(obj);
$.ajax({
type: 'GET',
url: 'http://example.com',
data: jsonData ,
dataType: 'json',
success: function (data) {
// add result to UI code over here
}
});
});
});
</script>
EDIT
The above javascript snippet edited to generate proper JSON value
Here is simple Ajax Code that I use in Asp.net MVC
I think This will help you,
$.ajax({
beforeSend: function (xhr) {
AjaxRequestStart();
},
error: function (result) {
},
complete: function () {
AjaxRequestFinish();
},
url: '#Url.Content("~/Project/SaveProject")',
type: 'POST',
data: $('#frmAddProject').serialize(),
success: function (result) {
}
});
Here i agree with #Aniket. add name first for each input type.
<form name="NAME" id="customerDetailSearchForm" action="your_url">
<fieldset>
<legend>Search Contact</legend>
<table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
<tr>
<td><label>Name :</label><input type="text" value="" name="name" /></td>
<td><label>City :</label><input type="text" value="" name="city" /></td>
<td><label>Phone :</label><input type="text" value="" name="phone" /></td>
</tr>
<tr>
<td><label>Address :</label><input type="text" value="" name="address" /></td>
<td><label>State Prov :</label><input type="text" value="" name="state" /></td>
<td><label>Email :</label><input type="text" value="" name="email" /></td>
</tr>
</table>
</fieldset>
<button class="vzuui-btn-red-active closeedit" onclick="_submit();" type="button" id="search">Search</button>
For calling ajax, you can use this.
function _submit{
$.ajax({
type: 'POST',
dataType: 'json',
url: 'your_url',
data: $("#customerDetailSearchForm").serialize(),
success: function(responseData, textStatus) {
// you implementation logic here
},
complete: function(textStatus) {
},
error: function(responseData)
{
}
});
}
Here you go
Convert form data to JavaScript object with jQuery
But before that you have to add name attribute for each input element.
So that name will be your json key and the data in the box will be value of that key as below
<input name='username' value='' />
Will become
{"username": "john"}
jhon is value entered in input box.
**edit (Ajax code) **
$(function() {
$('#customerDetailSearchForm').submit(function() {
$.post("//your URL here",JSON.stringify($('#customerDetailSearchForm').serializeObject()), function(result){
alert("Data posted successfully!!");
});
});
});
or replace below line if you dont have submit button in the form
$('#customerDetailSearchForm').submit(function() {
with
$('#search').click(function() {
You can refer below sample ajax call on form submit
$("#customerDetailSearchForm").submit(function(e) {
var postData = $('#conatctUs').serializeArray();
var formURL = $('#conatctUs').attr("action");
var formName = $('#conatctUs').attr('name');
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data)
{
if(data.status){
console.log(data);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
}
e.preventDefault();
});

how to let a submit button in a form do something before executing the action of the form

Good evening, i have a HTML form that contains a submit button that does something other than executing the action of the form, i want these submit button to do an action first then do the action of the form, that button do a nice jquery slideUp() but when i embed it in a form it does the action of the form and neglect the slideUp() behavior, what are the possible ways to let that button do the slideUp() first before submitting the form?
here's the form:
<form action="AddNewCar" method="get">
<table BORDER=2 BORDERCOLOR=YELLOW width="300px">
<tr>
<td>Description: <input type="text" name="desc" /></td>
<td>Quantity:<input type="text" name="qunt" /></td>
<td>Price: <input type="text" name="price" /></td>
</tr>
<tr>
<td>CC.No: <input type="text" name="cc" /></td>
<td>Engine: <input type="text" name="engine" /></td>
<td>Cylinder.No: <input type="text" name="cylinder" /></td>
</tr>
<tr>
<td>Max-speed: <input type="text" name="speed" /></td>
<td>Petrol-type: <input type="text" name="ptr-type" /></td>
<td>Petrol-capacity: <input type="text" name="ptr-cpcty" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" class="btn1" value="Add" onclick="addNewCar()" /></td>
</tr>
</table>
</form>
and here's the script is supposed to execute before anything else:
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
$(".btn1").click(function() {
$('#toggleText').slideUp();
});
</SCRIPT>
$(".btn1").on('click', function(e) {
e.preventDefault()
var self = this;
$('#toggleText').slideUp('fast', function() {
self.form.submit();
});
});
You should put the slide up in a method and call it on submit
<form action="AddNewCar" onsubmit="slideupmethod" method="get">
function slideupmethod(){
$('#toggleText').slideUp();
}
You can create a submit button, which uses onclick to fire off a function, and then submit your form. For example.
The html button for submit
<input type="button" value="Submit Order" class="btn_submit" onclick="submitOrder()" />
your javascript function
//function called when submit button pressed
function submitOrder() {
//perform client side form validation and other things
//submit the form
$('#yourFormId').submit();
}
Alternatively, using the button you currently have. You can prevent the form from submitting when the button is pressed, perform the required actions, and then submit the form.
javascript
$('form').submit(function(evt){
//prevent form from submitting
evt.preventDefault();
//do required actions
//submit form
$('form').submit();
});

JQuery Form Validation

I need to do a form validation with jQuery. But I'm having a problem in this.
I have a HTML form as below:
<FORM id="formID" method="POST" onsubmit="return checkRequiredFields(this)" action="">
<td><input class="required" type="text" id="input1" value="" /></td>
<td><input class="required" type="text" id="input2" value=""/> </td>
<td><input class="required" type="text" id="input3" value=""/> </td>
<td><input type="text" id="input4" value=""/> </td>
<td><input type="submit" id="save" value="Save" /></td>
</FORM>
The first three input text fields are required fields. I tried writing the script like below:
<script type="text/javascript">
function checkRequiredFields(form){
var no_errors = true;
$(form).find(".required").each(function(){
alert("Inside Loop");
var field = $(this);
if (field.val() == ""){
$("#"+field ).css("color","red");
no_errors = false;
} else {
$("#"+field ).css("color","white");
}
});
return no_errors;
}
</script>
But, the above code is not working as I expected. The alert() is never executed, meaning that the control does not find any element with class "required". So, what is the problem in my code?
$("#"+field ).css("color","red"); is not right. field is an object not a string, but since it's already a jQuery object you can just do this: field.css("color","red");. You'll have to do that for the other .css() call too: $("#"+field ).css("color","white"); => field.css("color","white");
Here is a demo: http://jsfiddle.net/eehV6/

Problem in form validation with JavaScript

The editvalidate() function is not getting called at all:
Please suggest why. What's the remedy?
<script type="text/javascript">
function editvalidate() {
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var numericExpression = /^[0-9]+$/;
if(document.editprofile.userid.value == '' || document.editprofile.password.value == ''||document.editprofile.name.value == ''||document.editprofile.age.value == ''||document.editprofile.collegeid.value == ''||document.editprofile.mobile.value == ''||document.editprofile.address.value == ''||document.editprofile.department.value == ''||document.editprofile.email.value == ''||document.editprofile.sec_ques.value == ''||document.editprofile.answer.value == ''){
alert("Hey! you can't left a field blank!");
return false;
}
else if(!document.editprofile.email.value.match(emailExp)){
alert("You need to enter a valid email address to get proper notifications!");
return false;
} else if(!document.editprofile.mobile.value.match(numericExpression)){
alert("Mobile numbers are all numeric digits i think!");
return false;
} else if(document.editprofile.mobile.value.length < 10){
alert("Mobile number must be 10 digit long!");
return false;
}
else{
return true;
}
}
</script>
the form is given below and its used to fetch data from database and itself getfilled with the values.the editable entries are corrected and the form is submitted.its working fine just not getting validated cz the editvalidate() is not getting called at all.why?
<form name="editprofile" action="editprofile.jsp" method="post" onsubmit="return editvalidate();">
<table align="center">
<%
for(int i = 0; i < list.length ; i++){
%>
<tr>
<td>Name:</td>
<td><input type="text" name="name" size="35" style="width: 219px" value="<%=list[i].getName() %>" maxlength="25"></td>
</tr>
<input type="hidden" name="userid" size="20" style="width: 220px"
value="<%=list[i].getUserid() %>" maxlength="10">
<tr>
<td>Address:</td>
<td><input type="text" name="address" size="46"
style="width: 221px" value="<%=list[i].getAddress() %>"
maxlength="50"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" size="20"
style="width: 220px" value="<%=list[i].getEmail() %>" maxlength="40"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" size="20" style="width: 219px"
value="<%=list[i].getAge() %>" maxlength="2"></td>
</tr>
<tr>
<td>College ID:</td>
<td><input type="text" name="collegeid" size="20"
style="width: 219px" value="<%=list[i].getCollegeid() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobile" size="20"
style="width: 218px" value="<%=list[i].getMobile() %>" maxlength="10"></td>
</tr>
<tr>
<td>Department:</td>
<td><input type="text" name="department" size="20"
style="width: 218px" value="<%=list[i].getDepartment() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Security Question:</td>
<td><input type="text" name="sec_ques" size="20"
style="width: 218px" value="<%=list[i].getSec_ques() %>"
maxlength="50"></td>
</tr>
<tr>
<td>Answer:</td>
<td><input type="text" name="answer" size="20"
style="width: 218px" value="<%=list[i].getAnswer() %>" maxlength="50"></td>
</tr>
<tr>
<td><input type="submit" name="operation" value="editprofile"
style="width: 118px"></td>
<td><input type="reset" value="Reset" name="B2"></td>
</tr>
<%
}
%>
i checked it the way u suggested and found that the function is getting called.but why the rest alerts r nt visible? isnt thatdue to the value attribute in input tags
With the as far given little information, all I can answer is: Just run a Javascript debugger. I can recommend you Firebug for this.
That said, in the future please come up with an SSCCE instead of cutouts of code with unnecessary clutter. This avoids crawling long in the code searching for lines of relevance and at first glance obvious questions as "Are they in the same file?", "Did you add alert('blah') as 1st line of function to see if it actually is invoked?", "Did the browser have JS enables?", "Are you sure that you didn't typo'ed the function name?", "Isn't there more into the code which may have disturbed it?", etcetera.
Here's a basic example of such an SSCCE:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2063598</title>
<script>
function validate(form) {
alert('Validate method invoked!');
return false;
}
</script>
</head>
<body>
<form onsubmit="return validate(this)">
<input type="text" name="foo" class="required">
<input type="submit">
</form>
</body>
</html>
That said, I see that you're still using the legacy scriptlets in your JSP. If you can, I strongly recommend to stop using it and switch to taglibs/EL before it's too late. Raw Java code belongs in Java classes, not in JSP files.
Basic example with JSTL's (just drop jstl-1.2.jar in /WEB-INF) c:forEach:
<table>
<c:forEach items="${users}" var="user">
<tr>
<td><input type="text" name="address" value="${user.address}"></td>
<td><input type="text" name="email" value="${user.email}"></td>
<td><input type="text" name="college" value="${user.college}"></td>
</tr>
</c:forEach>
</table>
And also keep CSS in its own CSS file to separate style from content and to increase webapp performance and maintainability.
you don't call it anywhere from your html, you should probably call it <form onsubmit="return editvalidate();">
Ok now I see he formatted it properly, I don't mind the down votes I give them sometimes as well.
#Robin Agrahari
you probably have somewhere typo in the javascript no one is going to go trought it but you, try to test one by one if by using alert as you do. But don't do it on sumbit, create a mock button that will call(on click) this function editvalidate(); and check your function thoroughly and you will get to the problem eventually
How can you tell it's not being called? I'd put an alert right at the top of the method and see if it hits that. It's possible you're hitting some kind of error somewhere. If an alert at the top of editvalidate doesn't occur, try changing the obsubmit to:
onsubmit="alert('hello!'); return editvalidate();"
then you should at least see "Hello!" when you click the submit button.
looking at the code it should be called
Or Try
onsubmit="editvalidate(); return false;"
Or check where it is not misplaced, I mean the javascript should be in <head> </head>
actually i used a password checking parameter in the first if block document.editprofile.password.value == ''
and i never used an attribute like password in the form.that was my mistake and so it was not working.i found it using the firebug tool.thanks for the help.

Categories