I want to check value of input for year of birth. I have figured out that if I use jquery function val() to get value of this input, so the php post of this input will be empty. It works fine without using val(). Here you can see the important part part of code. It is not so essential ability of form, but it would be useful to check if the isn't written anything inappropriate or any mistype.
Thank you for help.
<?php
if (!empty($_POST['rn']) && isset($_POST['rn'])){
// proceed
} else {
echo "You haven't filled all inputs";
}
?>
<script>
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
</script>
<form accept-charset="utf-8" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="send_form">
<input class="bold" id="rok_nar" type="text" name="rn" placeholder="Rok narození"/>
<input type="button" value="Odeslat" name="kontrola" id="kontrolaButton" />
<input type="submit" value="Odeslat" name="odeslat" id="odeslatButton" style="visibility: hidden;" />
</form>
Update:
I have probably found the problem. I didn't write it here, because I didn't consider it as an issue. My script looks like:
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
alert(rok);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
After erasing the alert, the code works :/ Interesting...
It looks like your trying to access an input in the dom before it is loaded. I don't see a document ready. You need to either stick your script inside a document ready so it is delayed until the dom is completely parsed, or move your logic at the bottom of your page so the elements exist by the time you try to look them up.
You should move the script right to the end of the HTML body so that it executes when the kontrolaButton element is in the DOM.
Note that the mouse down/up or key press/release you issue to close the alert(rok); may interfere with the submission of the form. For instance, I could reproduce a problem like this: I pressed the ESC key to close the alert, and although the form submitted its data, the next page did not render; it was just a blank page. This may be very browser dependent, but on my set-up the ESC key apparently interrupts the rendering of a page.
There may be other such side effects, certainly also if you have other Javascript code on the page that responds to these key or mouse events.
Related
I've been trying to make a multi-page poll with jQuery Mobile that is supposed to interact with my MySQL database through Ajax/PHP and have been having issues with it for a while now. It seems I have some problems submitting the form as a result of having it split into several pages. One requirements I need is that the page can not have a page reload.
In my first attempts I tried to divide the pages up into the following:
<div id="page1" data-role="page">
This however failed so many times no matter how I tried to code it. I can not get the submit button to work and I think it could be caused by the fact that I have split the form into several div "pages". I've also tried to make next/submit buttons rather than "Next, next, next ... submit" so that I can store the temporary data in the session, unsuccessfully.
I reworked my whole strategy into a code that hides the question divs that are not active. By this I mean I have one div with data-role set to page, and within it I have several divs with data-roles of content that are hidden/shown by clicking through the form with the next button. I managed to make a small sample form this way that submits the whole form and gets printed out perfectly with some PHP code. However I have yet to successfully validate this version. I can only get my script to validate the last page, and even then it requires ALL checkboxes to be checked, which is pointless. When I tried to implement this version into my real project I could not get it to submit to the .php script at all, but that might just be some syntax error that I will keep looking for.
So, have anyone done anything similar? I'm looking for potential other strategies to solve this issue, or perhaps someone has a theory as to why my aforementioned attemps have failed. Seems Ajax form submits are hard to get working within jQuery Mobile?
Also in case someone can spot a flaw in this I've attached this code that I use for submission, is there an easy way to make this into a function? Or is that pointless?
$(document).ready(function()
{
$("#submit").click(function()
{
var data_string = $('#form').serialize();
$.ajax(
{
type:'POST',
url:'add.php',
data:data_string,
success:function(response)
{
$("#answers").html(response);
}
});
})
});
I also use this function during window.onload to generate the poll with a lengthy .php script. Basically it generates the questions as , every other question variety has only name="answers[question_id]".
function getQuestions(id)
{
var xmlhttp = getHttpRequestObj();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll2.php",true);
xmlhttp.send();
}
The form looks like this:
<form id="form">
<div data-role="content" id="form'.$page.'" class="section">
<fieldset data-role="controlgroup" data-type="vertical" data-mini="true" id="'.$question_id.'">
<input type="checkbox" name="answers['.$question_id.']['.$alt_id.']" id="'.$question_id.'_'.$alt_id.'" value="'.$alt_id.'"/>
<label for="'.$question_id.'_'.$alt_id.'">'.$alt_desc.'</label>
</fieldset>
<input type="button" name="next" value="Next" id="next" onClick="toggleVisibility(\'form'.($page+1).'\')" class="next-btn"/>
</div>
The last page has this code instead of the next button:
</div><input type="button" id="submit" value="Submit" class="submit-btn"/></form>
In my opinion, hiding the other options and open one by one is a better way (also called multi step form).
For validation, you can do it in client side with javascript or use ajax which triggers on appropriate event (you don't need to submit it for validation) and validates in server side.
You are in right track. The issue i see here is how you'l do the validation but that'l depend upon how your form is structured.
I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link
I have the following HTML page:
<div id="foobar">
<?php echo $dynamicVar; ?>
</div>
<input type="button" value="Submit" id="subButton"/>
When I press submit, the value of $dynamicVar will change. Is there a way, without using Ajax callbacks, .each(), or anything complicated, to do a dead-simple refresh of the div element? I know there's a jQuery function, I've seen it before, but I can't find it now. This function will just refresh an element. Everything I've found requires me to write unnecessarily complicated code to attempt to refresh a very small very simple element.
For example, if the the entire div had the value "1" inside of it, and I pressed the button, I want to refresh in order to show the value "n".
Here's the jQuery code:
$('#subButton').live('click',function() {
//dead-simple element refresh, nothing fancy necessary
});
Example #2:
<div id="foobar">
<?php echo time(); ?>
</div>
<input type="button" value="Submit" id="subButton"/>
Since time generally goes forward, the timestamp should be different from a few seconds ago when the web server gave me the timestamp. I would want to have the div element do a very simple update of itself so that I would see the new timestamp upon button click.
Any help?
Were you thinking of .load()? It's a high-level ajax function. You'd use it something like this:
$('#subButton').live('click',function() {
$('#foobar').load('thispage.php #foobar > *');
});
You'll have to use AJAX AFAIK, but in your $.ajax() callback, you can use $.replaceWith() (documentation).
$('#foobar').load('my/script.php');
Edit: I fixed the problem by just starting from scratch. Sorry to waste y'alls time. Please vote to close if you feel so inclined.
I'm having trouble getting the actual data in a form to submit when the input fields are added via javascript. The fields show up, and in the right place, but when I do a var_dump( fieldname) on the server side, nothing is showing up. Inspecting with Live HTTP headers tells me that the browser isn't trying to submit the dynamically added form fields.
Do I need to somehow "attach" my dynamically created form inputs to the form?
My code:
HTML
<form id="att_form" method="post" name="add_attachments" enctype="multipart/form-data" action="#">
<-- below input to prove form submits, just not the dyn added elements -->
<input name="data[one]" type="text" />
<div id="add_fields"></div>
<input type="submit" />
</form>
Javascript
function addFormField()
{
var id = 1;
var htm = "<p id='row" + id + "'><input type='text' size='20' name='txt[]' id='txt" + id + "' /></p>";
$("#add_fields".append( htm );
}
When I submit the form, my input named data[one] shows up as a POSTd value, but those added with addFormField() do not. They show up, in the HTML, at the correct place, but don't POST. Do I need to append the element as a child to my form element to get it to submit?
I've seen Submit form input fields added with javascript which is where I got the idea of appending the data specifically to the form child, but that will require some restructuring of my CSS. So, I'm hoping that it's something simple I can do in the above code.
Thanks in advance!
edit: fixed the typos, but still not working. I've decided to use the library free JS method discussed in the SO link above, as that works fine. Thanks for the help though!
there is 2 typos in your code:
htm instead of html
and add_fields / add_files
There were a lot of typos in your code. For example, you didn't close the selector tag for jquery.
You put
$("#add_fields".append( htm );
Should have been
$("#add_fields").append( htm );
Notice the missing parantheses.
But I believe your problem lies mainly in how you're trying to access the values through PHP. I just put your source in a test page and it all works if you access the values correctly.
<?php
foreach ($_REQUEST['txt'] as $printme)
echo $printme."<br/>";
?>
The above source works fine.
When you are adding/appending or using innerHtml to place form fields as html, then sometime it will place it outside the form, you will see it as part of form but internally it is not.
To resolve this issue you need to add form attribute with input filed like form=myForm, and myForm should be your form id.
Is that your actual code?
If so, you didn't close the input tag and the p tag.. so maybe the form ignore them..
var htm = "<p id='row" + id + "'><input type='text' size='20' name='txt[]' id='txt" + id + "' /></p>";
For the past few years I've focused on back-end development so my javascript & css skills are lacking. I'm volunteering as a webmaster for a site and would like to spruce up the form validation (currently there is none).
My problem:
Basically I have one form with a few name fields, an email address and a phone number. When the form is submitted I validate all fields. If data is invalid I would like to change that field's label color to red (similar to struts validation). What's the easiest way to do this?
Edit: I also have back end PHP validation. I'm looking to make it prettier and more user-friendly on the front-end. The PHP validation is located on a different server. If the validation fails on the back-end it displays a message and the user is forced to use the Back button. I'm hoping to re-direct back to the original page and display the invalid fields.
when you're building the page server-side, mark all the fields with errors in them:
<input type="text" name="phone_number" class="error_field">
555-121
</input>
Then in the page's CSS include an entry like:
input.error_field { color: #FFF; bgcolor: #C00; }
(The period's a "class selector", means it applies to all inputs with the class attribute "error_field". If you're already using classes for your input tags you can give elements multiple classes, just use spaces to separate.)
If you want to know what kind of code Struts is producing to color the page, one easy way is to use the Firebug extension for Firefox.
Assuming that the label is in the same level of the DOM hierarchy as the input and that it is right next to the input in the markup, you can do something like this.
First of all, some example HTML:
<html>
<body>
<form onsubmit="return validation()" action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" value="" id="name" />
<label for="email">Email:</label>
<input type="text" value="" id="email" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
As you can see, all of the inputs are preceded by a label with the correct for attribute.
Now for the Javascript, which would go in the head:
<script type="text/javascript">
function validation() {
//So we have a validation function.
//Let's first fetch the inputs.
name = document.getElementById("name");
email = document.getElementById("email");
//The variable error will increment if there is a validation error.
//This way, the form will not submit if an error is found.
error = 0;
//Now for validation.
if(name.value.length < 6) {
//We've found an error, so increment the variable
error++;
//Now find the corresponding label.
nameLabel = name.previousSibling;
//If we found the label, add an error class to it.
if(nameLabel && nameLabel.for = name.id) {
nameLabel.className = "error";
}
}
///////////////////
//Do the same with the email...
///////////////////
//Now, if there are no errors, let the form submit.
//If there are errors, prevent it from doing so.
return (error == 0) ? true : false;
}
</script>
Now just add some CSS:
<style type="text/css">
.error {
background-color: red;
}
</style>
Edit -- I guess you didn't want this sort of solution, but in case you want it to validate before going to the server, here you go. :)
Struts validation is happening on the server side; JavaScript validation runs on the client. The distinction is important, because server-side validation still works even if your client turns off JavaScript in the browser (and ~10% of people reportedly do).
Best to have both if you can.
You can put this together yourself, as others have suggested. But I seem to remember that Struts has its own JavaScript validation. It can be configured to generate JavaScript functions, which perform the same checks that are done on the server side. Check the documentation -- this may be a fast way to get started, although it may not be as customizable as you want.
I definitely haven't used struts before, but I do a lot of form validation with and without javascript.
In my opinion, you should always have both javascript and server-side validation, so it should work for everyone.
Server-side, you should do something like glaziusf.myopenid.com mentioned, just add a class to the element which shows it in red.
In javascript (and ajax), just add the same class to the element that you'd use server-side, but dynamically.
I'd recommend you learn a JavaScript framework like JQuery or Prototype. JQuery helps you to obtain values out of filtered-elements, modify their CSS, add visual effects, etc. really easily.
I don't really understand the PHP logic of your site, but you can put a validation in the same page if the action submits to itself, although I don't know if it's a good practice.
For example, you put the following at the top:
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
//field validation code...
To redirect with PHP you just say:
header("Location: THE_PAGE.php");
Although you shouldn't have outputed anything before that. You could probably pass a parameter back to your page (i.e.: THE_PAGE.php?valMsg=1) to tell it to show validation messages, or something of the sort.