How to check if a html control exists? - javascript

How do I check if an HTML control exists?
This is my code:
var id = ...
if(document.getElementById(id)!=null)
{
//do something
}
if the html control is radio doesn't work.
How is this done?

Further to your comments above, you should use a unique id for each radio button, but you can use the same name for your radio group. Consider the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Testing document.getElementById()</title>
</head>
<body>
<input type="radio" id="my_radio_1_id" name="my_radios"> My Radio Button 1
<input type="radio" id="my_radio_2_id" name="my_radios"> My Radio Button 2
<script type="text/javascript">
if (document.getElementById('my_radio_1_id')) {
alert('It Exists');
}
</script>
</body>
</html>
It will alert 'It Exists' as expected.

function validate(ValFrm) {
var len = ValFrm.elements.length;
for (i = 0; i < len; i++) {
if (ValFrm.elements[i].required == "Yes") {
if (ValFrm.elements[i].value == "") {
alert('The ' + ValFrm.elements[i].title + ' is required to contain data.');
ValFrm.elements[i].focus();
return false;
}
}
if (ValFrm.elements[i].type == "radio") {
if (!ValFrm.app[0].checked && !ValFrm.app[1].checked) {
alert('Please accept or deny.');
return false;
}
}
}
}

Related

How to make an input for key verify with any prefix?

So I tried to make a key input that when users write something, prefix to be geton_ and random characters next... For example: geton_adminloginpanel or geton_lgpanel.
Tried this but not work like I thought:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>KeyPanel</title>
</head>
<body>
<span>Enter The Key</span>
<input aria-label="Enter the key" id="key-text" placeholder="Key" value="">
<button role="button" value="submit" id="key-btn" onclick="fctbtnkeygetorerror()">LOGIN</button>
</body>
</html>
JAVASCRIPT:
<script>
function fctbtnkeygetorerror() {
if (document.getElemetById("key-text").value == "geton_" + document.getElemetById("key-text").value) {
alert("Successfully Logged In");
} else {
alert("Invalid Key");
}
}
</script>
<script>
function fctbtnkeygetorerror() {
main_password = "geton_Password";
prefix = "geton_";
input_value = document.getElementById("key-text").value;
new_value = prefix+input_value;
if(new_value==main_password){
alert("Login Success");
}else
{
alert("Invalid Login");
}
}
</script>

How to get latest inputs by pressing the up arrow (Javascript)

How can i get the latest inputs I entered in order. For example:
I declared an array with 20 elements and when I input something I delete the first element of the array and add at the end the input I just entered.
So when I press the upArrow button the last element of the array will appear as the new input. If I press one more time the upArrow I want my input to change to my second last element and so on.
It doesn't work in my jsfiddle link. It outputs another element from the array.
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20);
latestInputs.fill("Latest");
function clickMe(){
singleValues = $( "#input" ).val();
var c = latestInputs.shift();
latestInputs.push(singleValues);
$( "#output" ).append( singleValues);
$("#input").prop('value', '');
}
$(document).on('keypress',function(e) {
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', latestInputs[theInputsNumber]);
theInputsNumber--;
}
});
if(e.which == 13) {
theInputsNumber=19;
clickMe();
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>
You've missed the idea that you must determine (logic test) the value of the counter (theInputsNumber) in order to reset at the top (and the bottom) of the stack.
I renamed theInputsNumber counter and provided the UP key and DOWN key feature. I also did not limit the array size to 20 as that won't make a difference anyway (array size is not restricted in size as it is in other languages).
EDIT (based on comment): I've placed everything within the HTML so you can save this content into an HTML file and open with your browser. It will work just fine with no server.
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
<script>
var counter = 0;
var latestInputs = [];
function clickMe() {
let input = $("#input").val();
latestInputs.push(input);
$("#input").prop('value', '');
}
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', previous());
} else if (e.which == 40) {
$("#input").prop('value', next());
} else if (e.which == 13) {
clickMe();
}
});
function previous() {
counter = (counter === 0) ? latestInputs.length - 1 : --counter;
return latestInputs[counter];
}
function next() {
counter = (counter === latestInputs.length - 1) ? 0 : ++counter ;
return latestInputs[counter];
}
</script>
</body>
</html>
it looks like your function on upArrow was triggered multiple times (3) every time you pressed that key, I moved it outside of the "keypress" binding and it stays on its own, and the problem no longer exists when i run the code
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20).fill("Latest");
function clickMe() {
singleValues = $("#input").val();
latestInputs.shift();
latestInputs.push(singleValues);
theInputsNumber = 19;
$("#output").append(singleValues);
$("#input").prop("value", "");
}
$(document).on("keypress", function (e) {
if (e.which === 13) {
clickMe();
}
});
$("#input").bind("keydown", function (e) {
var x = e.which || e.keyCode;
if (x === 38) {
$("#input").prop("value", latestInputs[theInputsNumber--]);
if (theInputsNumber === -1) {
theInputsNumber = 19;
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>

How to delete an appended message in jquery after you have already appended once clicking the same button?

I have looked through a lot of the already asked questions and cannot find it. I need the previous appended message to be deleted once you hit the submit button again. So this will let you choose your character that you type into the input field and then it will append a message bellow telling you that you choose x character. After that you can resubmit another character which I want, but I do not want the previous append to be there.
I tried to do a search function in javascript and if it was not equal to -1 then delete the first p in the div, but that did not work=/
Thanks for your help in advance.
html:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link rel='stylesheet' type='text/css' href='styles/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='jquery/script.js'></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) : <br><br><input id='text' type="text" name="mess" value="">
<button id='button1' type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br>
<div id="box_holder"></div>
<br><br>
<button id='button2' type='button' name='button2' onclick="redirect()">Start Your Adventure</button>
</body>
</html>
JS:
$(document).ready(function() {
$('#button1').click(function(){
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
chooseChar = function () {
var text = document.getElementById('text').value;
var text = text.toLowerCase();
if(text == 'human') {
$(document).ready(function() {
$('#button1').click(function(){
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function(){
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text+".html";
window.location.href = url;
}
So your variable send gets sent and then it clears out the input field with either of those functions
$(document).ready(function() {
$('#button1').click(function(){
$('#box_holder').children('p').remove(); <===========
or Either of these should work
$('#box_holder').empty(); <===========================
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
Instead of using append, try using html as follows
$('#box_holder').html('<p>'+ 'You have chosen your character to be: '+send+'</p>');
Here is a Plunkr to explain it a little better
$(document).ready(function() {
$('#button1').click(function() {
var send = $("input[name=mess]").val();
$('#box_holder').html('<p>' + 'You have chosen your character to be: ' + send + '</p>');
});
$('input').css("color", "blue");
});
chooseChar = function() {
var text = document.getElementById('text').value;
text = text.toLowerCase();
if (text == 'human') {
$(document).ready(function() {
$('#button1').click(function() {
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function() {
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text + ".html";
window.location.href = url;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) :
<br />
<br />
<input id="text" type="text" name="mess" value="" />
<button id="button1" type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br />
<div id="box_holder"></div>
<br />
<br />
<button id="button2" type="button" name="button2" onclick="redirect()">Start Your Adventure</button>
</body>
</html>
You have to remember, the append() function appends the content on the selected component. The html() function replaces all content inside of it.
Hope it helps

Detect if a textbox does not contain certain words

I want to know how to detect if a textbox does not contain certain words. For example if the textbox did not contain 'who', 'what', 'why', 'when' or 'where' some sort of function would run.
JavaScript:
function command() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
var t = srch;
if (srch == '') {
alert('Please do not leave the field empty!');
}
else if (srch.indexOf('time') != -1) {
alert('The current time according to your computer is' + ShowTime(new Date()));
}
else if (srch.indexOf('old are you') != -1) {
alert("I am as old as you want me to be.");
}
else {
if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
window.open('https://google.co.uk/#q=' + srch, '_blank');
}
else { /* Nothing */ }
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
</div>
</body>
</html>
You will want to call that function when you press a button.
Try something in your HTML like:
<input class="info" onclick="contains();" type="button">
And in your JS
function contains() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
if (
(srch.indexOf('who')==-1) &&
(srch.indexOf('what')==-1) &&
(srch.indexOf('why')==-1) &&
(srch.indexOf('when')==-1) &&
(srch.indexOf('where')==-1)
) {
alert("That is not a question");
}
}
You will want to merge this with your command() function in the future.
Also, what does info(); do ?

Check Passwords Match Issue (JavaScript)

can anybody see the issue with the following code? My script continues, ignoring my check.
The code below is only a snippet of the code but this issue is in here somewhere after doing some debugging.
function validatePasswordMatch(string1, string2) {
if (string1 != string2) {
return false;
} else {
return true;
}
}
var validatePasswordMatchFields = ["textbox2", "textbox3"];
if (validatePasswordMatch($("#" + validatePasswordMatchFields[0]).val(), $("#" + validatePasswordMatchFields[1]).val())) {
(some code)
} else {
return false;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>stackoverflow</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
function validatePasswordMatch(string1, string2) {
if (string1 !== string2) {
return false;
} else {
return true;
}
}
var validatePasswordMatchFields = ["textbox2", "textbox3"];
$(document).on('click','button',function(){
result = validatePasswordMatch($("#" + validatePasswordMatchFields[0]).val(), $("#" + validatePasswordMatchFields[1]).val())
if (result) {
alert("match")
} else {
alert("not match")
}
})
});
</script>
</head>
<body>
<input id="textbox2" type="text" placeholder="password">
<input id="textbox3" type="text" placeholder="password">
<button type="button" id="button">Click Me!</button>
</html>

Categories