Strange behavior of javascript && - javascript

I am using below method for validating that one of radio button must be selected.
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
In above method searchType is radio button which is creating two buttons. It works fine that is shows alert message if none of the two radio buttons are selected but it show alert message even when second of the radio button is selected. Any idea please?

<html>
<head>
<script language="javascript">
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1">
<input type="radio" name="form1:searchType" /> male
<input type="radio" name="form1:searchType" /> female
<input type="submit" name="submit" value="submit" onclick="validateForm()" >
</form>
</body>
</html>
i am using your function in this code and its working fine, it may help you

You need to use the or operator, not and - when using && it will be true only when both conditions are true - when one of them is false the whole statement is false as well.
So, just change to:
if(a || b){
alert('Please select search type');
return false;
}
And it should do what you want.
Edit: sorry, got confused myself with the boolean logic.
From quick test your code does work exactly as-is: only when no checkbox is ticked the alert shows up.
Please explain what is the problem and steps to reproduce in the jsFiddle if possible and we'll see.

Related

Html/javascript: Unable to disable Textbox

Not really sure how to phrase the question but I have created a function where if a button is disabled, the textbox below should also be disabled, but it's not. Here's the code:
<script>
function Play(){
if (document.getElementById("high").value > document.getElementById("low").value){
document.getElementById("myBtn").disabled = false;}
else {document.getElementById("myBtn").disabled = true;
document.getElementById("ErrorForPlay").innerHTML = "Numbers Wrong."}
}
</script> //this script checks to see if the higher number is less than the lower number. Will be disabled if so.
<br>
<button id="myBtn" onclick="Play()">Play</button>
<span id="ErrorForPlay"> </span>
<!--assume that the button on top is always disabled-->
GUESS: <!--But the textbox does not disable-->
<br>
<Input type="number" id="guess" onclick="dataValidationG()" onchange="dataValidationG()"> </Input>
<button id="submit">Enter Guess</button>
<script>
function dataValidationG(){
if (document.getElementById("myBtn").disabled = true;){
document.getElementById("guess").disabled = true;}
else {document.getElementById("guess").disabled = false;}
//script to check. If Button "myBtn" is disabled, the text should also disable if not, the text should be enabled.
}
</script>
I'm sure it has something to do with the javascript but I can't place where did I go wrong/what's missing. (I'm also only allowed to do everything under 1 html file.)
The problem is in your if statement conditions, you are using = and not ==.
And thanks to JavaScript being such a nice programming language, it doesn't throw a syntax error, but instead sets the value inside the if statement condition!
So just replace the = with == inside your if statement conditions.

JS validation, why this code won´t work?

I can´t get the validation in JS, and don´t understand why it doesn´t work.
The user should get an alert if at least one of the checkboxes isn´t checked.
It doesn´t work, because the form gets submitted ok even if if none checkboxes are checked.
<body>
<script>
function validar()
{
var s1=document.getElementById('s1');
var s2=document.getElementById('s2');
if (s1.value==''||s2.value=='')
{
alert("You must check at least one!");
return false;
}
}
</script>
<form name="calcular" onsubmit="return validar()" method="post">
<input type ="checkbox" name="servicios[]" id="s1" value="sinservicios">Sin servicios<br>
<input type ="checkbox" name="servicios[]" id="s2" value="dosservicios">Dos servicios<br>
...
You may try using the checked property to ensure that at least one of the 2 checkboxes is checked:
<script>
function validar() {
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
if (!s1.checked && !s2.checked) {
alert('You must check at least one!');
return false;
}
return true;
}
</script>
Also notice we should return true in case the validation succeeds.
The reason why your code doesn't work is because you have used the value property. That's always gonna return the value attribute of your checkbox (sinservicios or dosservicios) no matter if the user checked or not this checkbox. It will never return an empty string which is what you seem to be testing for in your if condition.

calling a function again in javascript

<!DOCTYPE html>
<html>
<head>
<title>input number</title>
</head>
<body>
enter no:1<input id="t1" type="text"><br>
<button type="button" onClick="myFunction()">submit</button>
<button type="button" onClick="myFunction()">next</button>
<div id="div1" style="color:#0000FF">
</div>
<script>
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no))
{
alert("Not Numeric");
}
else{
if(no!=1){
if(no%2==0){
no=no/2;
}
if (no%2!=0) {
no=(no*3)+1;
}
}
}
document.getElementById("div1").innerHTML = no;
}
</script>
</body>
</html>
After entering number in the text box when I press submit button it shows the following output
enter no:1
submit next
16
but when i press next button it is not showing any output.My expected output is when I press next button it shoult show the next no. by executing the logic in the myFunction() function.Helpme...
You haven't set any case for when no = 1. You have a case for when no != 1 and when no%2 != 0 both of which are false when no = 1. There isn't any increment logic in here to find the next number and return it. I think you are missing a } at the end of the no%2==0 clause.
Also I fail to see why you have two identical buttons here, next and submit do the same thing. Moreover I would advice more descriptive IDs. div1 isn't a good name for a div.
The javascript part should look like this, if the intention is to implement Collatz conjecture. http://en.wikipedia.org/wiki/Collatz_conjecture
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no)) {
alert("Not Numeric");
} else {
if(no!=1) {
if(no%2==0) {
no=no/2; // Note the division operator instead of mod
} else {
no=(no*3)+1;
}
}
}
document.getElementById("t1").value = no; // Note that we are writing to the textbox
}
There are some basic HTML issues too, in your post you are using the input tag as
<input id="t1" type="text"> use it as: <input id="t1" type="text" />
Secondly, when you submit the data to the function, you are having some value there! Maybe 1 is the value or 16, whatever. But when you are trying to resubmit, either its not allowed or your input is now an empty field. So the function is not executing further than this step:
if(no==""||isNaN(no))
Try to save the value in the form.
Try using this:
document.getElementById("t1").value = no;
Make sure that the value is captured as it was, because your code is changing the value into some other form, use a new variable for this. That would save the value from the input and again write it back to that input.
This will set the value for that text input as it was before the function. It might make the input again ready for the submit!

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

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 :)

Categories

Resources