Is there a way to check if an user input from text box (for example) exists in an array that I created and imported from other JS files?
And can I link all that code to an HTML button?
In Python to do this I use "in":
if a in List:
print("That's In")
PS: I know that List in Python are a little different with Arrays in JavaScript.
From my platform's JavaScript documentation:
//Use:
if (in_array('a', ['a','b',4,'z'])) {console.log('item in array.');}
//Prerequisite functions:
function in_array(s,a)
{
var r = false;
if (is_array(a))
{
for (var i = 0; i<a.length; i++)
{
if (a[i]==s) {r = true;}
}
}
else {console.log('Error: object to in_array ('+a+') is not an array.');
}
return r;
}
function is_array(a)
{
return ((a.constructor.toString().indexOf('Array') > 0) ? true : false);
}
Thanks for all, i think that i resolved my problem with array.indexOf
There's my solution below
How can i close the post ?
<!DOCTYPE html>
<form id="form" onsubmit="return false;">
<input style="position:absolute" type="text" id="userInput" /> <br>
<input style="position:absolute;" type="submit" onclick="name();" /> <br>
<script type="text/javascript">
function name() {
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var input = document.getElementById("userInput").value;
//Check if a value exists in the data1 array
if(fruits.indexOf(input) !== -1){
document.write(input, " Value exists!");
document.write(" Press F5 to reload")
} else{
document.write(input, " Value does not exists!");
document.write(" Press F5 to reload");
}
}
</script>
</form>
</html>
Related
I've read through many posts, and tried various options, but my validation check on my JavaScript doesn't seem to be running.
I used this post to try and write a validation check to see if the entered zip code is one one delivered to, but when I run it nothing happens and neither alert shows up. Any help is appreciated.
This is the JavaScript I was using:
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes)){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
This is the form
<form name="zipForm" onsubmit="return(validateForm(zipCode))">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
function validateZip() {
var zipCode = document.zipForm.zipCode.value;
var acceptableZipCodes = ["78205","72215","78212",];
for (i = 0; i < cars.acceptableZipCodes.length; i++) {
if(acceptableZipCodes[i] == zipCode{
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
}
There are 2 mistakes I found.
1, you define the function validateZip, but you didn't call it in the script.
2, inArray() function will be return the position of the value in the array, so when a value doesnt in the array, it will return -1.
I do some changes in the code.
Hope it help you.
<form name="zipForm" onsubmit="return(validateZip())">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes) !== -1){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
I would use an ID instead of name attribute for your form tag (for a quicker retrieval).
<form id="zipForm">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
Then below, I would do this:
<script>
$(function() {
// add an event handler to your form (look at adeneo's comment)
$('#zipForm').on('submit', function(e) {
// prevent form from submitting
e.preventDefault();
// call your function
validateZip($("#zipCode").val());
});
function validateZip(zipCode) {
var acceptableZipCodes = ["78205", "72215", "78212"];
// be careful with using $.inArray as the return value for no
// matches is -1 (and not false)
if ($.inArray(zipCode, acceptableZipCodes) != -1) {
alert("Yes, we can help!");
} else {
alert("Sorry, we don't deliever to your area yet.");
}
}
});
</script>
You should check if it's begger than -1:
if($.inArray( zipCode, acceptableZipCodes) > -1)
Here a jsfiddle example: JSFiddle
I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>
I'm trying to prevent the form being submitted if the validation fails, however its not working at the moment. The onclick method is used for hidden input, but its the onsubmit method that is failing. Any ideas?
<input type="submit" class="btn ccm-input-submit" id="register" name="register" value="Register" onsubmit="return validation(this)" onclick="copytextbox()"/>
<?php echo $form->hidden('rcID', $rcID); ?>
<script>
function copytextbox()
{
var textToCopy = document.getElementById('school').value;
var whereToCopy = document.getElementById('<?php echo $school ?>');
whereToCopy.value += textToCopy;
}
function validation(f)
{
var schoolText = document.getElementById('school').value;
if (schoolText == '') {
alert('Please Choose a value from the dropdown box.');
return false; // stop submission until textbox is not ''
} else {
f.submit();
return false;
}
}
</script>
Also, im attempting to see if that value is a member of an array, I tried using indexOf(schoolText) etc but this also failed, kind regards
Move your onsubmit="return validation(this)" attribute from the <input> tag to the <form> tag.
Test an array like this:
// global array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function findFruit(val) {
if(fruits.indexOf(val) == -1 {
alert('not found');
} else {
alert('Found!')
}
}
findFruit('Peach'); // not found
<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length
Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/