Ok so I am really confused on this whole javascript in HTML stuff.
What I am trying to do is validate a form either "onblur" or on submit with an external file.
Here is the HTML code that works for the first field:
<script>
function notEmpty(rep, errMsg)
{
var errMsg = "Please enter something in Rep";
var rep = document.getElementById('submitted_by_hrrep');
if(rep.value == '')
{
alert(errMsg);
hrrep.focus();
return false;
}
return true;
}
</script>
This is in the body of the form near its field.
<script type="text/javascript">document.getElementById("submitted_by_rep").onblur=notEmpty;</script>
So that DOES work and will pop an alert that tells em to go back
What I CAN'T get to work is doing this for the rest (15 fields) of the form.
The "onsubmit" is confusing me and I think it's right but I am not sure.
<form onsubmit="return formValidation()" method="post" action="process.asp" >
Anything will help
EDIT
function validate()
{
if(document.newempRequest.submitted_by_hrrep.value ==='')
{
alert("Please provide your name");
document.newempRequest.submitted_by_hrrep.focus();
return false;
}
I got so frustrated that I started from scratch and took it a field at a time. Found that this works for the fields that need text, it looks messy for the file but calling it externally works flawlessly.
I wish I could use jquery but it seems to be more complex to setup that I actually need. Thanks for the help :)
You would have to grab all the inputs then iterate over them with a loop of some flavor, maybe a for loop?
with jquery it's really easy since there are already form validator plugins out there, and the selectors are really friendly. Using jquery,
$('#formId input')
would grab all the inputs in the form, then you can use a .each() to iterate through all the inputs
You obviously aren't going to be able to .focus() on all of the fields though, so need another function to handle the entire list instead of just one.
Related
<script>
function fun(){
let i=document.getElementById("input")
if(i==="sam")
{
alert("welcome SAM")
}
else
{
alert("welcome user")
}
}
</script>
<input id="input"/>
<button onclick="fun()">click</click>
if user type input as 'sam' it should be follow the if block but every time it execute else part .how to change the condition that when user type 'sam' in textbox then only it follow if block or else execute else part
getElementById method returns html element, if you want to get text inside input you should use document.getElementById("input")?.value
Make sure your input is correct.
Instead of writing "if(i===sam)", write "if(i=="sam").
Other than that, I think there's a problem with your input method. Javascript doesn't directly get the input from the box. For further information, check this link: https://www.tutorialspoint.com/How-to-take-user-input-using-HTML-forms
If you want to do it the easier way, just put "document.getElementById("input").value"
If this answer helped you, please mark it as an answer
Just add .value ahead of document.getElementById("input")
Just like that:
let i=document.getElementById("input").value
Basically, you're not passing the text to the variable i that is the reason else is executing
I'm working on a school project and have attempted to create a calculator that can be found at the following link:
http://jsfiddle.net/ae97vgxz/2/
And my JS is:
$(document).ready(function(){
// Setup variable as empty
var method = "";
// Detect when initial radio button is clicked
$("input[type=radio]").click(function() {
// Get the weight from the input box
var weight = $("#meatWeight").val();
// If the water method was clicked
if ($(this).hasClass("water")) {
var method = weight * 60;
// Show me what the value is (can be removed)
alert(method);
// If the fridge method was clicked
} else if ($(this).hasClass("fridge")) {
var method = weight * 793;
// Show me what the value is (can be removed)
alert(method);
}
});
When you use it, if you enter a weight first, then select a method of defrosting you will get the correct answer in an alert window. However, if you press the 'calculate' button you get the following message -
{"error": "Please use POST request"}
From doing some of my own research, I believe this is because I am trying to submit a form and JSFiddle doesn't let you do that. If I try on a local environment in Chrome, again there is no output.
I am very limited by my JS knowledge (as I'm sure you can see) so I just can't fathom out a solution. Can anyone suggest what I am doing wrong and what the solution might be?
Thanks!
You have a mistake here:
function defrost(weight) {
return (makeTime(method));
}
It should be:
function defrost(weight) {
return (makeTime(weight));
}
Also, you should change the makeTime function or it won't work. The parseInt clause should be like this:
parseInt(time / 60);
Your current method of submitting the form is GET
<form id="defrostCalculator" name="defrostCalculator" onsubmit="callbackDefrost(this.elements.meatWeight.value); return false;" method="GET">
If the destination requires POST, use POST.
<form ... method="POST">
Your code has a couple of minor issues. However, the major issue you have is that if you want to use a non-AJAX form on jsfiddle, you have to change all your buttons to have the attribute:
type="button"
instead of what you currently have:
type="submit"
When you do <input type="submit", jsfiddle.net squawks and fails because you cannot submit form information to their servers. Luckily, you do not need any AJAX or server interaction. So your simple calculator can just use simple buttons.
I have the following jsfiddle setup:
http://jsfiddle.net/xCCA2/
Basically when a the form is submitted, the size select dropdown is validated to make sure a selection has been made. If a valid size has been selected then the form is posted.
If an invalid selection is made, then an alert box "An invalid size has been selected" should popup.
Please can I get help debugging this.
Nb: there will be many forms on a page, and would prefer to uses classes rather than id's also there is some commented out html, where the form has been set a class, this works but anything within the form becomes clickable, which I do not want. Only the button should trigger the validation.
Thanks
try this
$(".wq").live( "click", function () {
alert("test");
if($("select").val()!="")
alert("not empty");
else{
alert("select a val");
return false;
}
// $(this).submit();
});
http://jsfiddle.net/xCCA2/4/
Look here
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Add
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
and required to the select
<select required
DEMO HERE
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}
I have created a webpage, in which i have a few input box and a submit button in a
<form action="" method="post" name="password">
On the click of the submit button, it calls a js function, which checks if the passwords are same, and if not it displays the error
if (passwrd1!=passwrd2)
{
document.getElementById("response").innerHTML="<font color='red'>Passwords do not match</font>";
}
It displays the error in:
<div id="response" align="center">Response from js</div>
But the problem is, it displays the function and then the same "Response from js" comes back.
What should i do to solve this porblem??
Best
Zeeshan
Do you also return false from submit button's click function to prevent it from actually posting back the form?
if (passwrd1 != passwrd2)
{
document.getElementById("response").innerHTML = "Passwords don't match";
return false;
}
Because from the small amount of code you've given us it looks like, your form gets posted back anyway.
You need a return false; in your if-statement, as the form will get posted even if the statement is hit. The return false will stop the form from being posted and will display the message.
Even though it's not part of the question, I will recommend you don't use the <font>-element, as it is deprecated and not exactly a good way of just displaying some red text. You can either output the error message in a span with the text color set to red like this:
document.getElementById("response").innerHTML = "<span style=\"color: red;\">Message</span>";
Not much difference, but following the standards of the web is always a good thing.
To give an example of what was said in the comments, you're probably even better off defining a class and styling it with CSS.
.errormsg { color: red; }
document.getElementById("response").innerHTML = "<span class=\"errormsg\">Message</span>";
The result is the same, but as said in the comments; it's easier to maintain, and thus a better solution.