I have a search bar in my header. I did a validation test on it that if it is empty and the user presses the "Search" button then it should display a dialog box saying to "Write the product name". This validation works However on a couple of pages I have a search option that lets the user enter the price range for which he/she wants to see the products. They both are distinct and two different forms but for some odd reason when I put validation on the price range form, the validation skips that and displays the same "Write the product name" dialog box and highlights the search bar red which it shouldn't do at all. What can be the reason for it?
Here's the code for the search bar validation and form
<script>
function checkforblank()
{
if(document.getElementById('search').value == "")
{
alert('Please type a product name first');
document.getElementById('search').style.borderColor = "red";
return false;
}
}
</script>
<form action ="http://localhost/MyOnlineStoreOwn/product_search_result.php" method="post">
<input type ="text"name="search" id = "search" placeholder="Search for products..." align="right" />
<input type="submit" value="Search" />
</form></td>
Here's the code for price range search box and form
function checkforblank()
{
if(document.getElementById('price1').value == "")
{
alert('Please enter price first');
document.getElementById('price1').style.borderColor = "red";
return false;
}
if(document.getElementById('price2').value == "")
{
alert('Please enter price first');
document.getElementById('price2').style.borderColor = "red";
return false;
}
}
</script>
<form action="http://localhost/MyOnlineStoreOwn/product_list_priceSearch.php" onsubmit="return checkforblank()" method="post">
$<input name="price1" type="text" id="price1" size=8 />
to <br/>
$<input name="price2" type="text" id="price2" size=8 /> <br>
<input type="submit" name="sprice" value="Go" >
</form>
UPDATE:
if(isset($_GET['deleteid']))
{
echo 'Do you really want to delete this item with ID of ' .$_GET['deleteid']. '? Yes | No';
exit(); // doesn't render the whole page, only prompts the question script.
}
how do I make a dialog box to ask the "Do you really want" part and if the user selects yes it does: Yes
and he/she selects no then it does this:
I was having trouble writing the part inside of an echo statement because of the "" or ''..how do i write the correct syntax for echo "alert('Are you sure Y/N'); if yes do this and if no do this?
You cant have two functions on the same name. Might be you are getting the alert because the search script is loaded first.
For form validation, you need to write your code is another format. check this from w3 schools.
Try different function names.
Related
I hope you are all well.
I have a school assignment, and I want to dynamically be able to change the name of a 'project'. This assignment is about projects. The way I've done it right now works with the first 'project' from a list of 'projects' iterated through with thymeleaf. I'm aware that what I've done right now is absolutely bad code behavior, but we have had no teaching in JS yet. But I really wanted this feature.
I don't know how to make this work for each project preview, right now it works for the first preview, but for the rest it just erases the project name from database. (see picture)
<div class="projects" th:each="projectNames : ${listOfProjects}">
<form action="deleteProjectPost" method="post">
<input type="hidden" th:value="${projectNames.projectID}" name="deleteID">
<input type="image" src="delete.png" alt="Submit" align="right" class="deleteProject" onclick="return confirm('Are you sure that you want to delete this project?')">
</form>
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text()" align="right" class="editProject">
</form>
<form action="/projectPost" method="post">
<input class="projectInfo" name="projectID" type="text" th:value="'Project No.: ' + ${projectNames.projectID}" readonly="readonly">
<input class="projectInfo" type="text" th:value="'Project name: ' + ${projectNames.projectName}" readonly="readonly">
<input class="projectInfo" type="text" th:value="${projectNames.projectStartDate} + ' - ' + ${projectNames.projectEndDate}" readonly="readonly">
<input type="submit" value="OPEN" class="openProject">
</form>
</div>
<script>
function change_text() {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = document.getElementById("oldName").value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
document.getElementById("newName").value = changedText;
}
</script>
First form in HTML is the red cross to delete an entire 'project'. Second form is what is intended to change the name displayed on the 'project preview', but only works on first preview and deletes project name from the rest. Last form is the actual preview. I couldn't find another way to have multiple forms and do different POSTS while working with Java Spring and Thymeleaf.
My wish is to make the change_text() function work for each 'project preview'
Best regards!
function change_text(imageInput) {
var changedText;
var projectName = prompt("Please enter name of project:");
var oldName = imageInput.parentNode.querySelector('.old-name').value;
if (projectName === null || projectName === "") {
changedText = oldName;
} else {
changedText = projectName;
}
imageInput.parentNode.querySelector('.new-name').value = changedText;
}
<form action="/editProjName" method="post">
<input type="hidden" name="projectID" th:value="${projectNames.projectID}">
<input type="hidden" class="old-name" id="oldName" th:value="${projectNames.projectName}">
<input type="hidden" class="new-name" id="newName" name="projectName">
<input type="image" src="edit.png" alt="Submit" onclick="change_text(this)" align="right" class="editProject">
</form>
Ok so I made a few changes. First, notice the inputs with oldName and newName now have classes on them. These can be repeated. If you are not using the ids for anything other than the script, you should remove them. Otherwise if you have styling rules for them you should consider changing those CSS rules to use the class instead so you can remove the invalid repeating ids.
Secondly, the onlick of the image now passes in this. What that does is it passes in the actual input that the user clicked, so you have some context into which form element the user is interacting with.
Then looking at the logic, the method now accepts in imageInput which is the this from the onclick.
Using imageInput.parentNode we go up the DOM Tree to the parent element of the input, which is the form in this case. We can then turn around and use querySelector to find the other element in the form we want to manipulate. And it will only find the element in our particular form because that is what we are selecting off of.
(I know the questions is a bit long but I do believe solution is easy, so would really appreciate it if someone can help me have a look)
I am trying to write a school system, where you can enter a student's name, year, grade, on a webpage, and save the student's info to produce a list. I would like it to have two "buttons" on the webpage:
One is "save and next", i.e. if you finished entering one student info, click this, the info get saved and the webpage renew to enter the next student info.
Second is "save and finish", i.e. if this is the final student you want to enter, click this and the last student info get saved, and webpage is redirected to the next page where it shows a list of all student info.
To achieve this, in JSP, I used two HTML forms, and one of them I used javascript to try to submit to servlet, But I must have done something wrong because it does not work properly:
Here are my codes:
InputGrade.jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
The first form: used input labels for users to enter info, also used input label to create a submit button "save it next":
<form action = "InputGradeServlet" method="POST">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name = "stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="submit" value="save and next"/>
</td>
</tr>
</table>
<input type="text" name = "flag" style="display: none" value="1"/>
</form>
The second form include the "save and finish" button, but use javascript to submit the information: (I think where the problem is)
User still enter student info in the first form, but the javascript function use getElementById function to acquire the info in first form
<form name="form2" action ="InputGradeServlet" method="POST" >
<input type="text" name = "flag" style="display: none" value="2"/>
<button onclick="finSaveFunc()">Finish and submit</button>
<script>
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
document.stName.submit();
document.Subject.submit();
document.Grade.submit();
}
</script>
And in the Servlet, a list created to add the students the user entered
public class InputGradeServlet extends HttpServlet {
List<Student> inputStList = new <Student>ArrayList();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if user press "save and next" button, form one is submitted, and servlet do the action of saving student to the list and redirect to the same JSP file i.e. redirect the the same webpage again of entering the next student:(also might be problematic)
if (request.getParameter("flag").equals("1")) {
request.getParameter("Grade");
...... (get other info: name, year ect)
inputStList.add(findstudent); //add student entered to the list
response.sendRedirect("InputGrade.jsp");
}
}
}
If user press "save and finish", i.e. submitting the second form, and servlet again add the final student entered to the list and redirect to the next webpage showing the whole list:
}else if (request.getParameter("flag").equals("2")) {
request.getParameter("Grade");
....
inputStList.add(findstudent);
request.getSession().setAttribute("inputStList",inputStList);
response.sendRedirect("ShowList.jsp"); }
This is where it gets problematic: when submitting the first form hitting "save and next" button it works fine, but when submitting the second from hitting "save and finish" button, it returns error.
Therefore I would really appreciate it if some can help me have a look?
There are many reason that's why you can get a NullpointerException.
Rule of Thumbs : If you want to compare a string then first check if it is not null.
According to your requirement I am giving a solution that how can you do that.
Suppose your form be like:
<html>
<head>
<script>
function _submit(flagVal) {
document.getElementById('flagValId').value=flagVal;
document.getElementById('someFormId').submit();
}
</script>
</head>
<body>
<form action = "InputGradeServlet" method="POST" id="someFormId">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name ="stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="button" value="save and next" onclick="_submit('1')"/>
<input type="button" value="save and exit" onclick="_submit('2')"/>
</td>
</tr>
</table>
<input type="hidden" id="flagValId" name = "flag" value=""/>
</form>
</body>
</html>
Now when you click save and next button, then it set flagVal 1 and if we click save and exit button then it sets flagVal 2. After setting the flagVal it submits the form. After submitting your from you should check first that what is your flagVal. So in doPost method
if (request.getParameter("flag")!=null && request.getParameter("flag").equals("1")) {
//Add your student in this block and show the input page again.
response.sendRedirect("InputGrade.jsp");
}else if (request.getParameter("flag")!=null && request.getParameter("flag").equals("2")) {
//Add your student in this block and show the list.
response.sendRedirect("ShowList.jsp");
}
Hope that helps.
You don't get form1 values. You post form2 values so you get null error.
Try it please:
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
var newForm = document
.getElementById("form2")
.appendChild(stName)
.appendChild(Subject)
.appendChild(Grade);
newForm.submit();
}
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.
I'm having a bit of trouble with this assigment and would like your help.
We are meant to create a product registration form page with all the regular expressions and everything and display the correct error when the regexes don't match.
I am trying to print a tick or say OK next to a form field but I can't get the right function. My form right now looks like this: http://www.imageurlhost.com/images/98zrdmrmsvbxnwowrvsf.png
The "Please enter product ...." is activated by jquery with a slideUp and slideDown function with onblur on the text field.
So I want to display OK where the red circle is after you click away from it, and then if you change it to something that doesn't match the OK disappears and my alert shows up. So this is my code so far:
My html form:
<div>
<input type="text" class="name" placeholder="Name" name="name" onblur="return validateProductName()"> <p class ="p11" id="p1"></p>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
My css:
.p11 {
float: right;}
My jQuery:
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
And then my JavaScript:
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
So, it prints the OK in between the field on the right side, but I want it right next to the field like I showed in the picture and I can't get this to work! I want it to disappear if I go back to the form and put something wrong...
Thanks guys!
I assume, you have no problem with the jQuery itself, you have a problem of showing it next to input box. So,
Create a <span id='tick'> tag after the input field
And once it passes the validation, use jquery to show the tick
$('#tick').html('whatever you want');
EDIT: You dont have to include the float:left on span
Check out the fiddle link
EDIT:
In this validation function, just show and hide according to the validation results
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
document.getElementById("tick").style.display = 'none'; // to hide the OK text if enterd the wrong input
} else {
document.getElementById("tick").innerHTML = "OK"; //NOTE: This is for showing the ok text
document.getElementById("tick").style.display= "block";
}
}
Create a span wherever you want your tick to be displayed and they do this,
$("#btn").click(function() {
if ($("#txtname").val() == "") //can be any check
{
$("#g").attr("style", "display:block;width:20px");
} else {
$("#g").attr("style", "display:none;width:20px;");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtname" style="display:inline-block" placeholder="enter name" />
<img id="g" style="width:50px;display:none;" src="http://pixabay.com/static/uploads/photo/2014/04/02/10/19/check-303494_640.png" />
<br/>
<input type="button" id="btn" value="click to submit" />
This should work-
<script src="jq.js"></script>
<div>
<input type="text" class="name" placeholder="Name" name="name" id="input"> <span class ="p11" id="p1"></span>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
<style>
p11 {
float: right;}
</style>
<script>
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
validateProductName()
});
</script>
<script>
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.getElementById("input").value.trim() == "" || document.getElementById("input").value.length > 50 ) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
document.getElementById("p1").innerHTML = "";
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
</script>
I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>