How can I do simple validation of a dropdown list? - javascript

I've made a 'question-answer form' in HTML and linked it with Javascript so that people could answer with a specific number. Here is the sample of my code:
HTML code:
<p>Question</p>
<p>1)"ans1"</p>
<p>2)"ans2"</p>
<p>3)"ans3"</p>
<p>4)"ans4"</p>
<form method="POST" name="CorrectForm"
onSubmit="checkCorrect(document.CorrectForm.numCorrect.value); return false;">
<input type="text" name="numCorrect" id="numCorrect">
<input type="Submit" name="Submit">
</form>
JavaScript:
var correctnumber = 1;
var errormessage = "blabla";
function checkTrue (numTrue){
if (numCorrect == correctNumber){
alert("Correct")
}else{
alert(errormessage);
}
}
Now what I want is to let people choose an answer from a dropdown list. So I want the answers to be checked when the submit button is pressed.
So, HTML looks like
<p>Question</p>
<select>
<option value="ans1">ans1</option>
<option value="ans2">ans2</option>
<option value="ans3">ans3</option>
<option value="ans4">ans4</option>
</select>
So now I'm need of the JS part.
I apologize if this question has been asked a million times before, as I tried searching for a solution but didn't find one.
Thanks in advance!

Instead of creating a function that validates just the input number, you can create a function that validates the full form. See this example:
<!DOCTYPE html>
<html>
<head>
<title>Validation test</title>
<script>
var rightAnswer = 3;
function checkAnswer(form) {
if (parseInt(form.elements["answer"].value) == rightAnswer) {
alert("Correct");
} else {
alert("Wrong");
}
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="checkAnswer(this); return false;">
<p>Question:</p>
<select name="answer">
<option value="1">ans1</option>
<option value="2">ans2</option>
<option value="3">ans3</option>
<option value="4">ans4</option>
</select>
<input type="submit">
</form>
</body>
</html>
Some remarks:
In the code for the event onsubmit="", you can use the keywork this to refer to the form itself, and pass it to the checkAnswer() function.
When you have the variable form that points to your HTML form, you can retrieve its fields through form.elements["NAME"], where NAME matches the attribute name="" in the HTML tag. This works for all controls, select, button, input, with the exception of <input type="image">.
See MDN about this, it contains good reference about every object in the HTML DOM, in particular <select>.
You might still need to convert the value to an integer to be able to compare it to your right answer, that's the reason for parseInt.
This approach can be generalized: what you want to do is equivalent to form validation, you can find online plenty of libraries and tutorials that explain in detail how to do it; there are also many answers, if you know what to look for.

Related

javascript : document.getElementById("xxx") won't works [duplicate]

This question already has answers here:
What is the difference between JavaScript's getElementById() and getElementsByName() functions?
(6 answers)
Closed 5 years ago.
I have a form below, which in the "select option" will trigger the function selectType(), I found that the function selectType() has been ran, because the alert works and show in the screen, then the "document.getElementById("selectType").submit();" seems won't works, because it wont go to the url I expected.
Edited at 2017/02/26 : Thanks for the answer.
I found that if the form inside "#using (Html.BeginForm())", then the "document.getElementById("selectType").submit();" won't works, if the form is outside the "#using (Html.BeginForm())", it works.
<script>
function selectType() {
alert("aa");
document.getElementById("selectType").submit();
}
</script>
<form id="selectType" action="/TRecords/Audit">
<input type="text" name="id" class="dateInput" value=#ViewBag.SId hidden>
<select onchange="selectType();" name="auditType" class="form-control">
<option>Select Type</option>
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
<option value=4>D</option>
</select>
</form>
You almost got it right but this line:
<form name="selectType" action="/TRecords/Audit">.
Need to be change for that:
<form id="selectType" action="/TRecords/Audit">
Just change 'name' to 'id'.
<form id="selectType" action="/TRecords/Audit">
In order to use 'getElementById' method your need to access using 'id' attribute.
"document.getElementById("selectType").submit();" seems won't works
Because you have set name of form to be selectType and not id.
Either set <form id="selectType">..</form>
Or if name is must, then use document.getElementsByName('selectType')[0].submit();
Thanks for the answer.
I found that if the form inside #using (Html.BeginForm()) then the document.getElementById("selectType").submit(); won't work. If the form is outside #using (Html.BeginForm()) it works.

Adding object data to html form fields

Below is my simple form html where I want to add the object data to my form fields. I went through Google search and StackOverflow but all of them were talking about jquery implementation, so here is my simple form html where I want to add the object data to my form fields. Since I'm not aware of Jquery, I want to use the Java Script approach.
Below, I have a user form where I want to bind the details object to my above form fields, so for that I'm using the below java script approach. I don't know where I'm going wrong. My object data is not getting bound with my form. 
So kindly help me with it.
Thank you.
<!DOCTYPE html>
<html>
<body>
<div>
<form>
Name&nbsp<input id="name" type="text" name="name"><br>
Place&nbsp<input id="place" type="text" name="place"><br>
Age&nbsp<input id="age" type="text" name="age">
</form>
</div>
<script>
var details ={name:'Krishna',place:'India',age:26};
document.getElementById("name").innerHTML=details.name;
document.getElementById("place").innerHTML=details.palce;
document.getElementById("age").innerHTML=details.age;
</script>
</body>
</html>
As mentioned in the comment by #Jaromanda X, there is no innerHTML for an input field. Instead, you should try setting the value attribute.
<script>
var details ={name:'Krishna',place:'India',age:26};
document.getElementById("name").value = details.name;
document.getElementById("place").value = details.place;
document.getElementById("age").value = details.age;
</script>
This should do the trick.

How to validate bootstrap multiselect dropdown using jquery

I am trying to validate Bootstrap multiselect dropdown using the code given below, the form is getting validated but i did'nt get the proper output, the
validation message is above the selectbox and the message gets multiplied when
clicking on the submit button and after selecting option the message did'nt gets removed. Please help to solve my problem.
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("needsSelection", function (value, element) {
var count = $(element).find('option:selected').length;
return count > 0;
});
$.validator.messages.needsSelection = 'Select Atleast One College';
$("#User").validate({
rules: {
'college[]': {
needsSelection: true
}
},
}
});
$("#submit").click(function(e) {
var isvalidate=$("#User").valid();
if(isvalidate=="true")
{
}
else
{
$("#User").submit();
}
});
});
<form id="User" name="User" method="post" enctype="multipart/form-data" action="index">
<select data-placeholder="Choose College Name" name="college[]" class="chosen-select" id="college" multiple tabindex="4">
<option value=""></option>
<option value="1">abc</option>
<option value="2">abc1</option>
</select>
<a id="submit">Submit</a>
</form>
This is not a direct answer to your question, but may provide a solution to your problem.
First, change the anchor tag to a button -- because anchor tags have built-in navigation behaviour that you must counter (event.preventDefault()) and therefore add needless complexity. How about a button (input or button tags) or a div tag, or a p?)
Next, a simpler structure to evaluating your form:
jsFiddle Demo
HTML: (just changed your anchor submit button to:
<input id="dosubmit" type="submit" value="Submit" />
Note: do not use "submit" as the id for a submit button, as that is a reserved keyword
javascript/jQuery:
$('#User').submit(function(e){
var col = $('#college').val();
if ( col==null || col=='' || col=='Please choose one:' ){
$('#college').css('background','yellow').focus();
return false;
}else{
$('#college').css('background','transparent');
alert('Form submitted');
//continue to submit the form - but not now
return false;
}
});
Please consider this verification script for your project.
This is not an answer to your question but I will advise you and encourage you to use a server-side validation together.
Your data should be validate and as needed sanitzed on the php file that receives the ajax call.
If something is going wrong there, the response will always be passed back to your form giving your users the needed feedback.
You can find many examples on the internet of how to do this.
See here an example: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
So to recap: Dont't do client-side validation!!

How to navigate to other php pages using drop down list?

I am having trouble trying to figure out how to navigate to different web pages using a drop down list and submit. I have three forms:
main.php
two.php
three.php
In my main.php page I have a drop down list consisting of only two options 'second' and 'third'. How can I use these two options to navigate to other php pages? For example, if I selected the option 'two' and click submit, the page should then take me to the second.php page. And if I select option 'three', I will be taken to the third.php page.
Also, once I am directed to one of the php pages, how can I then be able to go back to the 'main.php' page if I decide to go to the other php page instead? (I thought perhaps the use of a back button).
Below is part of my 'main.php' page:
<label>Select the page you wish to go:</label></td>
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select></td>
On <select></select> value change :
HTML :
<select name="pages" onChange="my_function(this)">
JavaScript :
function my_function(element){
document.location.href = element.value
}
Example
On <button></button> click :
HTML :
<button onClick="my_function()"></button>
JavaScript :
function my_function(){
document.location.href = document.querySelector('select[name="pages"]').value
}
Example
You can do multiple things. If you dont wan't to rely on javascript, make the form submit to a file like router.php.
inside router.php put:
<?php
if (isset($_POST['pages']) {
header('Location: ' . $_POST['pages']);
}
Which will effectively forward the request to the page you submitted in the select.
You also have to change your html a bit:
<label>Select the page you wish to go:</label></td>
<form method="post" action="router.php">
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select>
<input type="submit" value="go there" />
</form>
If you are fine with javascript go with #notulysses's answer, its way easier and quicker.
Using POST values directly in a header method is kinda nasty imo.
Jquery solution
HTML CODE:
<form id="frm" method="post" action="" >
<label>Select the page you wish to go:</label>
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select>
<input type="submit" name="sub" value="Finish" />
</form>
JQUERY CODE
$('#frm').on('submit',function () {
var nextPage= $('select option:selected').val();
$(this).attr('action',nextPage);
return true;
});
Happy Coding :)

Update HTML form with Javascript while typing

I can update an HTML form using Javascript, when the user hits enter when on something on the form or when he triggers the onclick event on the "submit" button, but I want the form to be updated while the user is typing something.
I know that I can do Infinity loop, yet it is not a good idea; or I can check after intervals but it will cause unnecessary checking, which I don't want.
Use keyUp event handler with the input field contained within your form.
References: Javascript,
jQuery
[UPDATE]
You missed round brackets at function definition, check the updated fiddle
I had the same question and based on this post and sohel's answer I managed to get it working. Now I would like to share my solution in form of a short working example: If you type your name in the first field it will suggest an email address in the second one.
<!DOCTYPE html>
<html>
<head>
<script>
function nameModify(emailElement, nameElement) {
emailElement.value = nameElement.value + '#stackoverflow.com';
}
</script>
</head>
<body>
<form name="aform" action="#">
<input type="text" name="name" onkeyup="nameModify(this.form.elements['email'], this);" >
<input type="text" name="email" >
</form>
</body>
</html>
You are looking for Autocomplete

Categories