How to get all values in a form with Onchange attribute - javascript

I'm trying to get all the values in a form when the user selects an option in the droplist. I'm using the Onchange attribute but I don't know how to send the all values to submitForm() via this attribute.
<input type="hidden" name="var1" value="..." />
<input type="hidden" name="var2" value="..." />
<input type="hidden" name="var3" value="..." />
<select name="var4" onchange="submitForm([var1 var2 var3 var4]);return false">
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
</select>
<script>
function submitForm(var1, var2, var3, var4)
{
var OAjax;
if (window.XMLHttpRequest) OAjax = new XMLHttpRequest();
else if (window.ActiveXObject) OAjax = new ActiveXObject('Microsoft.XMLHTTP');
OAjax.open('POST',"return.php",true);
OAjax.onreadystatechange = function()
{
if (OAjax.readyState == 4 && OAjax.status==200)
{
if (document.getElementById)
{
document.getElementById('msg').innerHTML=''+OAjax.responseText+'';
}
}
}
OAjax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
OAjax.send(var1='+var1+'&var2='+var2'&var3='+var3'&var4='+var4);
}
</script>
Thanks

Since there is no jQuery used in your js method, I'm assuming you are not really using jQuery.
In that case
<select name="var4" onchange="submitForm();">
then
function submitForm() {
//get the input elements by name and then read its value
var OAjax, var1 = document.getElementsByName('var1')[0].value,
var2 = document.getElementsByName('var2')[0].value,
var3 = document.getElementsByName('var3')[0].value,
var4 = document.getElementsByName('var4')[0].value;
if (window.XMLHttpRequest) OAjax = new XMLHttpRequest();
else if (window.ActiveXObject) OAjax = new ActiveXObject('Microsoft.XMLHTTP');
OAjax.open('POST', "return.php", true);
OAjax.onreadystatechange = function () {
if (OAjax.readyState == 4 && OAjax.status == 200) {
if (document.getElementById) {
document.getElementById('msg').innerHTML = '' + OAjax.responseText + '';
}
}
}
OAjax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//create a parma string using the input values
OAjax.send('var1=' + var1 + '&var2=' + var2 '&var3=' + var3 '&var4=' + var4);
}

Related

how to remove double quotes from the string result after performing addition or any calculation?

I have 2 input fields with type text in html, the values are 2,200.01 and 5,000.02 and to perform addition I am navigating to controller to perform the addition
public Jsonresult TotalAssets(){
Decimal check = Convert.ToDecimal(chequing) + Convert.ToDecimal(savTax);
string totalAssets = check.ToString("#,##0.00"); //Now I get the result "7,200.03" .
return Json(totalAssets);
}
Now I pass this result back to html as response like below
<script>
function calculate() {
var request;
if (window.XMLHttpRequest) {
//New browsers.
request = new XMLHttpRequest();
var formData = new FormData(document.forms.assets);
}
if (request != null) {
var url = "Home/TotalAssets";
request.open("POST", url, false);
request.send(formData)
}
totalAssets.value = request.response;
}
</script>
Below is my html on page load calculate function from JS is called.
<form name="assets">
<input type="text" value="2,200.01" name="chequing" id="chequing" />
<input type="text" value="5,000.02" name="totalAssets" id="totalAssets" />
<input type="text" readonly="readonly" name="totalAssets" id="totalAssets" />
</form>
and I see in the text box as well with double quotes. How do I remove these quotes and display only the numbers like 7,200.03 ?
How about replacing each " occurence with nothing, effectively removing each double quote?
totalAssets = totalAssets.replace(/"/g, "")
I created an example for your question.
please consider that you can't have two elements with having the same id.
so I removed one of totalAssets elements and set the value to zero just for test.
in HomeController =
[HttpPost]
public JsonResult TotalAssets()
{
Decimal check = 7200.03m;
string totalAssets = check.ToString("0.00");
return Json(totalAssets);
}
in HTML =
<form name="assets">
<input type="text" value="2,200.01" name="chequing" id="chequing" />
<input type="text" value="0" name="totalAssets" id="totalAssets" />
</form>
<script>
$(document).ready(function () {
if (totalAssets.value == 0) {
calculate();
}
});
function calculate() {
var request;
if (window.XMLHttpRequest) {
//New browsers.
request = new XMLHttpRequest();
var formData = new FormData(document.forms.assets);
}
if (request != null) {
var url = "Home/TotalAssets";
request.open("POST", url, false);
request.send(formData)
}
var decimalFormat = parseFloat(JSON.parse(request.response)).toFixed(2);
totalAssets.value = numberWithCommas(decimalFormat);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
you can get decimal format(5000.00) with =
var decimalFormat = parseFloat(JSON.parse(request.response)).toFixed(2);

Javascript : How to check multiple empty values

I have four input elements in my form. I don't have submit button in my form. I want to check all the values and if all the values are not empty then I want to post that all values to php page by using ajax.
This is my form input elements.
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" onchange="getDetails(this.value)" name="managername"/>
Project Name<input type="text" id="projectname" onchange="getDetails(this.value)" name="projectname"/>
Task Name<input type="text" id="taskname" onchange="getDetails(this.value)" name="taskname"/>
Completion Date<input type="date" id="date" onchange="getDetails(this.value)" name="date"/>
<div id="cool"></div>
</form>
This is my script.
function getDetails()
{
var mname = document.getElementById('managername').value;
var pname = document.getElementById('projectname').value;
var tname = document.getElementById('taskname').value;
var cdate = document.getElementById('date').value;
//alert(mname);
if(mname!==null&&pname!==null&&tname!==null&&cdate!==null)
{
alert("true");
var jsonobj = {"mname" : mname, "pname" : pname, "tname" : tname, "cdate" : cdate};
var js = JSON.stringify(jsonobj);
alert(js);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(js);
document.getElementById("cool").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getAllDetails.php?js="+js,true);
xmlhttp.send();
}
}
Just am getting all the values and assigning to four variables. If the four variables are not null then I want to assign all that in single object. But the problem is every time it is coming inside the condition and showing alert.
At fourth time also it is showing the alert. But the values are not going to php page. I'am a beginner Please guide me if I approached in a wrong way.
1.Change Html Code to new code
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" name="managername" class="v1"/>
Project Name<input type="text" id="projectname" name="projectname" class="v1"/>
Task Name<input type="text" id="taskname" name="taskname" class="v1"/>
Completion Date<input type="date" id="date" name="date" class="v1"/>
<input id="Button1" type="button" value="button" onclick="return checkData();" />
</form>
2.Change Script Code to new script code (for checking multipe value)
function checkData() {
var _v = document.getElementsByClassName("v1"); // get all field
var _empty = false; // default has false;
var _jsParm = '';
for (var i = 0; i < _v.length; i++) {
if (_v[i].value == '') {
_empty = true; // if value of null or empty; *
break;
}
_jsParm += _v[i].id + ':\'' + _v[i].value + '\',';
}
//* if any field is null , show alert
if (_empty == true) {
alert('Error!!!!! \r\n Please enter data in all field.');
return false;
}
alert('OK! all field has data.' + '\r\n' + _jsParm)
_jsParm = _jsParm.substr(0, _jsParm.length - 1);
var jsonobj = '{' + _jsParm + '}';
var js = JSON.stringify(jsonobj);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(js);
document.getElementById("cool").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getAllDetails.php?js=" + js, true);
xmlhttp.send();
}
3.Save
4.Enjoy Now!

Javascript/ajax is passing all form textfield values to the php but not the last textfield value

This is my html with form and javascript/ajax function. All the textfield values are passed to the test.php. When I do so, if i enter the first three textfields then test.php will successfully display the form values. But on the other hand, if I fill all the four textfield and send then nothing will happen. Since, I am new in the programming, i could not figure this issue out. I would be thankful for the solution of this issue.
#form.html
<html>
<SCRIPT language="javaScript">
function sendData(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXobject ('Mircosoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var i=0;
var arr = new Array();
while ((document.getElementById(i).value)) {
if ((document.getElementById(i).value)!=""){
var activity = document.getElementById(i).value;
arr[i] = activity;
}
i++;
}
var params = 'activity='+JSON.stringify(arr);
xmlhttp.open('POST','test.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(params);
document.getElementById("message").innerHTML = "Sending...";
}
</script>
<form action="#" method="POST">
<tr>Name1:<td> <input type="text" id="0"/> </td></tr><br>
<tr>Name2:<td> <input type="text" id="1"/> </td></tr><br>
<tr>Name3:<td> <input type="text" id="2"/> </td></tr><br>
<tr>Name4:<td> <input type="text" id="3"/> </td></tr><br>
<input type="button" value="Send" onclick="sendData()";/>
</form>
<div id="message">
</div>
</html>
This is the test.php file where the form value will be displayed.
#test.php
<?php
$activity = $_POST['activity'];
$activity = json_decode($activity);
if (is_array($activity)){
foreach ($activity as $value){
echo $value."<br>";
}
}
else {
echo "error";
}
?>
The issue is with
while ((document.getElementById(i).value)) {
It works just fine until i === 4, then getElementById returns null, and null.value is an error, so the whole thing errors out.
Using a while loop for this doesn't really seem like a good idea, but something like this should at least work
while (document.getElementById(i)) {
if ((document.getElementById(i).value) != "") {
arr[i] = document.getElementById(i).value;
}
i++;
}
Getting the elements by class, tagname or something else other than numeric ID's seems better
var arr = new Array();
var elems = document.querySelectorAll('.inputs'); // class
for ( var i=0; i<elems.length; i++ ) {
arr.push(elems[i].value)
}

Sending parameters with ajax not working

I'm trying to send some variables using ajax to a php page and then displaying them in a div but it isn't working.
Html code :
<div id="center">
<form>
<input type="text" id="toSearch" class="inputText" title="Search for ...">
<select name="thelist1" id="ecoElem" class="comboBox">
<option>-- Ecosystem Element --</option>
</select>
<select name="thelist2" id="ecoActor" class="comboBox">
<option>-- Ecosystem Actor --</option>
</select>
<input type="button" value="Search" id="searchButton" onclick="loadData();">
</form>
</div>
<div id="resBox">
</div>
The loadData function :
function loadData(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
searchT = document.getElementById('toSearch').value;
ecoElem = document.getElementById('ecoElem').value;
ecoActor = document.getElementById('ecoActor').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('resBox').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","databaseRead.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}
and finally the php page :
<?php
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>
That's it , I've been working on this for a few hours but still can't figure it out.
Try changing the button so that the onclick return false (in case that is submitting the form)...
<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">
Also, you might want to URL encode the values from the textbox, otherwise somebody entering a = or a & will mess it all up...
xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}
You could also use JQuery.
function loadData(){
var searchT = $('#toSearch').val();
var toSearch = $('#ecoActor ').val();
var ecoActor = $('#ecoActor').val();
$.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
function(data){
$('#resBox').html(data);
});
}

Javascript two submit buttons in one form almost complete

I have a form with two submit buttons with onClick events attached. The form action is a paypal form.
If make a payment button is pressed the form is emailed and then redirects to paypal for payment.
If the invoice button is pressed an email is sent with the form details but the default action of redirecting to PayPal is stopped.
It all seems to work fine but when the invoice buttin is pressed it still redirects to paypal.
If the invoice button is pressed i want it to send the email but then stop and not continue on with the form action.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paymentform" name="paymentform">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="currency_code" value="GBP">
<fieldset id="your_details" class="">
<legend>Your Details</legend>
<ol>
<li><label for="your_name">Your Name</label><input type="text" name="your_name" value="" id="your_name" class="large "></li>
<li><label for="your_position">Your Position</label><input type="text" name="your_position" value="" id="your_position" class="large"></li>
<li><label for="your_company">Your Company</label><input type="text" name="your_company" value="" id="your_company" class="large "></li>
<li><label for="your_telephone">Your Telephone</label><input type="text" name="your_telephone" value="" id="your_telephone" class="medium "></li>
<li><label for="your_mobile">Your Mobile</label><input type="text" name="your_mobile" value="" id="your_mobile" class="medium"></li>
</ol>
</fieldset>
<input type="submit" value="Pay by Credit Card →" id="cc" onclick="return email_me(document.paymentform);" class="submit_button">
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);">
var xmlHttp;
var formname;
var invoiceonly_var
function email_me(Form,invoiceonly)
{
formname = Form.name;
var params = "";
var i;
var Element;
var type;
var name;
var fieldvalue;
var optional;
var BadFields = "";
var Title;
var Titles = new Array();
Titles['item_name'] = "Course Title";
var outMessage = "";
invoiceonly_var = invoiceonly;
//alert(formname);
//alert(Form.length);
var Optional = new Array();
// optional fields
Optional['your_position'] = true;
Optional['your_mobile'] = true;
for(i = 0; i < Form.length; i++)
{
Element = Form.elements[i];
type = Element.type;
name = Element.name;
//alert("name:"+name+" type:"+type);
if(type == "text")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
if(type == "textarea")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
}
if(BadFields)
{
outMessage = "We are unable to proceed as the following \n";
outMessage += "required fields have not been completed:\n\n";
outMessage += BadFields;
alert(outMessage);
return false;
}
//alert(params);
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url="/payment/ajax_email_me.php?";
if (invoiceonly_var == true)
{
params = params + "Payment_Method=Invoice";
}
else
{
params = params + "Payment_Method=PayPal&";
}
url=url+params;
//alert(url);
xmlHttp.onreadystatechange = Finished;
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
return true;
}
function Finished()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
//document.getElementById('search').innerHTML = xmlHttp.responseText;
var response = xmlHttp.responseText;
//alert(response);
if (invoiceonly_var == true)
{
alert("Thank you. Your message has been sent.");
}
else
{
document.paymentform.submit();
}
document.body.innerHTML = document.body.innerHTML + "<span></span>";
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
// alert("Mozilla");
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
// alert("IE");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
// alert("IEError");
}
}
return xmlHttp;
}
function selectval(Sel)
{
return Sel.options[Sel.selectedIndex].value;
}
function getTitle(name,Titles)
{
Title = Titles[name];
if (typeof(Title) == "undefined")
{
Title = name;
Title = Title.replace(/_/g," ");
}
return Title;
}
First of all, your code could be greatly simplified with the use of jQuery to abstract away much of the AJAX logic here.
Secondly, you have return true at the bottom of your email_me function - try changing this to:
return !invoiceonly;
Returning false from this function will prevent the form from submitting. When the invoice button is clicked (and the invoiceonly parameter is set to true) you do not want the form to submit, so the above logic will make the function return false.
Usually I would suggest adding ";return false" after the Javascript you want to run, but since you're already returning a value, I'm not sure that will work. Give it a shot, though, and if it doesn't work, can I ask what the return value is doing?
Something like this:
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);return false">
Did you try adding "return false" to the end of the onclick event which you don't want to submit?
Or you can change the type to "button" from "submit" - that might do the trick.

Categories

Resources