Submitting a value of input without form - javascript

I'm creating a website game and currently I am struggling with something I will name "dialogue".
Initially I tried to approach this by creating a form element, but clicking enter or submitting it ended up with page refresh, which ruins everything.
So I used inpute type text without form that looks like this:
You are
<input type="text" id="dead">
<input type="submit" onclick="dead()">
and dead function looking currently like this, later it's gonna check for certain value, and if the value is true it's gonna run another code:
var talk = document.getElementById("dead").value;
function dead() {
alert(talk);
}
And I don't know how to save input from a form so it would be detected by JS and then used as variable in boolean check. How can I solve this problem? If there is a way to use a form tag without refreshing the page that could also work.

You can handle the submit event of your form like this:
document.getElementById('yourFormId').onsubmit = function(e) {
// your code goes here...
e.preventDefault(); // this will prevent the default operation of your form within this event
return false;
}
Or create a function:
function handleForm(e) {
// your code goes here...
e.preventDefault();
return false;
}
And add this to your form tag:
<form onsubmit="return handleForm(this);">

To be able sending some value without refresh the page you can use Asynchronous JavaScript + XML (AJAX) and if you're working with pure Javascript without some frameworks you can see a good documentation about Ajax.
But of course I suggest to use some frameworks like Jquery to make your works more easier

Related

Use javascript AND PHP in one <input> tag?

I feel like I've looked around for the answer for this question, but most of the responses are very hacky: involving javascript that pops in via AJAX, redirects and other ways of modifying the DOM on the fly.
What I want to do is make the submit button disappear when a user submits a document (javascript) and submit the message via mail (php). The code I have is the following:
<form action="" method="post">
...
<input onclick="removeElements()" id="subButton" class="submit" name="submit" type="submit" value="submit">
The php mail function is in the same document.
Here is the removeElements() function:
var el = document.getElementById("subButton");
el.remove();
document.getElementById("thankYouMessage").setAttribute("style", "display:block");
The submit function works without the javascript call, but when I add the onclick="removeElements()" part, then the javascript part starts working, but the php is no longer executed.
I know that there are other methods for doing this, but in this case, I'm actually curious about why this doesn't function as I had planned. By removing the submit button, am I in effect killing the child PHP process mid(or pre)-execution?
Thanks!
If you add onclick you will have to fire the submit manually.
The other option is add your javascript call code in onsubmit="removeElements()" on the form tag. This way, it will execute your code after executing submit
Related question here
Don't remove the button, rather set visible: hidden or display: none for its style. This way it will still be in the document and will work, it just won't be shown.
When you send the form reloads your page so I suggest:
Using Ajax and only delete button on the response, or
Not generate the button when reloads your page.
Jquery Ajax examples: You can see them here api.jquery.com/jquery.ajax/
Regards.
You could simple use the .hide functionality which JQuery gives you. It's very simple to use and very clean.
Example1 using JQuery:
$("#FormID").submit(function(e)
{
e.preventDefault();
// Hide button
$("#subButton").hide();
// Display thank-you message
$("#thankYouMessage").css("display", "block");
});
Example2 using JQuery:
$(document).ready(function() {
$(".submit").click(function() {
$("#subButton").hide();
$("#thankYouMessage").css("display", "block");
return false;
});
});

Javascript submit function working and not working

I hesitate to ask this as it is a bit complex, but I will try to make it simple.
I have a page with several form fields.
I submit the page via a submit script (note more is done in this submit script, but I am leaving it out for simplicity
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;
alert(gonext);
f.submit();
}
Please note that there are other variables included in this function. gonext is not the only one, but I am leaving the others out in this case to keep it simple.
My HTML for simplicity sake looks like this:
<form name="file_form" id=file_form action="<?= $this->URL('#', 'UpdateUploadUser', array('mode'=>'upload', 'ID'=>$_GET['ID']));?>" method="post" enctype="multipart/form-data">
<input type="text" name="oneitem">
<button name="submit1" id="submit1" onclick="do_file_form_submit(2);"><img src="<?=$theme;?>/images/12addphoto32px.png">Save Settings Then Upload/Register Another</button>
On the backend side within the "UpdateUploadUser" function we have a checker which checks each submitted field to see if it is empty or not. If it is empty, it returns:
$this->chk = new mVal($event);
if(!$this->chk->Validate()) {
$this->mode = 'error_redisplay';
//$this->mode='Error';
return;
}
If all info is there, then the script continues and runs as expected. So, here is the issue.
If all information is there, and I click the button, then all works fine. The file_form submit JS ALERTS the gonext value and the script runs and updates as it should.
HOWEVER, if an item is missing, then the validation script runs and "RETURNS".
Once the page has been returned, if you THEN attempt to click the submit button, the page STILL submits as it should, but the file_form submit script seems as if it doesn't even run, so that the gonext value is not passed at all.
So, I am trying to figure out how the submission of the form is still happening apart from this do_file_form_submit script. Is there something having to do with "return" that I don't know about?
Hope that makes sense and thanks for any help!
Craig
Review your code
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;//f.gonext. i can not find gonext in ur form. just oneitem try something like f.oneitem.value = gonext; i believe that is where the //problem occurs
alert(gonext);
f.submit();
}
in nutshell, replace the line:
f.gonext.value = gonext;
with
document.file_form.value = gonext;
and then submit like
document.file_form.submit();

CKEditor submitting empty content to the form.

I've started using CKEditor v3 few weeks ago.using it in a php project.i've been using it with jquery (using jquery adapter) and all this while using $.ajax (because can't handle for errors when using jquery form) to submit and i thought everything was alright .
So here pops up a case where i need to use normal form mechanism to submit the ckeditor content and all the other information of the form.
To my surprise the content was empty so i started google and apparently it's a known issue.
i haven't seen any thing YET that could let me post my content to php side. so i've come up with a workaround.
I know onclick will always fire before the onsubmit so i've written this.
function returntoSubmit(){
myForm = document.forms[0];
myForm.elements["content"].value = $("#content").val();// note that the textarea name and id are all the same "content"
}
// html here
<input type="submit" value="Save" onclick="returntoSubmit()" />
that does the work for me.But truly and a little uncomfortable with this, isn't there any better method to solve this issue?
Thanks
I'm running a large application with some nasty legacy code and needed something that worked across the whole app as non-intrusively as possible. In my case it wasn't feasible to listen for submits on each page individually, and even when I did I occasionally had race conditions where the submit still occurred before the click event code had a chance to do it's thing. The following seems to do the trick for me when ran after page load at a global scope:
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].on('blur', function() { this.updateElement(); });
}
May this help
CKEDITOR.instances[content].getData()
Just ran across this problem too... it seems that the best way to update all the textareas is:
for(var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
http://cksource.com/forums/viewtopic.php?f=11&t=15877
I have actually added my own twist that works nicely as I was having trouble today with the same issue.
I used your function call, but instead do this i give my textarea the ID of ckeditor:
function returnToSubmit() {
$('#ckeditor').val(CKEDITOR.instances['ckeditor'].getData();
}
I used this in a jquery ready event for all forms:
$('form').on('submit',function(){
for(var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
}
});
Later I add another specific form submit event handler to do the actual custom submit logic for each form.

AJAX jquery Form Post not working

I am trying to post a form using ajax.
Right now, the code I have is
$("#sub").click(function() {
var tag = $("#tagbar").val();
var opinion = $("#op").val();
alert($("#expressform").serialize());
$.post("dbfunctions.php", $("#expressform").serialize());
});
This works, but it takes a long time to post and add to the database (thats what dbfunctions does) compared to how long it took before, when I was using a form action and refreshing the page. Why is this?
Also, if I remove the alert, the script stops working completely. I can't figure out anyway in which this makes sense.
Thanks
Make sure you cancel the default action of the button by returning false from the click handler:
$("#sub").click(function() {
$.post("dbfunctions.php", $("#expressform").serialize());
return false;
});
Also instead of subscribing for submit button clicks, it's better to subscribe to the submit event of the corresponding form directly:
$("#expressform").submit(function() {
$.post(this.action, $(this).serialize());
return false;
});
This way you are no longer hardcoding any urls in your javascript files. You are simply unobtrusively AJAXifying your form.
You can use below function for submit the data
through Ajax form Submit
$('#form1').ajaxForm({
success:function(response){
$('#save_data').html(response);
});
$('#btnSubmit').click(function() {
$('#form1').submit();
});

onBeforeUnload and multiple forms

I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.
Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.
As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

Categories

Resources