Changing input value of a form and submitting with jQuery - javascript

I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?

Related

Submitting form data to a popup window for processing

As so many posts start: This might be a duplicate, but...
Here's what I'm trying to do:
Have an HTML page within my site that contains a FORM element with various input, etc. elements inside, e.g.:
<form id="form1" method="post" action="">
Name: <input type="text" id="text1" size=10><br>
<input type="hidden" id="hidden1" value="This text is hidden">
<input type="checkbox" id="checkbox1" value="Y"> Include stuff?<br>
Job Title: <select name="select1" id="select1">
<option value="1">President</option>
<option value="2">Chief Cook</option>
<option value="3">Bottle Washer</option>
</select>
<button name="button1" id="button1" onclick="doThisScript()">Submit Stuff</button>
</form>
I want the "doThisScript" function to open a new popup window with coded parameters, directed to a url on our site, and pass the form's values to that url, something like:
function doThisScript() {
var form1=document.getElementById('form1');
form1.onsubmit=function() {
var w=window.open('resultsprogram.asp','resultswin','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300');
this.target = 'resultswin';
form1.submit();
}
}
This code (based on the closest Q/A here I could find) transfers the form from the "base" page to the popup window. But what I'm trying to do, I guess, is submit the form back to the server but have the results come back to that popup window instead of either the base page or a new tab/standard browser window.
Is that even possible? I assumed there had to be a way to create the popupwin with a URL, pass that page the current form values, and tell that popupwin to itself submit the form so that it, not the base page, gets the results. Doable?
Calling window.open() will invoke the server script, but it won't send the form parameters to it.
You need to change the form's action to be the server script:
function doThisScript() {
var form1=document.getElementById('form1');
form1.action = 'resultprogram.asp';
form1.target = 'resultswin';
}
}
You don't need to call submit() explicitly, since that's the default action of clicking on the submit button.

Console.log data from HTML form input

https://codepen.io/anon/pen/NYaeXV
I am trying to log the value of a HTML form input. I put multiple options inside the CodePen. Here is my initial thought process.
<form action="">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value());
}
sConsole();
You need to use value instead of value() since value is not a function , also consider using e.preventDefault() to avoid the page reload one more thing , by adding sConsole() into your js file you're asking the function to be executed when the page load, you need to move your function to the submit event instead.
Here is a working example and Happy coding :)
function sConsole(event) {
event.preventDefault();
var data = document.getElementById("data");
console.log(data.value);
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="" id="form" onsubmit="sConsole(event)">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
</div>
You missed onclick or onSubmit , you should also use .value
function sConsole() {
var data = document.getElementById("data");
console.log(data.value);
//!!Option 1a
//console.log(data.submit());
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="">
<input type="text" name="data" id="data">
<button type="submit" onClick="sConsole()">Submit</button>
</form>
</div>
You were close, just a few things to consider.
Getting the value of an input field
The value attribute of an input element stores the text in the textbox. To retrieve, this in javascript, use ExampleElement.value, for example:
var dataValue = document.getElementById("data").value;
or
var data = document.getElementById("data");
var dataValue = data.value;
You can also specify the value attribute in the input tag with value="". This is useful if you want to prefill the input text box, for instance, if you send the user input to a php script for action and wanted to return the textbox with information already included.
Calling a Javascript Function
There are multiple ways to call a javascript function, including doing so when certain events occur. In your situation, you probably want the input value logged every time the user clicks submit. You could add an event listener, but for simplicity sake of understanding, let's just use inline code. Every time they submit, let's log it, so onsubmit="sConsole();". Now the submit action will run your logging function.
If you wanted to log every change while the user was typing, you would use an event listener with more complex evaluation of the input value.
Prevent Default
It's likely that you don't want the form to actually be submitted to the server and page reloaded every time the user clicks submit. By using event.preventDefault();, javascript prevents the usual action of submitting the form to the server and instead leaves the user input and the page as is.
If you want the textbox to be "erases" after each submit, it's probably best to reset the value in your function rather than submitting the form. To reset the value, you would simply do data.value = "".
Code Example
Putting it all together, here's an example code segment with comments about your original sample.
<form action="" onsubmit="event.preventDefault(); sConsole();"> <!-- use inline JS to print input to console on submit -->
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
<script>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value); // data is the element, and we want its value
}
//sConsole(); This would call it only on script load, which isn't what you want
</script>

html submit form ajax response

Im currently loading my pages in Codeigniter using ajax for sections of the page.
but, when i press submit on one of the loaded forms, i dont get the response out from it. its like the form never was sent. im exspecting the layout to be proccessed, instead it returns the same layout as if it wasnt proccessed.
How can i make so, when pressing submit button on the loaded form data, that it will be proccessed by the same url, and then load the new response to the view?
piece of code:
$("form").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$(".main_center").html(data);
});
return false; // prevent normal submit
});
piece of html:
<form method="POST" action="/crime">
<input type="hidden" name="crimeinput" id="crimeAction" value="123">
<input type="submit" value="do" name="docrime" id="krimsubmit" style="display:none">
</form>
EDIT:
After more looking into it, it seems like only the crimeInput variable is sent to the server, and not the docrime. How can i make it able to send the submit name aswell?
As per the docs for serialize:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
So if you want that field to be passed, you'll have to add it in a different way, perhaps as another hidden input.

Update form fields without refresh (prevent duplicated form)

I need to update (submit) form without refresh. I know it should be done using Ajax, so I found many examples on this website, but none of them was useful in my case. Here's the catch - I don't need to display any "success" or similar messages when form was submitted, I need to display exactly the same form, but with new values.
Examining examples on this site, I got it working, but when form is submitted via ajax (this part works fine), I see two forms displayed. Here's the example - http://www.lipskas.com/form/ (the whole source is available to view)
What should I change here?
P.S. If I change "$('#msg').html(html);" to "$('#myForm').html(html);" duplicated form doesn't appear, except one "little" problem - the form can be submitted only for the 1st time. Then no more values are properly submitted.
In case you are interested why I need to display exactly the same form (but with updated fields) again, it's because I built some type of calculator which has many fields, and when user updates ANY field, re-calculations are made ( http://lipskas.com/bandymas/ )
Get rid of the "onclick" in the submit button and add this in the header above the chk function
<body>
<form id="myForm">
<input type="text" name="username" value="submitted - "><br/>
<input type="text" name="password" value="submitted - "><br/>
<select name="some_array[1]"><option value="1">1</option><option value="2">2</option></select>
<select name="some_stuff[2]"><option value="3">3</option><option value="4">4</option></select>
<input type="submit" name="submit_ok" value="test me">
</form>
</body>
function chk(this)
{
$.ajax({
type:"post",
url:"index.php",
data: this.serialize(),
cache:false,
success: function (html){
$('body').html(html);
}
});
}
$(function(){
$("body").on("submit","#myForm",function(){
chk($(this));
return false;
});
});

How can I submit a form automatically (onevent) with javascript?

I'd like to be able to submit a form automatically on an event ( a generic form, for user tracking).
For example, create a POST to
http://www.example.com/index.php?option=track&variable=variable
application/x-www-form-urlencoded with stuff like
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2
The actual string will be preformatted, though, because all it is is like a 'ping'.
It needs to be submitted onevent, with external js ( http://example.com/scripts/js.js )
What the hay should I do? This is getting annoying.
Update: I guess I didn't really make myself clear; I have a premade form that isn't supposed to display on the page; it needs to submit on an event. The form fields do not exist on the page; all I do is link to the script on the page and it executes onLoad.
POST uri: http://www.example.com/index.php?option=track&variable=variable
The arguments above (option=track and variable=variable) are not the form details (postdata).
The content type is application/x-www-form-urlencoded , and has the following keys/values.
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2 (when encoded, the spaces get turned to %20's.)
I need a script that submits this when run.
You have to get the form object and call the submit(); function provided by HTMLFormObject.
document.getElementById('myForm').submit();
1) with the following, (while page is loaded), the form will be immediately autosubmited
<form action="post.php" name="FNAME" method="post">
<input type="text" name="example22" value="YOURVALUE" />
<input type="submit" />
</form>
<SCRIPT TYPE="text/JavaScript">document.forms["FNAME"].submit();</SCRIPT>
another formSubmit alternative - submits any script:
document.forms[0].submit();
2) or use button click after 2second:
<SCRIPT TYPE="text/JavaScript">setInterval(function () {document.getElementById("myButtonId").click();}, 2000);</SCRIPT>

Categories

Resources