Validate specific input, Javascript - javascript

<form action="/cgi-bin/Lib.exe" method=POST name="checks">
<input type=checkbox name="user1" value="'$NAME'">
<input type=checkbox name="user2" value="'$NAME'">
<input type=checkbox name="user3" value="'$NAME'">
<input type="button" value="User 1" onclick="somefunction()">
For example, if I selected checkbox user2 I would want the javascript function to pop up saying "you are not user 1..." (all input check boxes are under same form name).
After validation of specific check box name I will do document.checks.submit();
Thanks.

I'd propose few improvements to sktrdie's reply.
This will avoid submitting form on errors.
<form action="".... onsubmit="return somefunction(this);">
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) {
alert("you are not user1");
return false;
}
return true;
}
Note #1: this example is very simple and not-so-flexible, so additional reading on forms validation would be good idea. Say, on w3schools
Note #2: do not forget to implement server-side validation along with this. JS checks can be easily avoided.

<form onsubmit="somefunction(this);" ...
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) alert("you are not user1");
}

You may want to use the checkbox's onclick event to do the validation... So when they click it to turn it on/off you can catch em immediately, before form submission.
<input type=checkbox name="user1" value="'$NAME'" onclick="javascript:validatecheckbox(document.checks.user1);">
And then whatever you want to validate against in the JS function: (sorry for some reason the encoding of this code isn't working right... but hopefully you get the idea)
<script language="javascript">
function validatecheckbox(inputbox) {
if (inputbox.checked)
alert ('Are you ' + inputbox.name + '?');
}
</script>

Related

JavaScript function() is not a function

I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function
The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

JavaScript Radio button selection validates fields?

I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>​​​​​
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

If input2 empty copy value from input1?

This is my first message here so I hope that newbies also get help :)
My problem is following:
let's start with code first....
javascript:
$(document).ready(function(){
if ($("input#datum2").val() == "")
{
$().click(function(){
$("input#datum2").val($("input#datum1").val());
});
}
});
html:
<form >
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)...
When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition
if ($("input#datum2").val() == "")
works only once.
I'm new to javascript and jquery so I would appreciate for any help.
Thanks in advance!
Cheers,
Ile
Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.
$(function() {
var $datum2 = $('#datum2');
$('#datum1').blur(function() {
if(!$datum2.val())
$datum2.val($(this).val());
});
});
Couple of things:
1) $(function() { ... is a nice shortcut to $(document).ready
2) In JavaScript, an empty string evals to false, so its a nice shortcut.
I see the way round are the order of the click event and "if ($("#datum2",..."
HTML:
<form id="myform">
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
Javascript:
$(document).ready(function(){
$().click(function(){
if ($("#datum2", $("#myform")).val() == "") {
$("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
}
});
});
$(document).ready(function(){
var $datum2 = $('#datum2');
$('#datum2').hover(function() {
if(!$datum2.val())
$datum2.val($('#datum1').val());
});
});

Categories

Resources