Javascript Function Not Preventing Form Submission with IF ELSE statement - javascript

I am using a small page to create a team of two members and it should stop the page from submission if someone selects the same member in both fields. I amusing following code:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create"
onClick="return checkDouble();" />
</form></html>
<script>
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble(){
if (2>1)
{
alert (tm2);
return false;
}
</script>
I have created a jsfiddle
If anyone can help it will be really helpful.
I know that my function is working as far as the calling the function is concerned but however somehow it does not work with if and else statement.

Try this . And Match the mmbr1 and mmbr2 selected value . And your function not closing properly with end of }
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble() {
if (mmbr1.value == mmbr2.value) {
alert(tm2);
console.log('fail')
return false;
}
else{
console.log('pass')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form action="" method="post">
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood2</option>
<option>Ahsan2</option>
<option>Usman2</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id" onclick="getText()">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>
</html>
<script>
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].text;
function getText() {
tm2 = mmbr2.options[mmbr2.selectedIndex].value;
};
console.log('选择的是' + tm2);
function checkDouble() {
if (2 > 1) {
alert(tm2);
return false;
}
}
</script>
enter code here

Forked yours, and added an event handler.
https://jsfiddle.net/springfeld/25ys4vm2/
First found: no closing bracket for your function.
One has to return a value, in every case, even if its dead code, so did i:
if (2>1)
return false;
return true;
Even if you strangle a function like checkDouble into onsubmit, as you did, you have to add an alternative. Think about like: What if 2 is smaller than 1? In that case the function now returns true, and evaluates correct in the eyes of your engine.
event.preventDefault();
within handler prevents it from running as designed, in your case to submit the form to the server. Think of it as a stop sign to the browsers default behaviour.
But keep in mind: This can be overridden by disabled javascript. If you disable javascript, forms values are submitted without further checks.
Hope: helps.
Have a nice.
Udo

Related

Why does this span tag only changes for less than a second?

This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>date of birth</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<main>
<div id="div1">
<h1>Age in days</h1>
</div>
<form id="user_input">
<input id="age_years" type="number" placeholder="Put your age in years">
<input type="submit" class="btn btn-success" id="submit_button" onclick="ageInDays()">
</form>
<div>
<p id="finalText">This is your age in days: <span id="span">0</span> </p>
</div>
</main>
<script src="app.js"></script>
</body>
</html>
This is my Javascript:
"use strict"
function ageInDays() {
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
When I run the code, it only shows the answer for a split second and then it goes away. Does anybody know why this happens?
The page reloads after showing the value in span because it is the default behavior while submitting forms, if you simply want to calculate the age in days and show it into span tag and don't want the values to be submitted using form then you can simply do this, just add onsubmit="return false" to your form element,
Like this
<form id="user_input" onsubmit="return false">
Hope it helps!
It actually submits the form by defaults, hence it refreshes the page, try to prevent the action:
in your HTML:
<input type="submit" class="btn btn-success" id="submit_button" onclick="ageInDays(event)">
in your JS:
function ageInDays(e) {
e.preventDefault(); // prevents from reloading the page
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
It may be possible that javascript is running before HTML is rendered. Try this one is .js file.
window.onload = function(){
"use strict"
function ageInDays() {
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
});

Multiple input boxes - alertifyjs / Jquery

I am trying to create a prompt dialog box using alertifyjs that has multiple input boxes. I have managed to create the dialog box to show the multiple boxes but I cant seem to make a reference to the inputs that user provides.
I want to write if statement that carries out action based on user input when they press OK. However, the OK button doesnt seem to be working and also the if-statements don't work as well. I am not sure what I might be doing wrong, can someone please help me.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css"/>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css"/>
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;" >
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value"/>
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value"/>
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title',"Update");
</script>
</body>
</html>
Link to JSfiddle: http://jsfiddle.net/1qouxdkc/4/
In your script you call a function named updateListItems(inpOneVal,inpTwoVal);
As that function is not declared anywhere, it errors, so with that temporarily commented out, it works.
Stack snippet
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;">
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value" />
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value" />
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
//updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title', "Update");
</script>
</body>
</html>

Why is the a form fade function not allowing validation?

Is this code correct? I want the 'submit' to validate the field (to make sure a value has been entered) and if this is correct (there is a value) then fade and display.
Currently, the form fades even when no value is entered? I feel I'm missing something really simple here!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />
<link rel='stylesheet' type='text/css' href='styles.css' />
<meta charset="utf-8"-->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div id="sidebarf">
<form id="sidebarform" name="myForm" onsubmit="return validateForm()" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" required>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
<script>
$("#sidebarformsubmit").click( function(){
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() )
});
});
</script>
</body>
</html>
Judging by your comment on the other answer, you don't care if this actually gets submitted, so you could do the following:
HTML:
<div id="sidebarf">
<form id="sidebarform" name="myForm" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" />
<input type="submit" id="sidebarformsubmit" value="Submit" />
</form>
JS:
$(document).ready(function() {
$('#sidebarform').on('submit', function() {
if ($('#sidebarusername').val() == '') {
alert('First name must be filled out');
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() );
});
return false;
});
});
Working example:
http://jsfiddle.net/3z5x8/
Your validation is bound to the submit event. The click event will always be fullfilled.
Bind your handler to the submit event also
$("#sidebarformsubmit").submit( function(){.....
Unless you are submitting with ajax the form will cause a page refresh also which means your fade and show new html won't work

Button not running javascript

So this should be changing the page so that when they click the button it shows a total of everything they have selected in the form, but it is not doing anything. It seems that it is not even running the script at all, and I have no idea what is up.
...more form stuff up here
<button type="button" onclick="total(this.form)">Get my Total</button>
<p id="subtotal"></p>
<input type="submit">
</form>
<script>
function total(form)
{
var SynCr= form.Synth.value;
document.getElementById("subtotal").innerHTML="You have ordered: <br>"+SynCr+" Synth");
}
</script>
Your problem is onclick="total(this.form)". When the handler is called this refers to the button, which does not have a form as a member.
Try instead:
onclick="total(document.getElementById('formId'))"
First of all:
this.form does not return the parent form.
Second: you have a syntax error in: document.getElementById("subtotal").innerHTML="You have ordered: <br>"+SynCr+" Synth"); the last ) should not be there.
The following is sinppet of code shows you in some what how to debug your code and it works:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<form id="hgg">
<input type="text" name="Synth" value="" />
<button type="button" onclick="total(this)">Get my Total</button>
</form>
<div id="subtotal">
<p>5518</p>
</div>
<script>
function total(button)
{
form1 = button.parentNode;
alert(form1.Synth.value)
/*alert(p.id)
alert("555");*/
SynCr= form1.Synth.value;
alert(SynCr)
k = document.getElementById("subtotal");
k.innerHTML = "You have ordered: <br>"+SynCr+"Synth";
}
</script>
</body>
</html>
Look at this online demo: http://jsbin.com/voruzumi/1/

Javascript to load page not working

I'm trying to get text from a text input, append it to a URL, and go to that URL, using Javascript. But when I submit, it appears to just reload the page.
http://jsfiddle.net/E3vv6/
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
}
</script>
</head>
<body>
<form onsubmit="loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>
You need to use event.preventDefault() in the submit function.
Live Demo (click).
Further, inline js (onsubmit in your html) is bad practice for a lot of reasons. Here are some: https://www.google.com/search?q=Why+is+inline+js+bad%3F
If would be better to get a reference to the form with javascript and attach the event listener.
<form id="myForm">
<input type="submit" value="Submit">
</form>
JavaScript:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e) {
myFunction();
e.preventDefault();
});
function myFunction() {
console.log('submitted!');
}
You need to prevent the default behaviour of the onsubmit.
You could use return false:
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
return false;
}
</script>
</head>
<body>
<form onsubmit="return loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>

Categories

Resources