Displaying Validation Error in Span for Drop Down Menu - javascript

I'm trying to validate a select menu I have on my page. If the first option is selected(the one with no value)and clicks the submit button, then I want to either display a span next to the menu or display the span under the menu. The span should tell the user to select an option (male/female). I'm having trouble doing either of these things. Is span not the correct thing to use here?
Note on possible duplicate: I read some of the answers posted on Stack similar to this question but some used JQuery which I have not learned yet. There was one answer that used Javascript which I tried to follow. It used a function with parameters and errorPlacement but I was having trouble understanding it and wanted to do it in a simpler way. There were other questions I looked as well, but I'm listing one for now.
Here is the link to the question: Problem with display error message in span element when validation
Also I'd specially like to use span tags if possible then prepend & append.
Here is my code:
HTML
<form onsubmit="return Validate();">
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
JAVASCRIPT
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
var gendererror = document.createElement("span");
gendererror.innerHTML = "please select a gender";
return false;
}
return true;
}

I think this is what you want. Always have a error-msg div to give styles to your errors.
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
if(!document.getElementById("error-msg").childNodes.length){
var gendererror = document.createElement("span");
gendererror.innerHTML = "please select a gender";
document.getElementById("error-msg").appendChild(gendererror);
}
return false;
}else{
return true
}
}
<form onsubmit="return Validate();" action="#">
<div id="error-msg"></div>
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
<script type="text/javascript" src="./jsfile.js"></script>

I think why you didn't get error message is because, javascript is confuse where to put the created tag and its content. You might have forgot to appendChild with some tag, so that javascript knows where to put created tag
Html:-
<form onsubmit="return Validate();">
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
Just below, Script:-
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
var relationshiperror = document.createElement("span");
document.body.appendChild(relationshiperror); // You can add to any new div for example, also after submit button
relationshiperror.innerHTML = "Please select the type of relationship";
return false;
}
return true;
}

Related

Check string in select option

I have created with javascript and I get a result of a string.I get that result on my html code
<div id="results"></div>
Next,I want when I select for example Red to check if it is the the same thing (string), the select option - > Red with the string of this code
<div id="results"></div>
I was trying to do it but I failed.It is not working not even sure ,if I press the submit button I will send the string.
<div id="results"></div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="submit" value="results"/>
It appears that you want to check whether the selected option is equal to the text value of the div #results. You can achieve this effect like so:
$(document).ready(function(){
var select = $("select");
$("input[type=\"button\"]").click(function(){
var text = select.find(":selected").text();
if(text==$("#results").text()){
$("#results").html(text+" is equal!");
}else{
$("#results").html(text+" is not equal :(");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results">Red</div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="button" value="results"/>
</form>
A form is going to be Sending data somewhere, it would be best to remove the form, leaving the select and button elements. In the button add the code onclick='myFunction() ; when the button is clicked it will run the javascript function called myFunction(). Also you need to give the select a Id. I'm using selectInput
<script>myFunction() { document.getElementById('result').innerHTML = document.getElementById('selectInput').value;} </script>
Now when ever the button is pressed it will set the content of the div equal to the value entity in the selected select box option
You lack an action attribute.
<form method="post" action="path/to/file">
<select name="select">
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input type="submit" value="Get Results" />
</form>
Use a function, and a regular button. No form is needed.
<button onclick='func()'></button>
const func = () => {...}

I can't get the value of my select element when i have a hidden field that is revealed if an option is selected

I have a select form element with various options. One of the options is "other". So when "other" is selected a hidden field is displayed for the user to enter the value not on the list. All that works fine. The problem is when a user selects any of the other options and submits the form, the value is not passed. Whereas, if the "other" option is selected and fills the text box then submits the form, the value of the text box is passed.
this is the select and the hidden text field:
<select name="memo" required class="newtxtbox" id="memo" onchange='checkvalue()'>
<option disabled="disabled" selected="selected">Select</option>
<option value="Donation for Bulletin">Bulletin</option>
<option value="Donation for Care Ministry">Care Ministry</option>
<option value="Donation for Cathedral Choir">Cathedral Choir</option>
<option value="Donation for Other">Other - (please specify below) </option>
</select>
<input type="text" style="display:none" name="memo" id="other">
and this is JavaScript:
function checkvalue()
{
if(document.getElementById('memo').value == 'Donation for Other') {
document.getElementById('other').style.display='block';
}
else {
document.getElementById('other').style.display='none';
}
}
I am sure i am missing something small but can't figure out what it is.
Here is a visual example of a small workaround. What I did was simply changing the name attribute of each element. I have added a CSS rule that displays the element with name="memo" as blue. The element that is blue will be sent to the server.
I have also expanded the javascript code so that you can test it out here on SO. You don't have to include the code after // added for testing purpose in your code. Click on "run code snippet" and try the submit button.
function checkvalue() {
var select = document.getElementById('memo');
var input = document.getElementById('other');
if (select.value == 'Donation for Other') {
document.getElementById('other').style.display = 'block';
select.name = '';
input.name = 'memo'; // form `memo` will now contain this input
} else {
document.getElementById('other').style.display = 'none';
select.name = 'memo';
input.name = '';
}
}
// added for testing purpose
document.getElementById('test').addEventListener('submit', function(e) {
e.preventDefault(); // no no submit
// FormData is HTML5 js object that contains ... data from the form ...
var fd = new FormData(this);
// .entries() isn't widely supported yet.
for (var tuple of fd.entries()) {
console.log(tuple[0] + ' contains value "' + tuple[1] + '"');
}
});
/*
added this for visibility of changes
element that is blue is being sent
*/
input[name="memo"],
select[name="memo"] {
background-color: lightblue;
}
<form id="test">
<select name="memo" required class="newtxtbox" id="memo" onchange='checkvalue()'>
<option disabled="disabled" selected="selected">Select</option>
<option value="Donation for Bulletin">Bulletin</option>
<option value="Donation for Care Ministry">Care Ministry</option>
<option value="Donation for Cathedral Choir">Cathedral Choir</option>
<option value="Donation for Other">Other - (please specify below) </option>
</select>
<input type="text" style="display:none" id="other">
<input type="submit" value="submit" />
</form>

getElementbyId for items in a div

So I've been having trouble understanding why my "document.getElementbyID()" function is breaking my external script. My script and html file look like this:
function validateRegCat(obj)
{
setRegCat(obj);
var invalid = false;
if(obj.value == "Invalid")
{
alert("Please select a Registration category")
invalid = true;
}
return invalid;
}
function setRegCat(obj)
{
if(obj.value == "UWSStudent")
{
document.getElementbyId("Institution").value = "The University of Western Sydney";
document.getElementbyId("Institution").readOnly = true;
}
}
<body>
<form class="Application" action"prac1task3Form.asp" method="post" onsubmit="return finalValidate(this);" >
<div class="PersonalDetails">
<fieldset>
<legend>
<h3>Personal Details</h3>
</legend>
<!--Kept in a list to keep the form looking neat and organised-->
<ul>
<li>
<!-- Create a selection box for the user to input their Registration Category-->
<label for="RegCat"><strong>Registration Category:</strong><sup>*</sup></label>
<select name="RegCat" size="1" onblur="validateRegCat(this); setRegCat(this)" required>
<option value = "Invalid">--Choose a registration category--</option>
<option value = "UWSStudent">UWS Student</option>
<option value = "OtherStudent">Student at another Institution</option>
<option value = "UWSAcademic">UWS Academic</option>
<option value = "UWSStaff">UWS Staff</option>
<option value = "OtherAcademic">Academic from another Institution</option>
<option value = "PublicMember">Member of the public</option>
<option value = "Retired">Retired</option>
</select>
</li>
<!-- Input Institution. Sets automatically to Uws and readonly if certain registration categorys are selected-->
<li>
<label for="Institution"><strong>Institution of learning/work:</strong> </label>
<input type="text" name="Institution" id="Institution" size="30" maxlength="30"/>
</li>
</ul>
</fieldset>
</div>
</form>
</body>
I've cut the html down to only the relevant parts. What I want the script to do is to change the value of the "Institution" text input to read only and set the text displayed. However I've found that the "document.getElementbyId("Institution")" breaks the script. The script runs fine before that and when I change those lines to meaningless things such as alerts, the script functions and returns as it should.
I assume the problem is related to typos (make sure you have capital 'B' instead of 'b'): document.getElementById (https://developer.mozilla.org/it/docs/Web/API/Document/getElementById).
If you use Firebug (http://getfirebug.com/) or similar while developing you can detect these small errors easily.

Save input text while switching between <option> tag

I have a text input, alongside I have option tag with two options.
Basically I want to save the text that the user enters while switching between options, but if the user choose an option that he already enterd a text the text should appear in the input field as the default value.
And of course it's part of the submit form.
Many thanks in advance!
<div>
<p>please enter your description for each of the languages</p>
<input id="description" type="text">
<select id="language-select">
<option value="EN">EN</option>
<option value="FR">FR</option>
</select>
</div>
You can use local storage for this if you want to persist what is saved, otherwise a variable would be good enough.
Example with variable
var previous;
var state = {};
$("#language").on('focus', function() {
previous = $(this).val()
}).change(function() {
state[previous] = $("#test").val();
$("#test").val('');
if (typeof(state[$(this).val()]) != 'undefined') {
$("#test").val(state[$(this).val()]);
}
$("#test").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="test" id="test" />
<select id="language">
<option val="en">EN</option>
<option val="fr">FR</option>
</select>
</form>

Check dropdown before submit

I use this code to check if dropdown opton is selected before submit.
On my page I have 3 dropdown menus, but only the first works correctly.
Is there a way to extend function for the 2nd and 3rd dropdowns?
My script:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var year = $('#year option:selected').val();
if(year == "")
{
$("#msg").html("Please select a year");
return false;
}
});
});
</script>
My HTML:
<div id="msg"></div>
<form method="post" action="">
<select id="year">
<option value="">OLLA</option>
<option>1991 </option>
<option>1992 </option>
<option>1993 </option>
<option>1994 </option>
<option>1995 </option>
</select>
<div id="msg"></div>
<form method="post" action="">
<select id="year">
<option value="">OLLA</option>
<option>1991 </option>
<option>1992 </option>
<option>1993 </option>
<option>1994 </option>
<option>1995 </option>
</select>
<input type="submit" name="submit" id="submit">
</form>
ID's should be unique and only used once. I advise you to give them all the class msg instead, e.g.
<div class="msg"></div>
...
<div class="msg"></div>
Also, give your selects a class too instead, for the same reason, both:
<select class="year">
Your jQuery would also be changed to:
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(){
var year = $('.year option:selected').val();
if(year == "") {
$(".msg").html("Please select a year");
return false;
}
});
});
</script>
If you put the listener on the form, it will be this within the function so you can just do something like:
$("<form selector>").click(function(){
if (this.year.value == "") {
$("#msg").html("Please select a year");
return false;
} else {
$("#msg").html("");
}
})
You could also check whether the selected index is greater than zero. If it's zero or -1, then either the first or no option is selected (respsectively).
You should turn the ID attributes into NAME attributes, then you can repeat them (and they will be successful when the form is submitted).
Oh, and never name a form control "submit" as it will shadow the form's submit method, making it impossible to call it.
Because Ids of both element are same so selector works with first id match this case .Try to use different ids or USe Class Instead of ID
or use the jquery each function http://api.jquery.com/each/
You could, of course, set an action on the DDL to ensure that a value has been set (enabling the submit button afterwards) thus putting the emphasis of validation directly on the control itself, rather than the submit button. (Just another way of skinning the same cat!)

Categories